Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trying to build first algorithm but can't get it to work, help much appreciated

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)  
3 responses

Hello Pascal,

Instead of copying the code, can you run a full backtest and then share the result as an attachment here in the post? It's much much easier to help when we have the shared backtest.

Thanks

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hey Dan,

unfortunately the algorithm does not work, so I cannot run a backtest. I already spotted a mistake the list of my securities and with using itervalues() for my security list in a for loop. However I still get the error message when trying to build the algorithm:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
There was a runtime error on line 52.

This is the error message from the backtest