Skip to content

zipline A 股文档

zhanghan1990 edited this page Apr 7, 2017 · 9 revisions

开始写策略

先写一个简单而完整的策略

import pandas as pd
from zipline import TradingAlgorithm
from zipline.api import order, sid,get_datetime
from zipline.data.loader import load_data
from zipline.api import order_target, record, symbol, history, add_history,symbol,set_commission,order_percent,set_long_only,get_open_orders
from zipline.finance.commission import OrderCost
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

input_data = load_data(
    stockList=['002057'],
    start="2015-11-04",
    end="2016-01-16"
)
def analyze(context=None, results=None):
    import matplotlib.pyplot as plt

    # Plot the portfolio and asset data.
    ax1 = plt.subplot(211)
    results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'策略收益')
    ax1.set_ylabel(u'收益')
    results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'基准收益')

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()



def initialize(context):
    context.has_ordered = False
    set_commission(OrderCost(open_tax=0,close_tax=0.001,open_commission=0.0003,close_commission=0.0003,close_today_commission=0,min_commission=5))
    set_long_only()

def handle_data(context, data):

    #输出每天持仓情况

    if not context.has_ordered:
        for stock in data:
            closeprice=history(5,'1d','close')
            #-2:昨天,-3 前天.-4 大前天
            print get_datetime(),closeprice[sid(stock)][0],closeprice[sid(stock)][1],closeprice[sid(stock)][2],closeprice[sid(stock)][3],closeprice[sid(stock)][4]
            if closeprice[sid(stock)][-2]>closeprice[sid(stock)][-3] and closeprice[sid(stock)][-3]>closeprice[sid(stock)][-4]:
                print "buy",get_datetime()
                order(stock, 300)
            elif closeprice[sid(stock)][-2]<closeprice[sid(stock)][-3] and closeprice[sid(stock)][-3]<closeprice[sid(stock)][-4]:
                print "sell",get_datetime()
                order(stock, -300)


algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data,capital_base=10000,benchmark='399004')



results = algo.run(input_data)
print results
analyze(results=results)

用户需要实现的几个函数:

  • load_data(stockList,start,end)
input_data = load_data(
    stockList=['002057'],
    start="2000-11-04",
    end="2016-01-16"
)

stockList 为股票池,类型为List,start是回测起始时间,end是回测结束时间, 其中几个特殊的stockList列表:

'hz300':沪深300
'zz500': 中证500
'sz50': 上证50
'all': 所有股票
  • initialize(context),策略初始化函数,可以初始化一些变量,滑点和手续费模型需要在本函数中设置

  • handle_data(context, data) 为策略执行函数,当前系统只支持日级别测试,因此本函数每天执行一次,执行时间为开盘时间,context为策略上下文,在context中可以定义

  • TradingAlgorithm(initialize=func, handle_data=func,capital_base=10000,benchmark='399004'), capital_base为起始本金,benchmark为基准收益,当前benchmark 支持指数如下:

000001: 上证指数
000300:沪深300
000002: 上证A股指数
000003: B股指数
000004: 上证工业指数
000005: 上证商业指数
000006: 上证地产指数
000007: 上证公用指数
000008: 上证综合指数
000009:上证380
000010: 上证180
000016:上证50
000017: 新综指
000020:中型企业指数
000032: 上证能源
000033: 上证材料
000034: 上证工业
000035: 上证可选
000036: 上证消费
000037: 上证医药
000038: 上证金融
000039: 上证信息
000040: 上证电信
000041: 上证共用
000043: 上证超大盘
000044: 上证中盘
000045: 上证小盘
000046: 上证中小
000047: 上证全指
000090: 上证流通
000104: 上证380能源
000105: 上证380材料
000106: 上证380工业
000107: 上证380可选消费
000108: 上证380消费
000109: 上证380医药卫生
000110: 上证380金融地产
000111: 上证380信息
000112: 上证380电信
000113: 上证380共用
000132: 上证100
000133: 上证150
000155: 上证市值百强
000852:中证1000
000903: 中证100
000904: 中证200
000905: 中证500
000906: 中证800
399001: 深圳成指
399002:深圳A股
399003:深圳B股
399004:深证100
399005:中小板指数
399006:创业板指数
399007:中小价格指数
399008:中小300
399009:深圳200
399010:深证700
399011:深证1000
399012:创业板300
399015:深证中小创新指数
399300:深圳 HS300
399303:中证 100
399304:中证中盘200
399304:中证小盘500
  • history(5,'1d','close'):获取最近5天的收盘价,返回值为 dataframe. closeprice[sid(stock)][-1] 获取今天收盘价,closeprice[sid(stock)][-2] 获取昨天收盘价,closeprice[sid(stock)][-2] 获取前天收盘价,依次类推
  • order(stock, N):买入stock N 股,N>0,为买入,N<0 为卖出,交易的价格为当天的开盘价

均线策略

import pandas as pd
from zipline import TradingAlgorithm
from zipline.api import order, sid,get_datetime
from zipline.data.loader import load_data
from zipline.api import order_target, record, \
symbol, history, add_history,symbol,set_commission,order_percent,set_long_only,get_open_orders,order_value,order_target

