How Do You Print Out Aggregate Cryptocurrency Information Based on a Date Range?

Problem scenario
You want to print out the average cryptocurrency price along with the minimum and maximum prices based on a range of dates. What do you do?

Solution
This solution only goes back to 2015 for BTC. For other cryptocurrencies, the oldest price data is usually more recent than that.

Prerequisite
This assumes you have installed pandas: pip install pandas
If you need assistance installing pip, see this posting.

Procedures
Run this Python program; you may change the exchange to the one of your choice, the currency symbols to the cryptocurrency symbol of your choice, and the "to_symbol" to the currency of your choice.

"""
Written in March of 2021 by www.continualintegration.com

It was adapted from these postings:
https://towardsdatascience.com/cryptocurrency-analysis-with-python-buy-and-hold-c3b0bc164ffa
https://towardsdatascience.com/cryptocurrency-analysis-with-python-macd-452ceb251d7c?gi=12b983021ac2


"""

import pandas as pd
import requests
from datetime import datetime

def get_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date):
    return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol, exchange, datetime_interval, download_date)

def download_data(from_symbol, to_symbol, exchange, datetime_interval):
    supported_intervals = {'minute', 'hour', 'day'}
    print('Downloading %s trading data for %s %s from %s' %
          (datetime_interval, from_symbol, to_symbol, exchange))
    base_url = 'https://min-api.cryptocompare.com/data/histo'
    url = '%s%s' % (base_url, datetime_interval)    
    params = {'fsym': from_symbol, 'tsym': to_symbol,
              'limit': 2000, 'aggregate': 1,
              'e': exchange}
    request = requests.get(url, params=params)
    data = request.json()
    return data

def convert_to_dataframe(data):
    df = pd.json_normalize(data, ['Data'])
    df['datetime'] = pd.to_datetime(df.time, unit='s')
    df = df[['datetime', 'low', 'high', 'open',
             'close', 'volumefrom', 'volumeto']]
    return df

def filter_empty_datapoints(df):
    indices = df[df.sum(axis=1) == 0].index
    print('Filtering %d empty datapoints' % indices.shape[0])
    df = df.drop(indices)
    return df

def file_creator(from_symbol, to_symbol, exchange, datetime_interval):
    data = download_data(from_symbol, to_symbol, exchange, datetime_interval)
    df = convert_to_dataframe(data)
    df = filter_empty_datapoints(df)
    latest_date = datetime.now().date().isoformat() 
    filename = get_filename(from_symbol, to_symbol, exchange, datetime_interval, latest_date)
    #print('Saving data to %s' % filename)
    print('The oldest day in the range obtained for ' + from_symbol + ' was ' + str(df['datetime'].min()))
    df.to_csv(filename, index=False)


def get_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date):
    return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol, exchange, datetime_interval, download_date)

def read_dataset(filename):
    #print('Reading data from %s' % filename)
    df = pd.read_csv(filename)
    df.datetime = pd.to_datetime(df.datetime) # change to datetime
    df = df.set_index('datetime') 
    df = df.sort_index() # sort by datetime
    #print(df.shape)
    return df

print("This prints out aggregated data for certain cryptocurrencies.  It downloads files first.")

from_symbol = 'BTC'
to_symbol = 'USD'
exchange = 'Coinbase'      # "Bitstamp" and "Coinbase" are valid among others.
datetime_interval = 'day'
file_creator(from_symbol, to_symbol, exchange, datetime_interval)

from_symbol = 'ETH'
file_creator(from_symbol, to_symbol, exchange, datetime_interval)

from_symbol = 'LTC'
file_creator(from_symbol, to_symbol, exchange, datetime_interval)

latest_date = datetime.now().date().isoformat() 
df_btc = read_dataset(get_filename('BTC', to_symbol, exchange, datetime_interval, latest_date))
df_eth = read_dataset(get_filename('ETH', to_symbol, exchange, datetime_interval, latest_date))
df_ltc = read_dataset(get_filename('LTC', to_symbol, exchange, datetime_interval, latest_date))

df = pd.DataFrame({'BTC': df_btc.close,
                   'ETH': df_eth.close,
                   'LTC': df_ltc.close}) 

print(" ")

print(df.describe())

If you want to receive free cryptocurrency by just learning more, try Coinbase; it is ideal for Americans. For Europeans, the platform/company Iconomi.com can allow you to buy crypto or learn more.

Leave a comment

Your email address will not be published. Required fields are marked *