Back to Community
Not managing to get an algorithm to work

I am new with Quantopian/Python and have looked at an algorithm to try to implement. I am for some reason getting Error 50: SyntaxError: expected an indented block when trying to 'build the algorithm' and an error when trying to run the backtes. If someone has the knowledge to help, it would be appreciated a million!

The code:

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
import quantopian.pipeline.factors as Factors
import quantopian.pipeline.filters as Filters
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
import numpy as pn
import pandas as pd
def initialize(context):
attach_pipeline(my_pipeline(context), name='my_pipe')
schedule_function(rebalance,
date_rule=date_rules.month_start(),
time_rule=time_rules.market_open())
def my_pipeline(context):
pass
market_cap = morningstar.valuation.market_cap.latest
roic = morningstar.operation_ratios.roic.latest
revenue_growth = morningstar.operation_ratios.revenue_growth.latest
shares_outstanding = morningstar.valuation.shares_outstanding.latest
ev_to_ebitda = morningstar.valuation_ratios.ev_to_ebitda.latest

market_cap_ok = market_cap > 100000000  
roic_ok = roic > 0.1  
revenue_growth_ok = revenue_growth > 0  
shares_outstanding_ok = shares_outstanding.notnull()  

my_mask = roic_ok & revenue_growth_ok & shares_outstanding_ok

return Pipeline(  
columns={},  
screen = ev_to_ebitda.bottom(20, mask = my_mask)  
)

def before_trading_start(context, data):
context.output = pipeline_output('my_pipe')
record (cash = context.portfolio.cash, asset = context.portfolio_value)

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

weight = create_weights(context, context.output.index, data)  

for stock in context.output.index:  
    if data.can_trade(stock, weight);  

def create_weights(context, stocks, data):

cantradecount = 0;  
for stock in stocks:  
    if data.can_trade(stock):  
        cantradecount += 1  

if cantradecount == 0:  
    return 0  
else:  
    weight = 1.0/cantradecount  
    return weight  
5 responses

Bumping, anyone that knows what might be wrong? Help please

The python error 'SyntaxError: expected an indented block' usually occurs after an 'if' or 'for', or some other statement where an indented block of code is expected below it. For example, take the following code

for stock in context.output.index:  
print('oops')

Python gets confused because it is expecting the code after the 'for' statement to be indented. Like this

for stock in context.output.index:  
    print('oops')

So, specifically, the issue with the code above is this statement. The 'if' doesn't have an indented block below it.

for stock in context.output.index:  
    if data.can_trade(stock, weight);  

Looks like the code was just unfinished or copied and pasted incorrectly? The data.can_trade method has the wrong parameters and looks more like you intended an order method? In any case, attached is the algo which has these things fixed and I believe is what you intended?

Clone Algorithm
3
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
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
import quantopian.pipeline.factors as Factors
import quantopian.pipeline.filters as Filters
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
import numpy as pn
import pandas as pd

def initialize(context):
    attach_pipeline(my_pipeline(context), name='my_pipe')
    schedule_function(rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open())
    
def my_pipeline(context):
    pass

    market_cap = morningstar.valuation.market_cap.latest
    roic = morningstar.operation_ratios.roic.latest
    revenue_growth = morningstar.operation_ratios.revenue_growth.latest
    shares_outstanding = morningstar.valuation.shares_outstanding.latest
    ev_to_ebitda = morningstar.valuation_ratios.ev_to_ebitda.latest

    market_cap_ok = market_cap > 100000000  
    roic_ok = roic > 0.1  
    revenue_growth_ok = revenue_growth > 0  
    shares_outstanding_ok = shares_outstanding.notnull()  

    my_mask = roic_ok & revenue_growth_ok & shares_outstanding_ok

    return Pipeline(
        columns={},
        screen = ev_to_ebitda.bottom(20, mask = my_mask)
    )

def before_trading_start(context, data):
    context.output = pipeline_output('my_pipe')
    record (cash = context.portfolio.cash, asset = context.portfolio.portfolio_value)

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

    weight = create_weights(context, context.output.index, data)  

    for stock in context.output.index:  
        if data.can_trade(stock):
            order_target_percent(stock, weight)

def create_weights(context, stocks, data):
    cantradecount = 0;  
    for stock in stocks:  
        if data.can_trade(stock):  
            cantradecount += 1  

    if cantradecount == 0:  
        return 0  
    else:  
        weight = 1.0/cantradecount  
        return weight  
There was a runtime error.
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.

Hi Dan Whitnable. Big thanks, this helped me immensely! Lastly I would like to ask about the market cap restriction (above $100.000.000). I am getting the error 'Local variable assigned but never used' regarding the market_cap_ok part of the code. What could be the reason for that?

The reason you are getting the warning Local variable assigned but never used is that the code assigns a value to 'market_cap_ok'. However, this is never used.

    market_cap_ok = market_cap > 100000000  

Did you intend to use it in your 'my_mask' filter? Perhaps like this

    my_mask = market_cap_ok  & roic_ok & revenue_growth_ok & shares_outstanding_ok

In any case it's simply a for information only warning. It's not an error. The code will run fine 'as is'.

Thank you for the answers! Im still very confused as to why the result in the backtesting are largely negative. My aim is to make it pick firms with a market cap larger than 100.000.000, a ROIC larger than 10%, revenue growth larger than 0 and then pick the 20 firms with the lowest EV/EBITDA. Might something else in the code be wrong?