Back to Community
Algo not backtesting correctly

My algo is not backtesting correctly. It is not pulling in the cumulative returns. Rick constraints are being identified, but that's about it. The algo is supposed to go long on stocks whose price is 5% under the 5day EMA. Any help would be greatly appreciated.

Clone Algorithm
4
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
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.factors import ExponentialWeightedMovingAverage
from quantopian.pipeline.factors import AverageDollarVolume
import quantopian.optimize as opt
from quantopian.algorithm import order_optimal_portfolio
from quantopian.algorithm import attach_pipeline, pipeline_output


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

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

    # Create our dynamic stock selector.
    my_pipe = make_pipeline()
    algo.attach_pipeline(my_pipe, 'my_pipeline')


def make_pipeline():
    """
    A function to create our dynamic stock selector (pipeline). Documentation
    on pipeline can be found here:
    https://www.quantopian.com/help#pipeline-title
    """

    # Base universe set to the QTradableStocksUS
    base_universe = QTradableStocksUS()

    EMA5 = ExponentialWeightedMovingAverage(
        inputs=[USEquityPricing.close],
        window_length=5,
        decay_rate=1,
        mask = base_universe) 
    
    latest_close = USEquityPricing.close.latest
    min_price = latest_close > 5.0 # Only stocks > $5
    close_vs_EMA5 = (latest_close - EMA5) / EMA5 # The close price's relationshiop with it's EMA5
    signal_filter = (close_vs_EMA5 < -.05) # The filter for those stocks who's price is 5% below EMA5
    dollar_volume = AverageDollarVolume(window_length = 30)
    high_dollar_volume = (dollar_volume > 10000000)
    
    return Pipeline(
        columns={
            'close_vs_EMA5': close_vs_EMA5},
        screen = signal_filter & min_price & high_dollar_volume)

def compute_target_weights(context, data):
    """
    Compute ordering weights
    """
    
    # Initialize empty target weights dictionary
    # This will map securities to their target weights
    weights = {}
    
    # If there are securities in our list, compute even target weights for each security
    if context.close_vs_EMA5:
        weight = 1 / len(context.close_vs_EMA5)
    else:
        return weights
        
    # Exit positions in our portfolio if they are not in our stock list
    for security in context.portfolio.positions:
        if security not in context.close_vs_EMA5 and data.can_trade(security):
            weights[security] = 0
            
        for security in context.close_vs_EMA5:
            weights[security] = weight
            
    return weights

def before_trading_start(context, data):
    """
    Get pipeline results
    """
    
    # Gets our pipeline output everyday
    pipe_results = algo.pipeline_output('my_pipeline')
    
    # Go long for securities whose price is 5% below the 5-day EMA and check if they can be traded
    context.close_vs_EMA5 = []
    for sec in pipe_results.index:
        if data.can_trade(sec):
            context.close_vs_EMA5.append(sec)
            
def my_rebalance(context, data):
    """
    Rebalance weekly
    """
    
    # Calculate target weights to rebalance
    target_weights = compute_target_weights(context, data)
    
    # If we have target weights, rebalance our portfolio
    if target_weights:
        algo.order_optimal_portfolio(
            objective = opt.TargetWeights(target_weights),
            constraints=[],
        )
        
def my_record_vars(context, data):
    """
    Record variables at the end of each day
    """
    
    close_vs_EMA5 = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount > 0:
            close_vs_EMA5 += 1
            
    # Record our variables
    record(
        leverage = context.account.leverage,
        long_count = close_vs_EMA5)
There was a runtime error.
1 response

Try to compute target weights this way:

def compute_target_weights(context, data):  
    weights = {}  
    if context.close_vs_EMA5:  
        weight = 1.0 / len(context.close_vs_EMA5)  
    else:  
        return weights

    for security in context.portfolio.positions:  
        if security not in context.close_vs_EMA5 and data.can_trade(security):  
            weights[security] = 0

    for security in context.close_vs_EMA5:  
        weights[security] = weight

    return weights