Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Syntax error in code from tutorial!!

Hi

I am a beginner, learning quant trading, followed this tutorial video of mean reversion strategy, I get syntax error when slicing the list. I commented everything above, below to see what it might be but cant find (is there anyway i could see details of this syntax error?)

Then I commented the whole weighted average function so I can proceed with tutorial then i get error "AttributeError: 'Positions' object has no attribute 'intervalues' " I tried look up documentations, cant find 'intervalues'

Appreciate the help.
Thanks

"""
mean reversion strategy means that stocks that moves away from its mean, revert back to its means.

stocks that trade above its mean are over priced and will be sort  
stocks that trade below its mean are uner priced and will be long  
"""

"""  
mean reversion strategy means that stocks that moves away from its mean, revert back to its means.

stocks that trade above its mean are over priced and will be sort  
stocks that trade below its mean are uner priced and will be long  
"""

def initialize(context):  
    context.sids = [sid(351), sid(1900), sid(7671), sid(18529)]  
    schedule_function(  
        func = rebalance,  
        date_rule = date_rules.every_day(),  
        time_rule = time_rules.market_open()  
        )  
    schedule_function(  
        record_vars,  
        date_rules.every_day(),  
        time_rules.market_open()  
    )  
def rebalance(context, data):  
    weights = calc_weights(context, data)  
    for security in context.sids:  
        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.intervalues():  
        if positions < 0:  
            shorts += 1  
        if positions > 0:  
            longs += 1  
    record(  
        leverage=context.account.leverage,  
        long_count = longs,  
        short_count = shorts  
        )

def calc_weights(context, data):  
    hist = data.history(context.sids, 'price', 30, '1d')  
    10_day_prices = hist[-10:]  
    30_day_prices = hist[-30:]  
    10_day_mean = 10_day_prices.mean()  
    30_day_mean = 30_day_prices.mean()  

    raw_weights = (10_day_mean - 30_day_mean) / 30_day_mean  
    return raw_weights / raw_weights.abs().sum()  



2 responses

There are a couple of issues you are probably experiencing. Both are related to the following code

    for position in context.portfolio.positions.intervalues():  
        if positions < 0:  
            shorts += 1  
        if positions > 0:  
            longs += 1 

First, Quantopian has migrated to Python 3 and the tutorial video was made before the switch. The tutorial code is written in Python 2. There are generally only a few things which changed but one was deprecating the itervalues method. The second issue is this method is incorrectly spelled with an 'n' as intervalues . The fix is to simply use values()instead. So, something like this

    for position in context.portfolio.positions.values():  
        if positions < 0:  
            shorts += 1  
        if positions > 0:  
            longs += 1 

Try that and see if you have better luck. There's more specifics on the transition from Python 2 to 3 here if interested.

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.

Thanks Dan

That was really helpful, new function now looks like below

def record_vars(context, data):  
    longs = shorts = 0  
    for position in context.portfolio.positions.values():  
        if position.amount < 0:  
            shorts += 1  
        if position.amount > 0:  
            longs += 1  
    record(  
        leverage=context.account.leverage,  
        long_count = longs,  
        short_count = shorts  
        )

as for the syntax error, apparently variable name had to change from 10_day_prices to prices_for_10_days resolved the issue (I programmed in C/C++ so never thought variable names starting with integer value could be issue but quick google confirmed this issue for PHP, not sure if same for python)