- (주의) zipline은 현재(21-12-23) python 2.7 / 3.5 / 3.6만을 지원함.
# import
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
from zipline.api import order, symbol
from zipline.algorithm import TradingAlgorithm
# data
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2016, 3, 19)
data = web.DataReader("AAPL", "yahoo", start, end)
# 백테스트를 위해서 데이터 필터링
# 종가 데이터만 있으면 됨
data = data[['Adj Close']]
# columns 명 수정
data.columns = ['AAPL']
# 시간을 UTC 시로 변경
data = data.tz_localize('UTC')
# 초기값을 딱히 설정할 것이 없다면 pass
def initialize(context):
pass
def handle_data(context, data):
# 매일 AAPL을 한 주 씩 산다는 명령
order(symbol('AAPL'), 1)
"""
starting_cash ending_cash ending_value
2010-01-04 21:00:00 100000.000000 100000.000000 0.000000
2010-01-05 21:00:00 100000.000000 99971.104604 27.895396
2010-01-06 21:00:00 99971.104604 99942.652921 54.903366
2010-01-07 21:00:00 99942.652921 99914.251985 82.202808
2010-01-08 21:00:00 99914.251985 99885.668879 110.332424
"""
# 알고리즘 시작
algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
result = algo.run(data)
# result.portfolio_value = ending_cash + ending_value
# 를 의미한다
plt.plot(result.index, result.portfolio_value)
plt.show()
Example-2
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
from zipline.api import order_target, record, symbol
from zipline.algorithm import TradingAlgorithm
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2016, 3, 29)
data = web.DataReader("AAPL", "yahoo", start, end)
#plt.plot(data.index, data['Adj Close'])
#plt.show()
data = data[['Adj Close']]
data.columns = ['AAPL']
data = data.tz_localize('UTC')
#print(data.head())
def initialize(context):
context.i = 0
context.sym = symbol('AAPL')
def handle_data(context, data):
context.i += 1
# 20일 평균선을 기준으로 하기에 20일 전까지는 모두 return처리
if context.i < 20:
return
ma5 = data.history(context.sym, 'price', 5, '1d').mean()
ma20 = data.history(context.sym, 'price', 20, '1d').mean()
if ma5 > ma20:
order_target(context.sym, 1)
else:
order_target(context.sym, -1)
record(AAPL=data.current(context.sym, "price"), ma5=ma5, ma20=ma20)
algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
result = algo.run(data)