Sling Academy
Home/Python/Building a Crypto Portfolio Tracker Using pycoingecko

Building a Crypto Portfolio Tracker Using pycoingecko

Last updated: December 22, 2024

In recent years, cryptocurrencies have gained significant popularity, resulting in a growing need for tools that help investors track and manage their crypto assets. One such tool is a crypto portfolio tracker, which allows users to monitor the value and performance of their cryptocurrency holdings in real-time. In this tutorial, we will build a simple crypto portfolio tracker using Python and the pycoingecko library, a convenient wrapper around the CoinGecko API.

Setup and Installation

Before we start coding, let's set up our environment. Make sure you have Python 3 installed on your computer. You can download it from the official Python website if you haven't already. Once Python is installed, you'll need to install the pycoingecko library. This can be done using pip:


pip install pycoingecko

With the pycoingecko library installed, we're ready to start building our crypto portfolio tracker.

Fetching Cryptocurrency Data

The first step in building our portfolio tracker is to fetch the latest cryptocurrency pricing data. We'll use the pycoingecko library to get this information from the CoinGecko API. Let's start by writing a function that retrieves data for specific cryptocurrencies:


from pycoingecko import CoinGeckoAPI

def fetch_crypto_data(crypto_ids):
    cg = CoinGeckoAPI()
    return cg.get_price(ids=crypto_ids, vs_currencies='usd')

# Example usage:
crypto_list = ['bitcoin', 'ethereum', 'cardano']
crypto_prices = fetch_crypto_data(crypto_list)
print(crypto_prices)

In the above code, we import the CoinGeckoAPI class from the pycoingecko library and create a function called fetch_crypto_data. This function takes a list of cryptocurrency IDs as an argument and returns their current prices in USD.

Building the Portfolio Tracker

With the ability to fetch current prices, we can now move on to building the core functionality of our portfolio tracker. This involves maintaining a list of the user's holdings and calculating the total value of their portfolio. Let's define a simple data structure for user holdings and implement a function to calculate the total value:


def calculate_portfolio_value(holdings):
    crypto_ids = list(holdings.keys())
    prices = fetch_crypto_data(crypto_ids)
    total_value = 0

    for crypto, amount in holdings.items():
        if crypto in prices:
            total_value += prices[crypto]['usd'] * amount

    return total_value

# Example usage:
user_holdings = {
    'bitcoin': 0.5,
    'ethereum': 2,
    'cardano': 1500
}

total_value = calculate_portfolio_value(user_holdings)
print(f'Total portfolio value: ${total_value:.2f}')

In this section of the code, we define a function called calculate_portfolio_value that takes a dictionary of user holdings as input. Each key in the dictionary represents a cryptocurrency ID, and its corresponding value is the amount held by the user. The function then uses our fetch_crypto_data function to retrieve current prices and calculates the total portfolio value.

Improving Usability

To enhance the usability of our crypto portfolio tracker, we can add features such as saving and loading portfolio data from a file, and displaying detailed asset information. For demonstration purposes, here's how to implement saving and loading the portfolio using a JSON file:


import json

def save_portfolio(holdings, filename='portfolio.json'):
    with open(filename, 'w') as f:
        json.dump(holdings, f)

def load_portfolio(filename='portfolio.json'):
    try:
        with open(filename, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

# Example usage:
# Save user holdings
save_portfolio(user_holdings)

# Load holdings
loaded_holdings = load_portfolio()
print(f'Loaded portfolio: {loaded_holdings}')

In the code above, we use Python's built-in json module to handle reading and writing JSON files. The save_portfolio function saves the current holdings to a file, while the load_portfolio function loads holdings from a file.

Conclusion

We've covered the essentials of building a simple crypto portfolio tracker using Python and the pycoingecko library. This tutorial illustrates how to fetch cryptocurrency prices via an API and calculate the total value of a portfolio. You can further enhance this project by adding features such as portfolio analytics, alerts for significant price changes, and integration with other data sources. In the fast-paced world of cryptocurrencies, having the ability to manage one's investments proactively can be invaluable.

Next Article: Comparing pycoingecko to cryptocompare: Pros and Cons

Previous Article: Integrating pycoingecko with TA-Lib for Indicator Analysis

Series: Algorithmic trading with Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots