How Do You Retrieve Cryptocurrency Data for One Day in the Past Using Python?

Problem scenario
You want to find the historic data for a given cryptocurrency using Python. You want to print out the low, high, open and close prices on a specific day. How do you get data for one specific date?

Solution

Prerequisite
This assumes you have installed pandas: pip install pandas

Procedures
Run this program:

"""
Usage instructions: Change the "2016-12-25" the value (assigned to "date_to_see") to the day you want to view.
Change "BTC" to the symbol of the cryptocurrency you want to examine.
You may or may note want to change "USD" or "Coinbase"

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

from_symbol = 'BTC'
to_symbol = 'USD'
exchange = 'Coinbase'      # "Bitstamp" and "Coinbase" are valid among others.
datetime_interval = 'day'
date_to_see="2016-12-25"

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('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):
    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
    return df


file_creator(from_symbol, to_symbol, exchange, datetime_interval)

latest_date = datetime.now().date().isoformat() 
df_btc = read_dataset(get_filename(from_symbol, to_symbol, exchange, datetime_interval, latest_date))
btc_date = open((get_filename(from_symbol, to_symbol, exchange, datetime_interval, latest_date)), 'r')
get_top = btc_date.read()[0:-1]


print("This prints out data for one cryptocurrency on one day.  It downloads a file first.")
print(" ")
print("Here is data for " + from_symbol + " for " + date_to_see + ":")

print(get_top.split('\n')[0])
for line in get_top.split():
    if line.split(",")[0] == date_to_see:
        print(line)

For aggregate data over a date range, see this posting.


If you sign up for Coinbase for the first time, you often can get up to $200 in free coins; 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 *