Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Stocks in a long-term uptrend with medium-term price correction showing short-term momentum

Hi Community,

I had the following idea for a trade algorithm: I'd like to find stocks which are outperforming the market over a long-term period (let's say 350 days) and are themselves in a long-term uptrend (stock price > 350 day Moving Average), which experienced a price correction in the last weeks or months because of some market worries (e.g. Apple seizing iPhone Sales Number Guidance and fear of slowing sales in 2018/19 or slower cloud business @ Amazon), but are now showing some sort of short-term momentum ( Stock Price crossing short-term_50_day Moving Average from below) indicating that market worries are now overdone.

My idea was to filter for stocks in a long-term uptrend and for short-term momentum in the make_pipeline() function And then calculate log-returns for the securities for the last 60 (or 120) days to then count the number of negative returning days to see if the stocks have been in a correction - essentially I want to exclude stocks which were just hoovering around their short-term 50 day moving average.

Specific idea for filtering for medium term correction was:
# Idea: Calculate log-Returns and count days with negative daily log returns over the last 60 days,
# then give me the 20 top stocks which corrected the most /or longest, whatever works out best,
# e.g. sum(daily_log_rets_of_last_60days 20 )

My pipeline Output seems to be okay, but I'm failing in integrating the above idea in the trade function.
Would love if someone here could help me on track with this!

Thanks,
Jo

from quantopian.algorithm import attach_pipeline,pipeline_output  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.filters import QTradableStocksUS  
from quantopian.pipeline.filters import Q1500US  
from quantopian.pipeline.factors import ExponentialWeightedMovingAverage,SimpleMovingAverage, CustomFactor, Factor, AverageDollarVolume, Returns

def initialize(context):  
    """  
    Called once at the start of the algorithm.  
    """  
    # schedule_function(check_trends,date_rules.every_day(),time_rules.market_open(minutes=20))

    # Create our dynamic stock selector.  
    attach_pipeline(make_pipeline(), 'pipeline')  
    # Rebalance every day, 1 hour after market open.  
    schedule_function(trade,date_rules.every_day(),time_rules.market_open(hours=1))



def before_trading_start(context, data):  
    context.output = pipeline_output('pipeline')  
    print(context.output)



def trade(context, data):  
    """  
    Execute orders according to our schedule_function() timing.  
    """  
    # Get daily pipeline output  
    df = context.output  
    security_list = df.index  
    # Get Stocks from pipeline output (longterm uptrend, short-term momentum) which corrected in a medium term  
    # Idea: Calculate log-Returns and count days with negative daily log returns over the last 60 days,  
    #       then give me the 20 top stocks which corrected the most /or longest, whatever works out best,  
    #       e.g. sum(daily_log_rets_of_last_60days<0)/sum(daily_log_rets_of_last_60days)  
    #       (optional with a filter: len(daily_log_rets_of_last_60days<0) > 20 )  
    buylist = Returns(data.history(security_list,'close',60,"1d").iloc[-60:],window_length=2).log1p()  
    print(buylist)  

def record_vars(context, data):  
    """  
    Plot variables at the end of each day.  
    """  
    pass


def handle_data(context, data):  
    """  
    Called every minute.  
    """  
    pass


def make_pipeline():  
    # Base universe set to the QTradableStocksUS  
    base_universe = Q1500US()  
    # yesterday's & the day before yesterday's close  
    yesterday_close = USEquityPricing.close.latest  
    day_before_yesterday = yesterday_close / (Returns(window_length=2)+1)  
    # Stocks in long-term uptrend  
    long_ma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=350)  
    longuptrend = yesterday_close > long_ma  
    # Stocks in a long-term uptrend which cross 50day Moving Average from below  
    short_ma = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=50,mask=longuptrend)  
    # short_momentum =   short_ma > yesterday_close < ma_60  
    short_momentum =  day_before_yesterday < short_ma < yesterday_close  
    log_rets = Returns(window_length=2,mask=short_momentum).log1p()  


    pipe = Pipeline(  
        columns={  
            # 'yesterday_close':yesterday_close,  
            'longuptrend':longuptrend,  
            # 'short_ma':short_ma,  
            # 'short_momentum': short_momentum,  
            'log_rets':log_rets,  
        },  
        screen=base_universe & short_momentum & longuptrend  
    )  
    return pipe