Notebook
In [13]:
# import pipeline stuff
from quantopian.pipeline import CustomFactor, Pipeline
from quantopian.research import run_pipeline

# import built in factors and filters
import quantopian.pipeline.factors as Factors
import quantopian.pipeline.filters as Filters
import quantopian.pipeline.classifiers as Classifiers
# import data
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar

# import these just in case we need them
import numpy as np
import pandas as pd
import scipy as scp
In [ ]:
 

Below is the original code. I'd use the built in 'make_us_equity_universe' filter unless there is some reason not to. See https://www.quantopian.com/help#built-in-filters

In [17]:
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = Filters.morningstar.IsPrimaryShare()

# Equities listed as common stock (as opposed to, say, preferred stock).
# 'ST00000001' indicates common stock.
common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')

# Non-depositary receipts. Recall that the ~ operator inverts filters,
# turning Trues into Falses and vice versa
not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest

# Equities not trading over-the-counter.
not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')

# Not when-issued equities.
not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')

# Equities without LP in their name, .matches does a match using a regular
# expression
not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[. ]?P.?$')

# Equities with a null value in the limited_partnership Morningstar
# fundamental field.
not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()

# Equities whose most recent Morningstar market cap is not null have
# fundamental data and therefore are not ETFs.
have_market_cap = morningstar.valuation.market_cap.latest.notnull()



# Filter for stocks that pass all of our previous filters.
tradeable_stocks = (
    primary_share
    & common_stock
    & not_depositary
    & not_otc
    & not_wi
    & not_lp_name
    & not_lp_balance_sheet
    & have_market_cap
)

original_universe = Factors.AverageDollarVolume(window_length=30, mask=tradeable_stocks).percentile_between(98, 100)

Let's make a universe of approximately 2% of the most liquid securities using 'make_us_equity_universe'. There's roughly 3000 tradable securities so set target size to 60. 'max_group_weight' is set to 30% to ensure no more than a 30% weighting in any one sector. This can be ommited if desired.

In [21]:
new_universe = Filters.make_us_equity_universe(
        target_size = 60,
        rankby = Factors.AverageDollarVolume(window_length=200),
        mask = Filters.default_us_equity_universe_mask(),
        groupby = Classifiers.morningstar.Sector(),
        max_group_weight = 0.3,
        smoothing_func = lambda f: f.downsample('month_start'),
    )
In [54]:
# a little faster implementation of log returns
class Log_Returns(CustomFactor):
    inputs = [USEquityPricing.close]
    window_length = 2
    
    def compute(self, today, asset_ids, out, close_prices):
        out[:] = np.nan_to_num(np.diff(np.log(close_prices), axis=0))
In [55]:
# Wouldn't bother using Log_Returns as an input. Just do the math here.
class Distribution_Estimation(CustomFactor):
    inputs = [USEquityPricing.close]
    outputs = ['mu','gam','H','GIGparam'] #Mu, Gam is a Nx1 Vector, H is a NxN Matrix and GIGparam is a 3x1
    
    window_length = 2
    
    def specified_function(log_returns, type_model_distribution, mu, gam, H, GIGparam):
        # do whatever logic is needed
        return mu, gam, H, GIGparam
    
    def compute(self, today, asset_ids, out, close_prices):
        # Mu, gam, H, GIGparam
        mu = []; gam = []; H = []; GIGparam = [];
        
        # below will replace any NaNs with zeros. Maybe this isn't desired?
        log_returns = np.nan_to_num(np.diff(np.log(close_prices), axis=0))
        
        type_model_distribution = 'Distribution'; 
        
        mu, gam, H, GIGparam = specified_function(log_returns, type_model_distribution, mu, gam, H, GIGparam)
        out.mu = mu; out.gam = gam; out.H = H; out.GIGparam = GIGparam        
In [56]:
def make_pipeline():
    window = 2
    
    #log Returns are preferred
    log_returns = Log_Returns(window_length = window, mask = new_universe)
    
    #regular Returns
    returns = Factors.Returns(inputs = [USEquityPricing.close], window_length = window, mask = new_universe)
    
    output = Distribution_Estimation(mask = new_universe)
    
    return Pipeline(
        columns = {
            'log_returns': log_returns,
        },
        screen = new_universe
    )
In [57]:
result = run_pipeline(make_pipeline(), '2015-05-05', '2015-05-06')
In [58]:
result
Out[58]:
log_returns
2015-05-05 00:00:00+00:00 Equity(24 [AAPL]) -0.001941
Equity(239 [AIG]) 0.007591
Equity(368 [AMGN]) 0.011665
Equity(679 [AXP]) 0.007502
Equity(698 [BA]) -0.004018
Equity(700 [BAC]) 0.021506
Equity(1267 [CAT]) -0.000916
Equity(1335 [C]) 0.007413
Equity(1406 [CELG]) -0.005899
Equity(1637 [CMCS_A]) 0.006828
Equity(1900 [CSCO]) 0.001716
Equity(2190 [DIS]) 0.004604
Equity(2263 [DOW]) -0.000581
Equity(2564 [EOG]) 0.004640
Equity(2673 [F]) -0.001267
Equity(3149 [GE]) -0.001099
Equity(3212 [GILD]) 0.006076
Equity(3443 [HAL]) 0.002034
Equity(3496 [HD]) 0.005101
Equity(3766 [IBM]) 0.002474
Equity(3806 [BIIB]) -0.000389
Equity(3951 [INTC]) 0.000000
Equity(4151 [JNJ]) 0.002295
Equity(4283 [KO]) 0.001221
Equity(4707 [MCD]) -0.017171
Equity(4758 [MDT]) 0.003974
Equity(5029 [MRK]) 0.013111
Equity(5061 [MSFT]) -0.008463
Equity(5121 [MU]) -0.011619
Equity(5692 [ORCL]) 0.005170
... ... ...
2015-05-06 00:00:00+00:00 Equity(5923 [PFE]) -0.006138
Equity(5938 [PG]) -0.003491
Equity(6295 [QCOM]) -0.010042
Equity(6653 [T]) -0.023737
Equity(6928 [SLB]) -0.009944
Equity(8151 [WFC]) 0.000000
Equity(8229 [WMT]) -0.013476
Equity(8347 [XOM]) -0.005346
Equity(8572 [AGN]) -0.014493
Equity(12213 [FOXA]) -0.016085
Equity(14848 [YHOO]) -0.017279
Equity(16841 [AMZN]) -0.004383
Equity(19917 [PCLN]) -0.002940
Equity(20088 [GS]) -0.010086
Equity(21839 [VZ]) -0.008150
Equity(23112 [CVX]) -0.002682
Equity(23709 [NFLX]) 0.018839
Equity(23998 [COP]) 0.002085
Equity(24819 [EBAY]) -0.020165
Equity(25006 [JPM]) -0.004942
Equity(26578 [GOOG_L]) -0.017611
Equity(33729 [DAL]) -0.031058
Equity(35920 [V]) 0.006082
Equity(39840 [TSLA]) 0.009948
Equity(40852 [KMI]) -0.003510
Equity(42950 [FB]) -0.015732
Equity(43694 [ABBV]) -0.013072
Equity(45815 [TWTR]) -0.011954
Equity(45971 [AAL]) -0.040235
Equity(47208 [GPRO]) -0.041258

120 rows × 1 columns

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: