1

我成功地使用以下代码输出几个小时前的历史价格数据的每分钟价格:

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()

向 Cryptocompare API 的家伙们竖起大拇指。

最终,我想实现以下目标:

1) 输出两个时间戳之间的每分钟价格,例如 3/12/18 3.00pm (15.00) 和 3/12/18 3.30pm (15.30)

2)我想将此数据保存为 3 列“令牌”(在 BTC 以上的情况下)、“时间戳”、“价格”,最好是 csv 或 json

任何人对如何使用给定的代码或替代方法有一个或两个想法?

4

1 回答 1

0

所以要回答第一部分,您可以为您想要的间隔创建两个时间戳最小值和最大值:

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

然后创建一个mask以仅选择df这两次之间的行:

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

现在,如果您这样做df[mask],您将只获得时间戳在这 30 分钟窗口内的行。

对于第二个问题:

# 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')

如果你想添加面具,然后做

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

编辑 json,这取决于你想要它的方式,所以我建议阅读有关 to_json 的文档以查找可能的内容

于 2018-05-26T23:48:54.413 回答