Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Going about writing a P/E-based algo?

Hello,

I'm new here and I'm testing the waters with some different algos. One that I wanted to make would do the following:

  • Figure out 10 stocks with highest P/E ratios for past 3 months, add them to a list if they don't already exist, and short them in equal amounts based upon portfolio size (rebalance as they are added and removed)
  • Put a loss protection on the stock so that if it goes above 5% of buying price, close the position
  • Hold until their P/E ratio crosses the market P/E ratio, then close out the position

I have a good grasp on Python but I'm having trouble conceptualizing how to translate that into a testable algo. Any help?

3 responses

Hi Andrei, you can use the Pipeline API and then add fundamental data filters to choose your universe of stocks.

When you submit orders, you can choose a variety of execution methods -- stop orders, limit orders, stop-limit orders. As well as IB-specific order types.

And you can store the value of the PE ratio per security you're trading as a dictionary, and then check against the latest value to determine any differences. Once the threshold has been crossed, you can enter your trades. Hope that helps!

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.

I see what you're saying. I managed to get this:


from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data.morningstar import earnings_ratios  
from quantopian.algorithm import attach_pipeline, pipeline_output


def initialize(context):  
    pipe = Pipeline()  
    attach_pipeline(pipe, name='pipeline')  
    #SPY  
    context.market = sid(8554)

def handle_data(context, data):  
    for i in context.high3MoPE:  
        price = data[i].price  
        if i not in context.portfolio:  
            #negative for shorting  
            order(i, -(context.portfolio.portfolio_value/len(context.portfolio.positions)))  
            #buy to cover at a 1.05 limit above price  
            order(i, (context.portfolio.portfolio_value/len(context.portfolio.positions)), style=LimitOrder(price*1.05))  
    for eq in context.portfolio:  
    #hold until their P/E ratio crosses the market P/E ratio, then close out the position  
         if data[eq].pe_ratio < data[context.market].pe_ratio:  
                  order_target_percent(eq, 0)

def before_trading_start(context, data):  
    results = pipeline_output('pipeline')  
    print results.head(10)  
    #find 10 stocks with highest 3 month P/E and put them in a list called high3MoPE  
    #doesn't do by 3 months... only does daily PE  
    context.high3MoPE = query(fundamentals.valuation_ratios.pe_ratio).order_by(fundamentals.valuation_ratios.pe_ratio).limit(10)  
    #context.high3MoPE = PEquery.all()  
    print(context.high3MoPE)  
    #rebalance portfolio when trading day starts every day by distributing positions equally

However, it looks like the .all() method is not whitelisted for the query, so I can't put the results into a list and iterate through them. Is there a known workaround?

Hi Andrei,

You can use the get_fundamentals(query(...)) method to work with fundamental data as iterables.

For example, you could write:

PEfundamentals = get_fundamentals(query(fundamentals.valuation_ratios.pe_ratio).order_by(fundamentals.valuation_ratios.pe_ratio).limit(10))  
context.high3MoPE = PEfundamentals.keys()  
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.