In this tutorial we will be building a digital asset portfolio tracking tool using python and the Coinbase API.
You’ll need to install python and the following library to make requests.
pip install requests
The code for this is open source on Github at: https://github.com/jamesbachini/Python-Portfolio-Tracker
Put this in a file called portfolio.py or fork the repo above.
import requests
import time
portfolio = {
'BTC': 1.5, # Amount of Bitcoin you own
'ETH': 26, # Amount of Ethereum you own
# Add more cryptocurrencies here
}
# Note some tokens aren't available on Coinbase
def get_crypto_price(ticker):
url = f'https://api.coinbase.com/v2/prices/{ticker}-USD/spot'
response = requests.get(url)
data = response.json()
return float(data['data']['amount'])
def display_portfolio(portfolio):
print(f"----------------------------------------------------------\n")
total_value = 0.0
for ticker, amount in portfolio.items():
price = get_crypto_price(ticker)
value = amount * price
total_value += value
print(f"{ticker}: ${price:.2f} (You own {amount} {ticker}, Value: ${value:.2f})")
print(f"Total Portfolio Value: ${total_value:.2f}\n")
def main():
while True:
display_portfolio(portfolio)
time.sleep(30)
if __name__ == "__main__":
main()
Then adjust the portfolio variable on line 4 with your current holdings making sure anything you add is on coinbase and there’s a spot market API for it.
Then run the script…
python portfolio.py
This will update your portfolio every 30 seconds so you can see your net worth depreciating before your eyes #fun
You could take this further by adding stocks, shares and whatever else you can get a price feed for. I hope you’ve enjoyed this tutorial and subscribe to the newsletter to stay in touch.