Back to Community
Help with Tradable Universe Please

Hello Quantopian friends, I just started coding and this is my first strategy. It performs quite well but I would like some help changing it to use the entire tradable universe instead of the 150 or so stocks I have manually typed in. This would help me remove some selection bias and get better testing data. Thank you for any help!

Clone Algorithm
4
Loading...
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
'''
Simple moving average algorithm using pipeline to define data
'''

# Imports needed
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor
import quantopian.pipeline.filters as Filters
import quantopian.pipeline.factors as Factors
import pandas as pd
import numpy as np
from quantopian.pipeline.data.builtin import USEquityPricing

# LARGEST NASDAQ STOCKS PLUS SOME DOW STOCKS
my_stocks = symbols('AAPL','MSFT','AMZN','GOOG','FB','INTC','CSCO','CMCSA','PEP','NFLX','ADBE','PYPL','AVGO','NVDA','AMGN','TXN','COST','QCOM','SBUX','BKNG','CHTR','GILD','QQQ','ADP','INTU','CELG','CSX','CME','ISRG','AMOV','BIDU','MU','ILMN','MAR','BIIB','VRTX','ADI','AMAT','CTSH','ADSK','BND','EQIX','REGN','ROST','ATVI','XLNX','FISV','EBAY','ORLY','MNST','AMTD','AMD','PAYX','LRCX','ALXN','SIRI','XEL','DLTR','TEAM','TROW','PCAR','MELI','ALGN','FOX','MCHP','LULU','UAL','SBAC','VRSN','INFO','GOLD','CTAS','FITB','CTRP','NTRS','CERN','ULTA','LBTYB','FAST','LBTYA','KLAC','SHV','NTES','WMT','HD','V','PFE','NKE','PG','MRK','JNJ','GS','CVX','BA','JPM','VZ','MCD','KO','TRV','UTX','TWTR','FDX')             

# Dedicate equal available capital to each stock in the filtered universe
weight = 1.0 / len(my_stocks)


def initialize(context):

    set_commission(commission.PerShare(cost=0.0015, min_trade_cost=0.01))
    
    # Attach pipeline that will provide data
    attach_pipeline(pipe_definition(context), name='my_data')
  
    # Schedule trading and recording
    schedule_function(trade,
                      date_rules.every_day(),
                      time_rules.market_open(minutes=5),
                      time_rules.market_close(minutes=1))

    # Schedule when to record tracking data
    schedule_function(record_vars,
                      date_rules.every_day(),
                      time_rules.market_close())

         
def pipe_definition(context):
    '''
    This function pulls data and calculates SMAs
    '''
    universe = Filters.StaticAssets(my_stocks)
    close_price = USEquityPricing.close.latest
    sma_10 = Factors.SimpleMovingAverage(inputs=[USEquityPricing.close],
                                         window_length=17,
                                         mask=universe)   
    sma_50 = Factors.SimpleMovingAverage(inputs=[USEquityPricing.close],
                                         window_length=97,
                                         mask=universe)
    return Pipeline(
            columns = {
            'close_price': close_price,
            'sma_10': sma_10,
            'sma_50': sma_50
            },
            screen = universe,
            )
    
 
def before_trading_start(context, data):
    '''
    This function pulls the data and makes it available for other functions
    '''
    context.output = pipeline_output('my_data')
       
   
def trade(context, data):
    '''
    This function sets up the trading rules.
    '''
    
    #Buy a stock whenever the 10-day MA is above the 50
    open_rules = 'sma_10 > sma_50'
    open_these = context.output.query(open_rules).index.tolist()

    for stock in open_these:
        if stock not in context.portfolio.positions and data.can_trade(stock):
            order_target_percent(stock, weight)
    
    #Close a position whenever the 10-day MA is below the 50
    close_rules = 'sma_10 < sma_50'
    close_these = context.output.query(close_rules).index.tolist()
 
    for stock in close_these:
        if stock in context.portfolio.positions and data.can_trade(stock):
            order_target_percent(stock, 0)
                  

def record_vars(context, data):
    #Record the portfolio holdings each day
    record(leverage=context.account.leverage,
           positions=len(context.portfolio.positions))
There was a runtime error.