Back to Community
What's the problem ?

I am unable to figure out the problem in the code. Any help is appreciated.

def initialize(context):  
    schedule_function(rebalance,date_rule=date_rules.every_day(),  
                      time_rule=time_rules.market_open(minutes=1))  
def before_trading_starts(context):  
    fundamentals_df = get_fundamentals(  
        query(  
            fundamentals.operation_ratios.net_income_growth,  
            fundamentals.earnings_ratios.diluted_eps_growth,  
            fundamentals.valuation.market_cap,  
            fundamentals.valuation.shares_outstanding,  
        )  
        .filter( fundamentals.valuation.market_cap != None  
        )  
        .filter( fundamentals.operation_ratios.net_income_growth > 1.5  
        )  
        .filter( fundamentals.earnings_ratios.diluted_eps_growth > 1.2  
        )  
        .filter( fundamentals.valuation.shares_outstanding != None  
        )  
        .order_by( fundamentals.operation_ratios.net_income_growth.desc()  
        )  
        .limit(100)  
        )  
    context.stocks = fundamentals_df  
    update_universe(context.stocks)  

def rebalance(context,data):  
    for stock in context.portfolio.positions:  
        if stock not in context.stocks:  
            order_target(stock,0)  

def weights(context,stocks):  
    if len(stocks) == 0:  
        return 0  
    else:  
        weight = 0.99/len(stocks)  
        return weight  
def handle_data(context,data):  
    for stock in context.stocks:  
        order_target_percent(stock,weights(context,context.stocks))  

It gives an error saying : "'update_universe' only permitted within before_trading_start function"

14 responses

Yatharth

You named you functions before_trading_starts with an "s" it is just before_trading_start no "s". That will get your code to run, but you should also include an if stock in data: line as it threw a couple KeyErrors when I ran it.

Cheers

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.

So silly of me !! Thanks James

The code is going whack.

Clone Algorithm
2
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 55ad1722d1a21e0c72cafd9a
There was a runtime error.

So when you see algo performance that is just absolutely ridiculluos it's always a good idea to check the leverage over time. record(lever=context.account.leverage) put that line of code at the end of handle data. If you do you will see that your account becomes ludicrously leveraged ~5k. That's not good or realistic. This means that you are borrowing money to fill the orders you are placing. This is usually due to how people weight each security in their portfolio. So you need to look at your weights function and revamp it because it is probably not doing what you have in mind.

It's also a common sense analysis too, e.g. if you are only holding long positions you can't lose more than 100% of your starting capital. So bear in mind the affects leverage has on algo performance.

How should I curb the borrowing ? I am using order_targer_perecnt already and unable to find the error in weight allocation, i just want to allocate equal positive weights.

So just using order_target_percent does not guarantee you controlled leverage it guarantees to place an order for the given percentage.

Here is an example,

DAY 1: Let's say you decide to buy only one stock, and lets say you want to buy BRK_A. order_target_percent(symbol(BRK_A), 1) Now you have allocated 100% of your portfolio to BRK_A.

DAY 2: You decide that you want to buy another stock LMT. order_target_percent(symbol(LMT), 1) Now you have allocated 100% of your current portfolio value to LMT. But wait you also allocated 100% of it from yesterday to BRK_A, so now you are roughly leveraged 2x. You had to borrow the money to buy LMT, because your current portfolio was tied up in BRK_A.

So even though you are using order_target_percent that is no guarantee that you will not borrow money. Does that help?

Does the value of portfolio also get updated everyday ?

For example :(Day 1) If my initial cash was say $1000 which got allocated to certain stocks in equal proportion.
(Day 2)Next day I order the same using order_target_percent thus making my leverage to 2x.
(Day 3) Next day if I send the exact same order will it make my account 3x leveraged or 4x leveraged ? (Will it take the portfolio size as $1000 or would have updated it to $2000 on the second day)

Also during rebalancing I am liquidating certain stocks and allocating equal weights to each stock in the context , won't this make sure that I always order within my cash.

Yatharth,

The problem is context.stocks is a pandas dataframe with fundamentals:

2014-01-07 PRINT security            Equity(26890 [TSRE])  Equity(33988 [FBRC])  
net_income_growth             117.790244          9.378411e+01  
diluted_eps_growth            185.000000          1.163333e+02  
market_cap               72598770.000000          3.152467e+08  
shares_outstanding       11468665.000000          1.121475e+07  

So len(context.stocks) is always 4.

When you have a problem like this, just print EVERYTHING and step through in the debugger every line. It's always a silly mistake that everyone makes from time to time (I looked at your code yesterday and couldn't understand why it was going over leverage).

You can use context.stocks.shape[1] instead:

Clone Algorithm
7
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 55ae1f56a12ef00c639c4bbf
There was a runtime error.

Thanks a lot James ! This really helped :)

I changed the fundamental query. There seems to be a sudden upsurge in return for this time period. Is this right ? Also what is causing the increased leverage this time ?

Clone Algorithm
2
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 55afcf0476626c0c6c519418
There was a runtime error.

This is SAN Missing split adjustment data bug.
https://www.quantopian.com/posts/missing-split-adjustment

@Vladimir
Mine is for 2011 Jan period , while the one that you refer to is for 2015. And I am long on multiple securities based on the fundamental query which may or may not include SAN.

I think bad data on PXG before
2011-01-31
PXG
$0.30 298064
$89,419.20 $76,900.51