Back to Community
A noobs first week on quantopian

Hello friends. I've been a member of the Quantopian gang for about a week now, and the Python crew not much longer than that. I am hoping to post a new algorithm as frequently as I can in the hopes they will all get picked apart by you, who are all much smarter than I am, and that I can get some constructive criticism on what I am doing wrong so I can correct it and learn :) Since I am new not only to this platform, but to Python as well, I am expecting there to be issues with my code; so please don't hold back I am really interested in learning from you guys and getting better!

I've attached my very first attempt at a simple algorithm. Basically it's a long only strategy (I think) that aims to invest in companies with a $2B + market cap, current ratios above 2, P/B within the range of 1 and 2.5, P/E of less than 15. The goal was to be evenly weighted in however many assets made it through the pipeline, and rebalance daily. I also thought I was managing leverage, but it still seems to be above 1 in some months.

I guess my first question is, is there something wrong with my code, or is my "value" idea I tried to use just that terrible? Any recommendations on how I can improve this either code wise or pipeline wise would be very much appreciated. I'm looking to make some alterations and post version 2 next week for anyone that wants to come along on the journey!

Thanks everyone, and I apologize in advance to anyone who looks at the code.

Clone Algorithm
3
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.morningstar import valuation_ratios, operation_ratios, cash_flow_statement
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.data import Fundamentals  
from quantopian.pipeline.factors.fundamentals import MarketCap

def initialize(context):
    
    mypipe = make_pipeline()
    attach_pipeline(mypipe, "my_pipeline")
    
    # Schedule some functions
    schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))
    schedule_function(record_vars, date_rules.every_day(), time_rules.market_open())
    
def my_rebalance(context,data):
    
    # Get open orders
    open_orders = get_open_orders()
    
    # Gives me every position in my portfolio
    for security in context.longs:
        # If security not in pipeline, exit position
        if security not in context.longs and data.can_trade(security):
            order_target_percent(security,0)
            
    # For each position in my long list (from pipeline)
    for security in context.longs:
        if data.can_trade(security) and security not in open_orders:
            order_target_percent(security,context.weight_per_stock)
        

def compute_weights(context):
    
    # Simple equal weighted portfolio
    if len(context.longs) == 0:
        weight_per_stock = 0
        
    else:
        weight_per_stock = 1.0/len(context.longs)
    
    return weight_per_stock

def before_trading_start(context,data):
    
    # Calculated every day before trading starts.
    context.output = pipeline_output("my_pipeline")
    
    context.longs = context.output[context.output.Longs].index.tolist()

    context.weight_per_stock = compute_weights(context)

    
def record_vars(context,data):
    
    record(leverage = context.account.leverage)
       
# Pipeline created in research notebook
def make_pipeline():

    # Set market cap to $2Billion
    market_cap = Fundamentals.market_cap.latest
    
    # Set the current ratio
    current_ratios = operation_ratios.current_ratio.latest
    
    # Sets the PB ratios
    PB_Ratios = valuation_ratios.pb_ratio.latest
    
    # Sets the PE ratios
    PE_Ratios = valuation_ratios.pe_ratio.latest
        
    # Asks for sector codes (used in V2)
    sectors = morningstar.asset_classification.morningstar_sector_code.latest
    
    # Set the universe
    longs = (QTradableStocksUS() &
               (market_cap >= 2000000000)&
               (current_ratios >= 2)&
               (PB_Ratios >1)&
               (PB_Ratios <= 2.5)&
               (PE_Ratios <= 15))
    
    
    pipe = Pipeline(columns={"Market_Cap":market_cap,
                            "Current_Ratios":current_ratios,
                            "PB_Ratios":PB_Ratios,
                            "PE_Ratios":PE_Ratios,
                            "Sector_Code":sectors,
                            "Longs":longs},
                   screen = longs)
    
    return pipe
There was a runtime error.
3 responses

You had a minor logic error. I've attached the corrected code.

The basic problem is that when you were looking to sell positions not in context.longs but in your portfolio, you were iterating through the stocks in context.longs rather than the stocks in your portfolio. The logic change was line 24.

For reference though, the algorithm won't be of much interest for a capital allocation from Q because it's not long-short.

Clone Algorithm
3
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.morningstar import valuation_ratios, operation_ratios, cash_flow_statement
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.data import Fundamentals  
from quantopian.pipeline.factors.fundamentals import MarketCap

def initialize(context):
    
    mypipe = make_pipeline()
    attach_pipeline(mypipe, "my_pipeline")
    
    # Schedule some functions
    schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))
    schedule_function(record_vars, date_rules.every_day(), time_rules.market_open())
    
def my_rebalance(context,data):
    
    # Get open orders
    open_orders = get_open_orders()
    
    # Gives me every position in my portfolio
    for security in context.portfolio.positions:
        # If security not in pipeline, exit position
        if security not in context.longs and data.can_trade(security):
            order_target_percent(security,0)
            
    # For each position in my long list (from pipeline)
    for security in context.longs:
        if data.can_trade(security) and security not in open_orders:
            order_target_percent(security,context.weight_per_stock)
        

def compute_weights(context):
    
    # Simple equal weighted portfolio
    if len(context.longs) == 0:
        weight_per_stock = 0
        
    else:
        weight_per_stock = 1.0/len(context.longs)
    
    return weight_per_stock

def before_trading_start(context,data):
    
    # Calculated every day before trading starts.
    context.output = pipeline_output("my_pipeline")
    
    context.longs = context.output[context.output.Longs].index.tolist()

    context.weight_per_stock = compute_weights(context)

    
def record_vars(context,data):
    
    record(leverage = context.account.leverage)
       
# Pipeline created in research notebook
def make_pipeline():

    # Set market cap to $2Billion
    market_cap = Fundamentals.market_cap.latest
    
    # Set the current ratio
    current_ratios = operation_ratios.current_ratio.latest
    
    # Sets the PB ratios
    PB_Ratios = valuation_ratios.pb_ratio.latest
    
    # Sets the PE ratios
    PE_Ratios = valuation_ratios.pe_ratio.latest
        
    # Asks for sector codes (used in V2)
    sectors = morningstar.asset_classification.morningstar_sector_code.latest
    
    # Set the universe
    longs = (QTradableStocksUS() &
               (market_cap >= 2000000000)&
               (current_ratios >= 2)&
               (PB_Ratios >1)&
               (PB_Ratios <= 2.5)&
               (PE_Ratios <= 15))
    
    
    pipe = Pipeline(columns={"Market_Cap":market_cap,
                            "Current_Ratios":current_ratios,
                            "PB_Ratios":PB_Ratios,
                            "PE_Ratios":PE_Ratios,
                            "Sector_Code":sectors,
                            "Longs":longs},
                   screen = longs)
    
    return pipe
There was a runtime error.

Hey EL, that's pretty good for the first week into Quantopian as for me it felt like half a life time to get my journey going!

You are well on your way :o) as Quantopian is a treasure trove of research, tools, examples and a supportive community of diverse experiences and interests!

Have fun and good coding forward!

Hi Quant Trader, thanks so much for finding that. I figured something was off with the code but didn't know what. Honestly at this point in time I'm not really looking for an allocation, just want to learn for now before trying to enter the competition; I heard it's super hard to win anyways! Also, my strategy would have lost to a basic market index fund it looks like anyways lol.

Thanks for the words of encouragement Karl :) Your first algo looks really good I am excited to look at it more and see what you really did! I look forward to learning from everyone here!