James Bachini

Building A Portfolio Tracker In Python

Python Portfolio

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

Python Portfolio Tracker

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.


Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.