I wrote couples of lines of codes to build up a mean-reverse model.
However, it shows:
21 Warning Undefined name 'rebalance'
21 Error Runtime exception: NameError: name 'rebalance' is not defined
23 Warning Undefined name 'record_vars'
41 Warning Undefined name 'raw'
Could anyone help or explain why these errors happen?
Thanks a lot!
def initialize(context):
context.security_list = [
sid(24),#Apple
sid(16841),#Amazon
sid(46632),#Google
sid(5061),#Microsoft
sid(11100),#Berkshire Hathaway B
sid(42950),#Facebook
sid(47740),#Alibaba
sid(39062),#JPMorgan Chase
sid(4151),#Johnson & Johnson
sid(35920),#Visa
sid(8347),#ExxonMobil
sid(8229),#Walmart
sid(5938),#Procter & Gamble
sid(32146),#Mastercard
sid(52320)#AT&T Inc
]
schedule_function(rebalance,date_rules.week_start(),time_rules.market_open())
schedule_function(record_vars,date_rules.every_day(),time_rules.market_close())
def compute_weights(context,data):
hist = data.history(context.security_list, "price", 30, "ld")
prices_10 = hist[-10:]
prices_30 = hist[-30:]
sma_10 = prices_10.mean()
sma_30 = prices_30.mean()
raw_weights = (sma_10 - sma_30) / sma_30
normalized_weights = raw_weights / raw_weights.abs().sum()
return normalized_weights
def rebalance(context, data):
weights = compute_weights(context, data)
for security in context.security_list:
if data.can_trade(security):
order_target_percent(security, weights[security])
def record_vars(context, data):
longs = shorts = 0
for position in context.portfolio.positions.itervalues():
if position.amount > 0:
longs += 1
elif position.amount < 0:
shorts += 1
record(leverage=context.account.leverage, long_count = longs,
short_count = shorts)