from zipline.finance.commission import OrderCost
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
import pytz
from datetime import datetime, timedelta


input_data = load_data(
    stockList=['000001'],
    start="2014-11-04",
    end="2016-01-16"
)


# 初始化函数,设定要操作的股票、基准等等
def initialize(context):
    # 定义一个全局变量, 保存要操作的股票
    # 000001(股票:平安银行)
    context.security = '000001'

# 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次
def handle_data(context, data):
    # 获取股票的收盘价
    close_data = history(12,'1d','close')
    # 取得过去五天的平均价格
    ma5 = close_data[-6:-2].mean()
    # 取得过去10天的平均价格
    ma10 = close_data[-11:-2].mean()
    # 取得当前的现金

    print get_datetime(),ma5,ma10
    cash = context.portfolio.cash
    
    #print ma5[sid(symbol(context.security))],ma10[sid(stock)],cash,symbol(context.security)
    #如果当前有余额,并且五日均线大于十日均线
    if ma5[sid(symbol(context.security))] > ma10[sid(symbol(context.security))]:
         order_value(symbol(context.security), cash)
    # 如果五日均线小于十日均线,并且目前有头寸
    elif ma5[sid(symbol(context.security))] < ma10[sid(symbol(context.security))]:
        # 全部卖出
        order_target(symbol(context.security), 0)
        # 记录这次卖出
        #log.info("Selling %s" % (context.security))

    #record(short_mavg=ma)

    # # 绘制五日均线价格
    # record(ma5=ma5)
    # # 绘制十日均线价格
    # record(ma10=ma10)
def analyze(context=None, results=None):
    import matplotlib.pyplot as plt
    import logbook
    logbook.StderrHandler().push_application()
    log = logbook.Logger('Algorithm')

    fig = plt.figure()
    ax1 = fig.add_subplot(211)

    results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'策略收益')
    ax1.set_ylabel(u'收益')
    results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'基准收益')

    plt.show()

# capital_base is the base value of capital
#
algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data,capital_base=10000,benchmark='000300')

#print input_data
#api: print all the api function
#print algo.all_api_methods()
results = algo.run(input_data)
#print results['benchmark_period_return'],results['portfolio_value']
analyze(results=results)
  • order_value(symbol(context.security), cash):用cash多现金,买入security 股,交易的价格为当天的开盘价。
  • symbol(context.security):symbol函数,把股票的代码,转换成系统内对股票识别的标志。
  • order_target(symbol(context.security), N): 把股票价格调整到N,N=0,把这只股都卖出。

选股策略

import pandas as pd
from zipline import TradingAlgorithm
from zipline.api import order, sid,get_datetime
from zipline.data.loader import load_data
from zipline.api import order_target, record, symbol, history, add_history,symbol,set_commission,order_percent,set_long_only,get_open_orders,run_monthly,run_weekly
from zipline.finance.commission import OrderCost
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False



def analyze(context=None, results=None):
    import matplotlib.pyplot as plt

    # Plot the portfolio and asset data.
    ax1 = plt.subplot(211)
    results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'策略收益')
    ax1.set_ylabel(u'收益')
    results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'基准收益')

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()



# loading the data
input_data = load_data(
    stockList= ['000001','000002','000004','000005'],
    start="2013-11-01",
    end="2016-01-16"
)


def initialize(context):
    # 初始化此策略
    # 设置我们要操作的股票池
    context.stocks = ['000001','000002','000004','000005']



# 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次
def handle_data(context, data):
    
    # context.i+=1
    # if context.i<=5:
    #     return
    # 循环每只股票

    closeprice= history(5,'1d','close')
    for security in context.stocks:
        vwap=(closeprice[symbol(security)][-2]+closeprice[symbol(security)][-3]+closeprice[symbol(security)][-4])/3
        price = closeprice[symbol(security)][-2]
        print get_datetime(),security,vwap,price
        # # 如果上一时间点价格小于三天平均价*0.995,并且持有该股票,卖出
        if price < vwap * 0.995:
            # 下入卖出单
            order(symbol(security),-300)
            print get_datetime(),("Selling %s" % (security))
            # 记录这次卖出
            #log.info("Selling %s" % (security))
        # 如果上一时间点价格大于三天平均价*1.005,并且有现金余额,买入
        elif price > vwap * 1.005:
            # 下入买入单
            order(symbol(security),300)
            # 记录这次买入
            print get_datetime(),("Buying %s" % (security))
            #log.info("Buying %s" % (security))


algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data,capital_base=100000,benchmark='000300')

#print input_data
#api: print all the api function
#print algo.all_api_methods()
results = algo.run(input_data)
#print results['benchmark_period_return'],results['portfolio_value']
analyze(results=results)

  • input_data = load_data(stockList= ['000001','000002','000004','000005'],start="2013-11-01",end="2016-01-16"),开始加载需要的股票池(可以自己定义,也可以使用系统内置的几个股票池)
  • handle_data 内部轮动操作,找到每天符合买入条件的股票买入和卖出