I’m trying to import cryptocurrency minute data and do zipline-reloaded backtesting, and now I’ve completed bundle registration and collection. And now it’s time to run run_algorithm, but my current version of zipline-reloaded says that the results of run_algorithm only output daily performance. (Check run_algorithm’s internal function, check perf)
I want to get perf based on minute instead of daily through run_algorithm.
Below is my code and version
Package Version
---------------------------- --------------------
absl-py 1.3.0
aiodns 3.1.1
aiohttp 3.9.1
aiosignal 1.3.1
alembic 1.9.1
alphalens 0.4.0
anyio 3.6.2
appdirs 1.4.4
argon2-cffi 21.3.0
argon2-cffi-bindings 21.2.0
asttokens 2.1.0
astunparse 1.6.3
async-timeout 4.0.3
attrs 22.1.0
backcall 0.2.0
Backtesting 0.3.3
bcolz-zipline 1.2.6
beautifulsoup4 4.11.1
bleach 5.0.1
blosc2 2.0.0
bokeh 3.1.1
Bottleneck 1.3.5
cachetools 5.2.0
catboost 1.1.1
ccxt 4.1.99
certifi 2022.12.7
cffi 1.15.1
chardet 3.0.4
charset-normalizer 3.0.1
click 8.1.3
cloudpickle 2.2.0
contourpy 1.0.6
cryptography 39.0.0
cvxpy 1.3.0
cycler 0.11.0
Cython 0.29.33
DateTime 5.4
dbus-python 1.2.16
debugpy 1.6.3
decorator 5.1.1
defusedxml 0.7.1
Deprecated 1.2.14
ecos 2.0.12
empyrical 0.5.5
empyrical-reloaded 0.5.9
entrypoints 0.4
exchange-calendars 3.3
executing 1.2.0
fastjsonschema 2.16.2
finance-datareader 0.9.50
flatbuffers 22.10.26
fonttools 4.38.0
frozendict 2.3.4
frozenlist 1.4.1
funcsigs 1.0.2
gast 0.4.0
google-auth 2.14.1
google-auth-oauthlib 0.4.6
google-pasta 0.2.0
graphviz 0.20.1
greenlet 2.0.1
grpcio 1.50.0
h5py 3.7.0
html5lib 1.1
idna 2.8
importlib-metadata 5.0.0
importlib-resources 5.10.0
intervaltree 3.1.0
ipykernel 5.1.1
ipython 8.6.0
ipython-genutils 0.2.0
ipywidgets 8.0.2
iso3166 2.0.2
iso4217 1.11.20220401
jedi 0.17.2
Jinja2 3.1.2
joblib 1.2.0
jsonschema 4.17.0
jupyter 1.0.0
jupyter_client 7.4.7
jupyter-console 6.4.4
jupyter_core 5.0.0
jupyter-http-over-ws 0.0.8
jupyter-server 1.23.2
jupyterlab-pygments 0.2.2
jupyterlab-widgets 3.0.3
keras 2.11.0
kiwisolver 1.4.4
korean-lunar-calendar 0.3.1
koreanize-matplotlib 0.1.1
libclang 14.0.6
lightgbm 3.3.4
llvmlite 0.39.1
Logbook 1.5.3
loguru 0.7.2
lru-dict 1.1.8
lxml 4.9.2
Mako 1.2.4
Markdown 3.4.1
MarkupSafe 2.1.1
matplotlib 3.5.3
matplotlib-inline 0.1.6
mistune 2.0.4
mock 5.0.1
msgpack 1.0.4
multidict 6.0.4
multipledispatch 0.6.0
multitasking 0.0.11
nbclassic 0.4.8
nbclient 0.7.0
nbconvert 7.2.5
nbformat 4.4.0
nest-asyncio 1.5.6
networkx 3.0
notebook 6.5.2
notebook_shim 0.2.2
numba 0.56.4
numexpr 2.8.4
numpy 1.23.3
oauthlib 3.2.2
OpenDartReader 0.2.1
opt-einsum 3.3.0
osqp 0.6.2.post8
packaging 21.3
pandas 1.5.3
pandas-datareader 0.10.0
pandas-ta 0.3.14b0
pandocfilters 1.5.0
parso 0.7.1
patsy 0.5.3
peewee 3.17.0
pexpect 4.8.0
pickleshare 0.7.5
Pillow 9.3.0
pip 23.3.2
pkgutil_resolve_name 1.3.10
platformdirs 2.5.4
plotly 5.11.0
prometheus-client 0.15.0
prompt-toolkit 3.0.32
protobuf 3.19.6
psutil 5.9.4
psycopg2-binary 2.9.9
ptyprocess 0.7.0
pure-eval 0.2.2
py-cpuinfo 9.0.0
pyasn1 0.4.8
pyasn1-modules 0.2.8
pycares 4.4.0
pycparser 2.21
pyfolio 0.9.2+75.g4b901f6
pyfolio-reloaded 0.9.3
Pygments 2.13.0
PyGObject 3.36.0
pykrx 1.0.45
pyluach 2.0.2
pyparsing 3.0.9
pyportfolioopt 1.5.4
pyrsistent 0.19.2
python-apt 2.0.1+ubuntu0.20.4.1
python-bitget 1.0.7
python-dateutil 2.8.2
python-interface 1.6.1
pytz 2022.7
PyYAML 6.0.1
pyzmq 24.0.1
qdldl 0.1.5.post3
qtconsole 5.4.0
QtPy 2.3.0
requests 2.31.0
requests-file 1.5.1
requests-oauthlib 1.3.1
requests-unixsocket 0.2.0
rsa 4.9
scikit-learn 0.24.2
scipy 1.10.0
scs 3.2.2
seaborn 0.12.2
Send2Trash 1.8.0
setuptools 64.0.2
shap 0.41.0
six 1.14.0
slicer 0.0.7
sniffio 1.3.0
sortedcontainers 2.4.0
soupsieve 2.3.2.post1
SQLAlchemy 1.4.51
stack-data 0.6.1
statsmodels 0.13.5
TA-Lib 0.4.25
tables 3.6.1
tenacity 8.1.0
tensorboard 2.11.0
tensorboard-data-server 0.6.1
tensorboard-plugin-wit 1.8.1
tensorflow 2.11.0
tensorflow-estimator 2.11.0
tensorflow-io-gcs-filesystem 0.27.0
termcolor 2.1.0
terminado 0.17.0
threadpoolctl 3.1.0
tinycss2 1.2.1
toolz 0.12.0
tornado 6.2
tqdm 4.64.1
trading-calendars 2.1.1
traitlets 5.5.0
typing_extensions 4.9.0
tzdata 2023.4
urllib3 1.25.8
wcwidth 0.2.5
webencodings 0.5.1
websocket-client 1.4.2
websockets 12.0
Werkzeug 2.2.2
wheel 0.34.2
widgetsnbextension 4.0.3
wrapt 1.14.1
xgboost 1.7.3
xlrd 2.0.1
xyzservices 2023.10.1
yahoofinancials 1.20
yarl 1.9.4
yfinance 0.2.3
zipline-reloaded 2.2.0
zipp 3.10.0
zope.interface 6.1
from zipline.api import order_target_percent, symbol
from zipline import run_algorithm
from zipline.utils.calendar_utils import get_calendar
import pandas as pd
import talib
import plotly.graph_objects as go
def initialize(context):
context.asset = symbol('BTCUSDT') # 백테스팅할 자산 설정
# 이전 N분 데이터 가져오기
context.window = 120 # 분석할 윈도우 크기 설정
context.data_list = [] # 분 단위 데이터를 저장할 리스트 초기화
def handle_data(context, data):
prices = data.history(context.asset, ['high', 'low', 'close', 'volume'], context.window, '1m')
# VWAP, RSI 및 Bollinger Bands 계산
typical_price = (prices['high'] + prices['low'] + prices['close']) / 3
vwap = (typical_price * prices['volume']).cumsum() / prices['volume'].cumsum()
rsi = talib.RSI(prices['close'], timeperiod=14)
upperband, middleband, lowerband = talib.BBANDS(prices['close'], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
# 현재 가격 가져오기
current_price = data.current(context.asset, 'price')
# 매수 신호: 현재 가격이 VWAP 아래이고, RSI < 30, Bollinger 하위 밴드 아래
buy_signal = current_price < vwap[-1] and rsi[-1] < 30 and current_price < lowerband[-1]
# 매도 신호: 현재 가격이 VWAP 위이고, RSI > 70, Bollinger 상위 밴드 위
sell_signal = current_price > vwap[-1] and rsi[-1] > 70 and current_price > upperband[-1]
# 분 단위 데이터 기록
context.data_list.append({
'time': data.current_dt,
'vwap': vwap[-1],
'rsi': rsi[-1],
'upperband': upperband[-1],
'lowerband': lowerband[-1],
'current_price': current_price,
'buy_signal': buy_signal,
'sell_signal': sell_signal
})
# 주문 실행
if buy_signal:
order_target_percent(context.asset, 0.1)
elif sell_signal:
order_target_percent(context.asset, -0.1)
def analyze(context, perf):
# 리스트를 DataFrame으로 변환
minute_data = pd.DataFrame(context.data_list)
# 매수 및 매도 신호 표시를 위한 데이터 필터링
buy_signals = minute_data[minute_data['buy_signal']]
sell_signals = minute_data[minute_data['sell_signal']]
# 가격 및 VWAP 차트 생성
price_vwap_chart = go.Figure()
price_vwap_chart.add_trace(go.Scatter(x=minute_data['time'], y=minute_data['current_price'], mode='lines', name='Price'))
price_vwap_chart.add_trace(go.Scatter(x=minute_data['time'], y=minute_data['vwap'], mode='lines', name='VWAP'))
# 매수 신호 추가
price_vwap_chart.add_trace(go.Scatter(x=buy_signals['time'], y=buy_signals['current_price'], mode='markers', name='Buy Signal', marker=dict(color='green', size=10)))
# 매도 신호 추가
price_vwap_chart.add_trace(go.Scatter(x=sell_signals['time'], y=sell_signals['current_price'], mode='markers', name='Sell Signal', marker=dict(color='red', size=10)))
price_vwap_chart.update_layout(title='Price and VWAP with Buy/Sell Signals', xaxis_title='Time', yaxis_title='Price')
# RSI 차트 생성
rsi_chart = go.Figure()
rsi_chart.add_trace(go.Scatter(x=minute_data['time'], y=minute_data['rsi'], mode='lines', name='RSI'))
rsi_chart.add_hline(y=70, line_dash="dash", line_color="red")
rsi_chart.add_hline(y=30, line_dash="dash", line_color="green")
rsi_chart.update_layout(title='RSI', xaxis_title='Time', yaxis_title='RSI')
# 차트 표시
price_vwap_chart.show()
rsi_chart.show()
# 저장
minute_data.to_csv('minute_backtest_results.csv', index = 0)
# 백테스팅 실행
perf = run_algorithm(
start=pd.Timestamp('2023-12-15', tz='UTC'),
end=pd.Timestamp('2023-12-20', tz='UTC'),
initialize=initialize,
handle_data=handle_data,
analyze=analyze,
trading_calendar=get_calendar('24/7'),
capital_base=40000,
data_frequency='minute',
bundle='btcusdt_12to31'
)