Notebook
In [6]:
from quantopian.pipeline import Pipeline
import quantopian.optimize as opt
import quantopian.pipeline.factors as Factors
import quantopian.pipeline.filters as Filters
from quantopian.pipeline.data.factset import Fundamentals
from quantopian.pipeline.domain import US_EQUITIES

import numpy as np
import pandas as pd
 
SECURITY_UNIVERSE = Fundamentals.cash_only.latest.top(20)
 
def initialize(context):
    
    set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0))
 
    set_long_only()
    
    attach_pipeline(my_pipeline(context), name='my_pipeline')

    schedule_function(enter_trades, date_rules.every_day(), time_rules.market_open())
    
    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
 
    
def my_pipeline(context):
    
    universe = Filters.StaticAssets(SECURITY_UNIVERSE)
 
    cash_only = Fundamentals.cash_only.latest
 
    return Pipeline(
            columns = {
            'cash_only' : cash_only,
            },
            screen = universe,
            )
 
def before_trading_start(context, data):
    
    context.output = pipeline_output('my_pipeline')
 
def enter_trades(context, data):

    securities_to_hold = context.output.query('cash_only > 10000000000.0').index

    weight = 1.0 / len(securities_to_hold)
    weights = pd.Series(index = securities_to_hold, data = weight)
    
    target_weights = opt.TargetWeights(weights)
    
    order_optimal_portfolio(objective = target_weights, constraints = [])
 
def my_record_vars(context, data):
            
    record(securities = len(context.portfolio.positions))
    pass
    
In [ ]: