Search code examples
pythonpython-3.xpandascryptocurrency

Historical price per minute between two timestamps for a cryptocurrency


I am successfully using the following code to output the price per minute for historical price data ranging back a couple of hours:

import requests
import datetime
import pandas as pd
import matplotlib.pyplot as plt

def minute_price_historical(symbol, comparison_symbol, limit, aggregate, exchange=''):
    url = 'https://min-api.cryptocompare.com/data/histominute?fsym={}&tsym={}&limit={}&aggregate={}'\
        .format(symbol.upper(), comparison_symbol.upper(), limit, aggregate)
    if exchange:
        url += '&e={}'.format(exchange)
    page = requests.get(url)
    data = page.json()['Data']
    df = pd.DataFrame(data)
    df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]
    return df

time_delta = 1 # Bar width in minutes
df = minute_price_historical('BTC', 'USD', 9999, time_delta)
print('Max length = %s' % len(df))
print('Max time = %s' % (df.timestamp.max() - df.timestamp.min()))

plt.plot(df.timestamp, df.close)
plt.xticks(rotation=45)
plt.show()

Thumbs up to the Cryptocompare API guys.

Ultimately, I would like to achieve the following:

1) Output the price per minute between two timestamps, e.g. 3/12/18 3.00pm (15.00) and 3/12/18 3.30pm (15.30)

2) I would like to save this data into 3 columns "Token"(in the case above BTC), "Timestamp", "Price" as a csv or json ideally

Anyone with an idea or two on how to do that with the given code or an alternative approach?


Solution

  • so to answer the first part, you can create two timestamp min and max for the interval you want:

    time_min = pd.Timestamp('2018-05-26 15:00')
    time_max = pd.Timestamp('2018-05-26 15:30')
    

    and then create a mask to select only the rows of your df between this two times:

    mask = (df.timestamp >= time_min) & (df.timestamp <= time_max)
    

    Now if you do df[mask] you will get only the rows where the timestamp is within this 30 min window.

    For the second question:

    # you can first create the column for the token do:
    df['token'] = 'BTC' # should fill all the rows of your df with this word
    # rename the column close to price
    df = df.rename(columns={'close':'price'})
    # finally save as csv only the columns you want:
    df[['token','timestamp','price']].to_csv('here_the_path_to_your/file.csv')
    

    and if you want to add the mask, then do

    df[['token','timestamp','price']][mask].to_csv('here_the_path_to_your/file.csv')
    

    EDIT for the json, it depends how you want it, so I would suggest to read the documentation about to_json to find what is possible