Hey Guys,
I am just starting to learn how Quantopian works and I decided to build a simple Momentum strategy without using the pipeline.
I selected ten securities and if the price increased over the previous week I would take a long position, etc.
I want to assign the same weights to each position and I think my mistake is in the calulation of the raw weights, but I can't figure out how to solve it, so I am hoping someone might be able to help me.
The code is seen below:
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Rebalance on first trading day of week, 1 hour after market open.
schedule_function(my_rebalance, date_rules.week_start(days_offset = 0), time_rules.market_open(hours=1))
# Record tracking variables at the end of each day.
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
context.my_securities = [sid(24), sid(3149), sid(40430), sid(42950), sid(1267), sid(48129), sid(3242), sid(698), sid(49518), sid(5061)]
def my_assign_weights(context, data):
"""
Assign weights to securities that we want to order.
"""
#Get timeseries of Prices for Securities
timeseries = data.history(context.security_list, 'price', 6, '1d')[:-1]
#Get Last and First Day of previous week
Last_Day = timeseries[-1:]
First_Day = timeseries[:-4]
#Calculate raw weights
raw_weights = Last_Day - First_Day
for security in context.security_list.itervalues():
if raw_weights > 0:
raw_weights = 1
elif raw_weights < 0:
raw_weights = -1
elif raw_weights == 0:
raw_weights = 0
normalized_weights = raw_weights / raw_weights.abs().sum()
#Determine Long and Short Positions
short_secs = normalized_weights.index[normalized_weights < 0]
long_secs = normalized_weights.index[normalized_weights > 0]
log.info("This week's longs: " + ", ".join([long_.symbol for long_ in long_secs]))
log.info("This week's shorts: " + ", ".join([short_.symbol for short_ in short_secs]))
#Return Normalized Weights
return normalized_weights
def my_rebalance(context,data):
"""
Execute orders according to our schedule_function() timing.
"""
#Calculate Target Weights via compute_weights function
weights = my_assign_weights(context, data)
#Place Orders for Securities
for security in context.security_list:
if data.can_trade(security):
order_target_percent(security, weights[security])
def my_record_vars(context, data):
"""
Plot variables at the end of each day.
"""
longs = shorts = 0
for position in context.portfolio.positions.itervalues():
if position.amount > 0:
longs += 1
elif position.amount < 0:
shorts += 1
#Record Variables
record(leverage = context.account.leverage, long_count = longs, short_count = shorts)