Hi, I would like to do the following in the code. Can someone show me how please?
Rules:
Trading only once per day at 3:50pm
StockDelta( 3:50pm Today) = 1.0 * R(1) + 2.0 * R(2) + 3.0 * R(3) + 4.0 * R(4) + 5.0 * R(5)
R(1) = Price( 3:50pm Today) / Price ( T-1 Close) - 100%
R2) = Price( T-1 Close) / Price ( T-2 Close) - 100%
R(3) = Price( T-2 Close) / Price ( T-3 Close) - 100%
R(4) = Price( T-3 Close) / Price ( T-4 Close) - 100%
R(5) = Price( T-4 Close) / Price ( T-5 Close) - 100%
import numpy as np
import math
from pytz import timezone
set_commission(commission.PerShare(cost=0.0))
set_slippage(slippage.FixedSlippage(spread=0.0))
def initialize(context):
context.stock = sid(24)
def handle_data(context, data):
#set timezone to EST
exchange_time = get_datetime().astimezone(timezone('US/Eastern'))
#Rebalance at 3:50PM
if exchange_time.hour == 15 and exchange_time.minute == 50:
price_history = history(bar_count=6, frequency='1d', field='price')
return1 = price_history.ix[0] / price_history.ix[-1] - 1.0
return2 = price_history.ix[-1] / price_history.ix[-2] - 1.0
return3 = price_history.ix[-2] / price_history.ix[-3] - 1.0
return4 = price_history.ix[-4] / price_history.ix[-5] - 1.0
return5 = price_history.ix[-5] / price_history.ix[-6] - 1.0
StockDelta = 1.0 * return1 + 2.0 * return2 + 3.0 * return3 + 4.0 * return4 + 5.0 * return5
StockDelta_limit = max( -1.0, min( 1.0, StockDelta) )
record( tgt_pct = 100 * StockDelta_limit)
order_target_percent( context.stock, StockDelta )