Back to Community
Problem in first code

in the following code:

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q1500US
from quantopian.pipeline.data.sentdex import sentiment

def initialize(context):
"""
# Called once at the start of the algorithm.
"""
# Rebalance every day, 1 hour after market open.
schedule_function(
rebalance,
date_rules.every_day(),
time_rules.market_open(hours=1),
)

# Record tracking variables at the end of each day.  
schedule_function(  
    record_vars,  
    date_rules.every_day(),  
    time_rules.market_close(),  
)

# Create our dynamic stock selector.  
attach_pipeline(make_pipeline(), 'pipeline')

def make_pipeline():
sentiment_factor = sentiment.sentiment_signal.latest

universe = (Q1500US() & sentiment_factor.notnull())  

sentiment_quantiles = sentiment_factor.rank(mask=universe, method='average').quantiles(2)  

pipe = pipeline(columns={'sentiment': sentiment_factor,  
                        'longs': (sentiment_factor >= 4),  
                        'shorts': (sentiment_factor <= -2)},  
                screen=universe)  
return pipe

def before_trading_start(context, data):

context.output = pipeline_output('pipeline')


context.security_list = context.output.index  

def rebalance(context, data):
long_secs = context.output[context.output['longs']].index
long_weight = 0.5 / len(long_secs)

short_secs = context.output[context.output['shorts']].index  
short_weight = 0.5 / len(short_secs)  

for security in long_secs:  
    if data.can_trade(security):  
        order_target_percent(security, long_weight)  

for security in short_secs:  
    if data.can_trade(security):  
        order_target_percent(security, short_weight)

for security in context.portfolio.positions:  
    if data.can_trade(security) and security not in long_secs and security not in short_secs:  
        order_target_percent(security,0)

def record_vars(context, data):
long_count = 0
short_count = 0

for position in context.portfolio.positions.itervalue():  
    if position.amount > 0:  
        long_count +=1  
    elif position.amount < 0:  
        short_count +=1  

record(num_longs = long_count, num_shorts = short_count, leverage= context.account.leverage)

I get an error at the line:
for position in context.portfolio.positions.itervalue():. It says there is an unexpected indent.

Could someone please help with the following questions:
1- what is an indent?
2- what is the solution to the problem in the code?

1 response

I got it running, it doesn't return any stocks though.

Regarding indenting: https://en.wikipedia.org/wiki/Indentation

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
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q1500US
from quantopian.pipeline.data.sentdex import sentiment

def initialize(context):
    """
    # Called once at the start of the algorithm.
    """
    # Rebalance every day, 1 hour after market open.
    schedule_function(
    rebalance,
    date_rules.every_day(),
    time_rules.market_open(hours=1),
    )

    # Record tracking variables at the end of each day.  
    schedule_function(  
        record_vars,  
        date_rules.every_day(),  
        time_rules.market_close(),  
    )

    # Create our dynamic stock selector.  
    attach_pipeline(make_pipeline(), 'pipeline')
    
    
    
def make_pipeline():
    
    sentiment_factor = sentiment.sentiment_signal.latest

    universe = (Q1500US() & sentiment_factor.notnull())  

    sentiment_quantiles = sentiment_factor.rank(mask=universe, method='average').quantiles(2)  

    pipe = Pipeline(columns={'sentiment': sentiment_factor,  
                            'longs': (sentiment_factor >= 4),  
                            'shorts': (sentiment_factor <= -2)},  
                    screen=universe)  
    return pipe

def before_trading_start(context, data):

    context.output = pipeline_output('pipeline')
    context.security_list = context.output.index  
    
    
    
def rebalance(context, data):
    long_secs = context.output[context.output['longs']].index
    long_weight = 0.5 / (len(long_secs) + 1)

    short_secs = context.output[context.output['shorts']].index  
    short_weight = 0.5 / (len(short_secs)  + 1)

    for security in long_secs:  
        if data.can_trade(security):  
            order_target_percent(security, long_weight)  

    for security in short_secs:  
        if data.can_trade(security):  
            order_target_percent(security, short_weight)

    for security in context.portfolio.positions:  
        if data.can_trade(security) and security not in long_secs and security not in short_secs:  
            order_target_percent(security,0)
            
def record_vars(context, data):
    long_count = 0
    short_count = 0

    for position in context.portfolio.positions:  
        if position.amount > 0:  
            long_count +=1  
        elif position.amount < 0:  
            short_count +=1  
    record(num_longs = long_count, num_shorts = short_count, leverage= context.account.leverage)

There was a runtime error.