Back to Community
Only look trigger when price is above the 20 SMA

How can i code if current price is above the 20 day MA
then check to see if
12 SMA is greater than 26 SMA

4 responses

You can use the pipeline API to calculate the 20, 12 and 26 day moving averages. These would be computed for all securities every day before trading starts.

You would have to narrow your universe down to the 500 securities that you are most interested in. Perhaps a screen based on the difference between the 12 and 26 day moving average? Either including all stocks where the 12 day is greater (or less than) the 26 day, depending on your theory.

From there you can pass the pipeline output into your algorithm with the 12, 20 and 26 day moving averages to do your comparisons.

Attached is an example that might help you explore the pipeline API

Clone Algorithm
939
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
"""
This example comes from a request in the forums. 
The post can be found here: https://www.quantopian.com/posts/ranking-system-based-on-trading-volume-slash-shares-outstanding

The request was: 

I am stuck trying to build a stock ranking system with two signals:
1. Trading Volume/Shares Outstanding.
2. Price of current day / Price of 60 days ago.
Then rank Russell 2000 stocks every month, long the top 5%, short the bottom 5%.

"""

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline import CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar


# Create custom factor #1 Trading Volume/Shares Outstanding
class Liquidity(CustomFactor):   
    
    # Pre-declare inputs and window_length
    inputs = [USEquityPricing.volume, morningstar.valuation.shares_outstanding] 
    window_length = 1
    
    # Compute factor1 value
    def compute(self, today, assets, out, volume, shares):       
        out[:] = volume[-1]/shares[-1]

# Create custom factor #2 Price of current day / Price of 60 days ago.        
class Momentum(CustomFactor):   
    
    # Pre-declare inputs and window_length
    inputs = [USEquityPricing.close] 
    window_length = 60
    
    # Compute factor2 value
    def compute(self, today, assets, out, close):       
        out[:] = close[-1]/close[0]
        
# Create custom factor to calculate a market cap based on yesterday's close
# We'll use this to get the top 2000 stocks by market cap
class MarketCap(CustomFactor):   
    
    # Pre-declare inputs and window_length
    inputs = [USEquityPricing.close, morningstar.valuation.shares_outstanding] 
    window_length = 1
    
    # Compute market cap value
    def compute(self, today, assets, out, close, shares):       
        out[:] = close[-1] * shares[-1]
        

def initialize(context):
    pipe = Pipeline()
    attach_pipeline(pipe, 'ranked_2000')
       
    # Add the two factors defined to the pipeline
    liquidity = Liquidity()
    pipe.add(liquidity, 'liquidity')
    
    momentum = Momentum()
    pipe.add(momentum, 'momentum')
    
    # Create and apply a filter representing the top 2000 equities by MarketCap every day
    # This is an approximation of the Russell 2000
    mkt_cap = MarketCap()
    top_2000 = mkt_cap.top(2000)
    
    # Rank factor 1 and add the rank to our pipeline
    liquidity_rank = liquidity.rank(mask=top_2000)
    pipe.add(liquidity_rank, 'liq_rank')
    
    # Rank factor 2 and add the rank to our pipeline
    momentum_rank = momentum.rank(mask=top_2000)
    pipe.add(momentum_rank, 'mom_rank')
    
    # Take the average of the two factor rankings, add this to the pipeline
    combo_raw = (liquidity_rank+momentum_rank)/2
    pipe.add(combo_raw, 'combo_raw') 
    
    # Rank the combo_raw and add that to the pipeline
    pipe.add(combo_raw.rank(mask=top_2000), 'combo_rank')
    
    # Set a screen to ensure that only the top 2000 companies by market cap 
    # with a momentum factor greater than 0 are returned
    pipe.set_screen(top_2000 & (momentum>0))
            
    # Scedule my rebalance function
    schedule_function(func=rebalance, 
                      date_rule=date_rules.month_start(days_offset=0), 
                      time_rule=time_rules.market_open(hours=0,minutes=30), 
                      half_days=True)
    
    # set my leverage
    context.long_leverage = 0.50
    context.short_leverage = -0.50
    
            
def before_trading_start(context, data):
    # Call pipelive_output to get the output
    context.output = pipeline_output('ranked_2000')
      
    # Narrow down the securities to only the top 200 & update my universe
    context.long_list = context.output.sort(['combo_rank'], ascending=False).iloc[:100]
    context.short_list = context.output.sort(['combo_rank'], ascending=False).iloc[-100:]   
    
    update_universe(context.long_list.index.union(context.short_list.index)) 


