当我运行此文件以将比特币数据从交易所提取为 JSON 格式时:
import os
import pytz
from datetime import datetime
import json
from catalyst.api import record, symbol, symbols
from catalyst.utils.run_algo import run_algorithm
def initialize(context):
# Portfolio assets list
context.asset = symbol('btc_usd') # Bitcoin on Bitfinex
def handle_data(context, data):
# Variables to record for a given asset: price and volume
currentTimeString = str(data.current_dt)
currentData = {
'open': data.current(context.asset, 'open'),
'high': data.current(context.asset, 'high'),
'low': data.current(context.asset, 'low'),
'close': data.current(context.asset, 'close'),
'volume': data.current(context.asset, 'volume'),
}
context.allData[currentTimeString] = currentData
def analyze(context=None, results=None):
# Generate DataFrame with Price and Volume only
data = results[['open','high','low','close','price','volume']]
# Save results in CSV file
# filename = os.path.splitext(os.path.basename(__file__))[0]
# data.to_csv(filename + '.csv')
with open('data.json', 'w') as outfile:
json.dump(context.allData, outfile)
''' Bitcoin data is available on Poloniex since 2015-3-1.
Dates vary for other tokens. In the example below, we choose the
full month of July of 2017.
'''
start = datetime(2018, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime(2018, 1, 31, 0, 0, 0, 0, pytz.utc)
results = run_algorithm(initialize=initialize,
handle_data=handle_data,
analyze=analyze,
start=start,
end=end,
exchange_name='bitfinex',
capital_base=10000,
quote_currency = 'usd')
我收到以下错误:
File "C:/Users/XYZ/Code/grabdata.py", line 31, in handle_data
context.allData[currentTimeString] = currentData
AttributeError: 'ExchangeTradingAlgorithmBacktest' object has no attribute 'allData'
编辑:最初发布了错误的错误代码,现在已更新。
我的代码中是否有错误,或者我在初始化时缺少对 context.allData 的引用?我试图通过从文件中读取而不是从交换中获取来加速回测,这似乎需要很长时间。使用由 Quantopian/Zipline 构建的催化剂框架:https ://enigma.co/catalyst/index.html