详解 Zipline 1 basics

最近很多量化回测平台的涌现让zipline又火了一把,断断续续用了一段时间,现在来深入玩一下:

格式很简单,三段式:

1. 数据

2. algo

3. run

 

首先要跑起来,找到example里面buyapple的例子,从yahoo返回的data格式如下,跟自己写的从wind返回数据的函数功能基本一致。

                AAPL
Date
2014-01-02 00:00:00+00:00 77.39
2014-01-03 00:00:00+00:00 75.69
2014-01-06 00:00:00+00:00 76.10
2014-01-07 00:00:00+00:00 75.56
2014-01-08 00:00:00+00:00 76.04

 

数据这部分搞定。

 

algo部分,运行速度很慢,光是建立起来花了113s,跟pyalgo根本不能比,必须要优化才能用。

if self.sim_params is None:
            self.sim_params = create_simulation_parameters(
                capital_base=self.capital_base
            )

创建simu params的速度太慢了,跟进去,发现

    sim_params = SimulationParameters(
        period_start=start,
        period_end=end,
        capital_base=capital_base,
        sids=sids,
        data_frequency=data_frequency,
        emission_rate=emission_rate,
    )

在这个class里面self._update_internal()方法调用了tardingenvironment的instance,初始化就慢在这里了

    @classmethod
    def instance(cls):
        global environment
        if not environment:
            environment = TradingEnvironment()

        return environment
    def __init__(
        self,
        load=None,
        bm_symbol='^GSPC',
        exchange_tz="US/Eastern",
        max_date=None,
        env_trading_calendar=tradingcalendar
    )

 

问题出在读取index数据和rf的数据上,必须让它读取本地的csi300和国债利率,而且还要能更新,是个问题。

这个load_market_data里面有两大消耗时间的函数

update_benchmarks(symbol, last_date)它要从网络更新新的index data points

>>> benchmark_returns.head()
1950-01-03 00:00:00+00:00    0.000000
1950-01-04 00:00:00+00:00    0.011405
1950-01-05 00:00:00+00:00    0.004748
1950-01-06 00:00:00+00:00    0.002953
1950-01-09 00:00:00+00:00    0.005889

dump_treasury_curves(module, filename),这货时间太长了都是做同样的操作,从网络上追加新数据,先不看了,后续会把这些改为从wind上更新数据。

本来是应该patch里面的update_benchmarks方法的,但是我先在173行的改一下

days_up_to_now = trading_days[:most_recent_index] # csz patch

这样不会影响太大,如果当天更新了就没影响,或者不用今天的数据回测。

 

尼玛迅速运行完毕,但是使用中国的stock测试会出现问题,应该是curve的问题,太晚了,回头再写。

 

TODO:

直连wind重写load_market_data

# components. To set the environment, you can set the property on
# the module directly:
# from zipline.finance import trading
# trading.environment = TradingEnvironment()
#
# or if you want to switch the environment for a limited context
# you can use a TradingEnvironment in a with clause:
# lse = TradingEnvironment(bm_index="^FTSE", exchange_tz="Europe/London")
# with lse:
# the code here will have lse as the global trading.environment
# algo.run(start, end)

 

posted on 2015-09-23 23:13  surghost  阅读(1031)  评论(1编辑  收藏  举报

导航