def handle_data(context, data):  
    
     # Record and plot the leverage of our portfolio over time. 
    record(leverage = context.account.leverage)
    
    print "Long List"
    log.info("\n" + str(context.long_list.sort(['combo_rank'], ascending=True).head(10)))
    
    print "Short List" 
    log.info("\n" + str(context.short_list.sort(['combo_rank'], ascending=True).head(10)))

# This rebalancing is called according to our schedule_function settings.     
def rebalance(context,data):
    
    long_weight = context.long_leverage / float(len(context.long_list))
    short_weight = context.short_leverage / float(len(context.short_list))

    
    for long_stock in context.long_list.index:
        if long_stock in data:
            log.info("ordering longs")
            log.info("weight is %s" % (long_weight))
            order_target_percent(long_stock, long_weight)
        
    for short_stock in context.short_list.index:
        if short_stock in data:
            log.info("ordering shorts")
            log.info("weight is %s" % (short_weight))
            order_target_percent(short_stock, short_weight)
        
    for stock in context.portfolio.positions.iterkeys():
        if stock not in context.long_list.index and stock not in context.short_list.index:
            order_target(stock, 0)
We have migrated this algorithm to work with a new version of the Quantopian API. The code is different than the original version, but the investment rationale of the algorithm has not changed. We've put everything you need to know here on one page.
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.

Lakith,
Here is an example showing how I would using the pipeline API to do the price comparisons you were asking about.

Hope this is helpful,

KR

Clone Algorithm
12
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
'''
How can i code if current price is above the 20 day MA
then check to see if
12 SMA is greater than 26 SMA
'''

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline import CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.factors import SimpleMovingAverage

        
# Create custom factor to calculate a market cap based on yesterday's close
class MarketCap(CustomFactor):   
    
    # Pre-declare inputs and window_length
    inputs = [USEquityPricing.close, morningstar.valuation.shares_outstanding] 
    window_length = 1
    
    # Compute market cap value
    def compute(self, today, assets, out, close, shares):       
        out[:] = close[-1] * shares[-1]

def initialize(context):
    
    context.long_leverage = 0.50
    context.short_leverage = -0.50
    
    # create and attach my pipeline
    pipe = Pipeline()
    attach_pipeline(pipe, 'example')
    
    # Create and apply a filter representing the top 2000 equities by MarketCap every day
    # This is an approximation of the Russell 2000
    mkt_cap = MarketCap()
    top_2000 = mkt_cap.top(2000)
    pipe.set_screen(top_2000)

    # I'm using the yesterday's close price as a first check for 
    # current price > the 20 day SMA
    close = USEquityPricing.close.latest
    # I also calculate all 3 of the SMA factors
    sma_20 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20)
    sma_12 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=12)
    sma_26 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=26)
    # add the factors to my pipeline
    pipe.add(sma_20, 'sma_20')
    pipe.add(sma_12, 'sma_12')
    pipe.add(sma_26, 'sma_26')
    
    # Add the filters to the pipeline, for review
    # These will show as a column with boolean values 
    current_price_filter = sma_20<close
    pipe.add(current_price_filter, 'close>20')
    
    sma_filter = sma_12 > sma_26
    pipe.add(sma_filter, '12>26')
               
def before_trading_start(context, data):
    
    context.output = pipeline_output('example')
    log.info(len(context.output))
    
    my_universe = context.output.iloc[:500]
    
    update_universe(my_universe.index) 


def handle_data(context, data):  
    
     # Record and plot the leverage of our portfolio over time. 
    record(leverage = context.account.leverage)
       
    log.info("\n" + str(context.output.sort(['sma_12'], ascending=True).head(10)))
    
    
There was a runtime error.

Thanks Karen.... Do people use the quantopian for day trading basis... also whats pipe line.... and i'm having very hard time with indent errors..
any advice

Hi Lakith,

Yes, some members of our community use the Quantopian platform for day trading, check out some of these community posts:

https://www.quantopian.com/posts/does-quantopian-support-day-trading
https://www.quantopian.com/posts/how-to-determine-if-a-day-is-the-last-trading-day-of-the-month

Check out this post for a good description of the Pipeline API: https://www.quantopian.com/posts/introducing-the-pipeline-api

Regarding the indent errors, make sure that you are following Python's indentation rules and if you are having a hard time figuring out the problem, you can email us at [email protected] and we can help you figure it out!

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.