Back to Community
adding ETFs to filtered stocks

Hi, I am new to quantopian and just starting to learn how to build my first algo. I like to pick the top 3000 stocks by market cap. In addition, I like to add quite a number of (US+foreign) ETFs (whose market cap might not make to the top 3000) to that list before running a ranking of features. How could I do that? Thanks

2 responses

First off, welcome!

To add fixed or static assets to your universe of potential stocks use the StaticAssets filter. (see the docs https://www.quantopian.com/help#built-in-filters ).

Something like this

    # Base universe set to the QTradableStocksUS  
    # This is includes only stocks and is recommended as a base for most trading universes  
    base_universe = QTradableStocksUS()  


    # Select largest 3000 stocks by market cap from the initial base  
    # Use base_universe as a mask to begin with that subset of stocks  
    top_3000 = MarketCap(mask=base_universe).top(3000)


    # Select some fixed ETFs  
    my_etfs = StaticAssets(symbols('SPY', 'VTI', 'GSIE'))  


    # my universe is the top 3000 plus my etfs  
    my_universe = top_3000 | my_etfs

Check out the attached algo to see it run. Good luck.

Clone Algorithm
9
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 is a stategy to demonstrate ordering by fixed weights

"""

# import pipeline methods 
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor

# import the built in filters and factors
from quantopian.pipeline.filters import QTradableStocksUS, StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage, Returns
from quantopian.pipeline.factors.fundamentals import MarketCap

# import any datasets we need
from quantopian.pipeline.data import Fundamentals

from quantopian.pipeline.data.builtin import USEquityPricing

# import optimize
import quantopian.optimize as opt

# import numpy and pandas just in case
import numpy as np
import pandas as pd


def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    # Set the constant weight we want
    context.target_leverage = 1.0
    context.target_stock_qty = 100
    context.target_weight = context.target_leverage / context.target_stock_qty

    # Set up our pipeline
    attach_pipeline(make_pipeline(context), 'pipeline')
    
    # order every day, 1 hour after market open.
    schedule_function(
        my_orders_using_optimize,
        date_rules.every_day(),
        time_rules.market_open(hours=1),
        )
def make_pipeline(context):
    """
    A function to create our dynamic stock selector (pipeline). Documentation
    on pipeline can be found here:
    https://www.quantopian.com/help#pipeline-title
    """

    # Base universe set to the QTradableStocksUS
    # This is only stocks
    base_universe = QTradableStocksUS()
    
    # Select largest 3000 stocks by market cap
    # Use base_universe as a mask to only use those stocks
    top_3000 = MarketCap(mask=base_universe).top(3000)

    # Select some fixed ETFs
    my_etfs = StaticAssets(symbols('SPY', 'VTI', 'GSIE'))
    
    # my universe is the top 3000 plus my etfs
    my_universe = top_3000 | my_etfs
    
    # Factor for 5 day return.
    returns = Returns(window_length=5)
    
    # Long the top 50 returns / short the bottom 50
    longs = returns.top(context.target_stock_qty/2, mask=my_universe)
    shorts = returns.bottom(context.target_stock_qty/2, mask=my_universe)

    pipe = Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts,
        },
        screen=my_universe
    )
    return pipe


def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('pipeline')
    context.my_longs = context.output.query('longs==True').index.tolist()
    context.my_shorts = context.output.query('shorts==True').index.tolist()

def my_orders_using_optimize(context, data):
    """
    Use Optimize to place orders all at once
    """
    # Specify our series with the weights we want
    # Need to specify BOTH the securities (as the index) and the weight
    # Specify the shorts with a negative weight
    my_long_weights = pd.Series(index=context.my_longs, data=context.target_weight)
    my_short_weights = pd.Series(index=context.my_shorts, data=-context.target_weight)

    my_weights = pd.concat([my_long_weights, my_short_weights])
    
    # Create our target weight objective
    weight_objective = opt.TargetWeights(my_weights) 
    
    # Set the constraints
    pass
    
    # Execute the order_optimal_portfolio method with above objective and constraint
    order_optimal_portfolio(objective = weight_objective, 
                            constraints = [])
There was a runtime error.

Thank you!