如何更新已弃用的python zipline.transforms模块?

时间:2017-09-21 14:46:21

标签: python zipline

我使用quantopian zipline包http://www.zipline.io/beginner-tutorial.html编写了一个python程序。我最近更新了包,并且遇到了不推荐使用zipline.transforms包的问题。我使用了zipline.transforms包中的两个函数batch_transform()MovingAverage

除了用batch_transform函数替换history()之外,我还没有找到一篇好文章来演示如何解决这个问题。但是,我不知道如何更换它。我还没找到一篇帖子告诉我们如何解决MovingAverage弃用问题。

这是我正在使用的代码。

from zipline.algorithm import TradingAlgorithm
from zipline.transforms import batch_transform
from zipline.transforms import MovingAverage


class TradingStrategy(TradingAlgorithm):

    def initialize(self, window_length=6):
        self.add_transform(
            MovingAverage, 'kernel', ['price'], window_length=self.window_length)

    @batch_transform
    def get_data(data, context):
        '''
        Collector for some days of historical prices.
        '''
        daily_prices = data.price[STOCKS + [BENCHMARK]]
        return daily_prices

strategy = TradingStrategy()

有人可以提供一个如何更新上述代码的示例吗?我假设有很多人在处理有关流行的quantopian的问题。

1 个答案:

答案 0 :(得分:4)

似乎没有直接的方式来使用history 而不是 batch_transform

在我看来,不仅方法有所改变,而且它们的使用方式也完全改变了。

文档提到以下内容:

  

每个zipline算法都包含两个您必须定义的函数:

  • initialize(context)
  • handle_data(context, data)

以下是使用历史记录方法创建一些基本移动平均线的文档示例:

def initialize(context):
    context.i = 0
    context.asset = symbol('AAPL')


def handle_data(context, data):
    # Skip first 300 days to get full windows
    context.i += 1
    if context.i < 300:
        return

    # Compute averages
    # data.history() has to be called with the same params
    # from above and returns a pandas dataframe.
    short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean()
    long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()

    # Trading logic
    if short_mavg > long_mavg:
        # order_target orders as many shares as needed to
        # achieve the desired number of shares.
        order_target(context.asset, 100)
    elif short_mavg < long_mavg:
        order_target(context.asset, 0)

    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           short_mavg=short_mavg,
           long_mavg=long_mavg)