Zipline Pythonic 交易算法库 项目简介
Zipline 是一个 Pythonic 算法交易库。 它是一个事件驱动的系统,支持回测检验和实时交易。Zipline 目前在生产中用作 Quantopian(托管平台) 的测试和实时交易引擎。特性使用简单,以便你可以专注于算法开发带有许多常见的统计数据,包括常用统计方法如移动平均和线性回归历史数据的输入和性能统计的输出基于 Pandas DataFrames,与现有 python 生态圈能很好融合一些常用统计和机器学习库,如 matplotlib、scipy、statsmodels 和 sklearn,支持交易系统的开发、数据分析和可视化快速开始下面的代码实现了一个简单的双重移动平均算法。from zipline.api import (
history,
order_target,
record,
symbol,
)
def initialize(context):
context.i = 0
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
sym = symbol('AAPL')
# Trading logic
if short_mavg[sym] > long_mavg[sym]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(sym, 100)
elif short_mavg[sym] < long_mavg[sym]:
order_target(sym, 0)
# Save values for later inspection
record(AAPL=data[sym].price,
short_mavg=short_mavg[sym],
long_mavg=long_mavg[sym])
history,
order_target,
record,
symbol,
)
def initialize(context):
context.i = 0
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
sym = symbol('AAPL')
# Trading logic
if short_mavg[sym] > long_mavg[sym]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(sym, 100)
elif short_mavg[sym] < long_mavg[sym]:
order_target(sym, 0)
# Save values for later inspection
record(AAPL=data[sym].price,
short_mavg=short_mavg[sym],
long_mavg=long_mavg[sym])