I'm trying to implement history function instead of @batch_transform in the code below. Does anyone know how to achieve the same functionality with history?
'''
Implementation of the trading system described here:
http://systemtradersuccess.com/vix-rsi/
The Rules
1. Price must be above its 200-day moving average
2. RSI(2) on price must be below 30
3. Buy when RSI(2) of the VIX is above 90
4. Exit when RSI(2) of the price rises above 65
'''
import numpy as np
import talib
@batch_transform(window_length=200, refresh_period=0)
def _history(data):
return data
def initialize(context):
# Quandl URL for VIX data
url ='http://www.quandl.com/api/v1/datasets/YAHOO/INDEX_VIX.csv?request_source=python&request_version=2&sort_order=asc&trim_start=2002-01-01'
context.stock=sid(8554)
fetch_csv(url, symbol='VIX', date_column='Date')
context.invested = False
context.leverage = 1.95
def handle_data(context, data):
hist = _history(data)
# Return if there is not enough data yet
if hist is None:
return
# Use the close VIX value because the price is also the close
vix = hist['Close']['VIX'].values
prices = hist['price'][context.stock].values
vix_rsi = talib.RSI(vix, timeperiod=2)[-1]
spy_rsi = talib.RSI(prices, timeperiod=2)[-1]
spy_ma200 = np.mean(prices)
record(vix_rsi=vix_rsi,
spy_rsi=spy_rsi)
record(spy_ma200=spy_ma200,
spy=data[context.stock].price)
if not context.invested:
if vix_rsi > 90 and spy_rsi < 30 and prices[-1] > spy_ma200:
order_target_percent(context.stock, context.leverage)
context.invested = True
else:
if spy_rsi > 65:
order_target(context.stock, 0)
context.invested = False