I wrote a python program using the quantopian zipline package http://www.zipline.io/beginner-tutorial.html. I recently updated the package and have encountered that the zipline.transforms package is deprecated. I was using two functions from the zipline.transforms package, batch_transform()
and MovingAverage
.
I haven't been able to find a good post demonstrating how to fix this, other than saying to replace batch_transform
with the history()
function. However, I am unaware how exactly to replace it. I haven't found a post telling how to fix the MovingAverage deprecation.
Here is my code I am using.
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()
Could someone provide an example of how to update the code above? I assume there are many people dealing with the issues given how popular quantopian is.
There doesn't seem to be a direct way to use history
instead of batch_transform
.
It looks to me that not only were the methods changed, but the way in which they are intended to be used were completely changed also.
The documentation mentions the following:
Every zipline algorithm consists of two functions you have to define:
initialize(context)
handle_data(context, data)
Here's an example from the docs of using the history method to create some basic moving averages:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With