Notebook
In [1]:
from quantopian.pipeline import CustomFactor, Pipeline
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.factors import AverageDollarVolume, Returns
import numpy as np
import scipy as scp
import pandas
In [2]:
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = 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
)

base_universe = AverageDollarVolume(window_length=30, mask=tradeable_stocks).percentile_between(98, 100)
In [3]:
class Log_Returns(CustomFactor):
    inputs = USEquityPricing.close # iterable, optional
    mask = base_universe
    
    def compute(self, today, asset_ids, out, values):
        if np.isnan(values) or np.isnan(values[-1]):
            out[:] = 0
        else:
            out[:] = np.log(values/values[-1])
In [5]:
class Distribution_Estimation(CustomFactor):
    inputs = [Log_Returns]
    outputs = ['mu','gam','H','GIGparam'] #Mu, Gam is a Nx1 Vector, H is a NxN Matrix and GIGparam is a 3x1
    mask = base_universe
    
    def compute(self, today, asset_ids, out, Log_Returns):
        # Mu, gam, H, GIGparam
        mu = []; gam = []; H = []; GIGparam = [];
        Log_Returns = np.nan_to_num(Log_Returns)
        type_model_distribution = 'Distribuiton';        
        mu, gam, H, GIGparam = specifided_Function(Log_Returns, type_model_distribution, mu, gam, H, GIGparam)
        out.mu = mu; out.gam = gam; out.H = H; out.GIGparam = GIGparam        
In [6]:
def make_pipeline():
    window = 1
    
    #log Returns are preferred
    log_returns = Log_Returns(window_length = 1)
    
    #regular Returns
    returns = Returns(inputs = USEquityPricing.close, window_length = window+1, missing_value = )
    
    
    output = Distribution_Estimation(window_length=window)
   
    
    return Pipeline(
        columns={
            'log_returns': logreturns
        }
    )
  File "<ipython-input-6-583d7c1227d1>", line 8
    returns = Returns(inputs = USEquityPricing.close, window_length = window+1, missing_value = )
                                                                                                ^
SyntaxError: invalid syntax
In [47]:
result = run_pipeline(make_pipeline(), '2015-05-05', '2015-05-06')

TypeErrorTraceback (most recent call last)
<ipython-input-47-a81379f02a34> in <module>()
----> 1 result = run_pipeline(make_pipeline(), '2015-05-05', '2015-05-06')

<ipython-input-46-636460a794ff> in make_pipeline()
      1 def make_pipeline():
      2     window = 1
----> 3     logreturns = Log_Returns(window_length = 1)
      4     output = Distribution_Estimation(window_length=window)
      5 

/build/src/qexec_repo/zipline_repo/zipline/pipeline/mixins.pyc in __new__(cls, inputs, outputs, window_length, mask, dtype, missing_value, ndim, **kwargs)
    138             missing_value=missing_value,
    139             ndim=ndim,
--> 140             **kwargs
    141         )
    142 

/build/src/qexec_repo/zipline_repo/zipline/pipeline/term.pyc in __new__(cls, inputs, outputs, window_length, mask, *args, **kwargs)
    451             # Allow users to specify lists as class-level defaults, but
    452             # normalize to a tuple so that inputs is hashable.
--> 453             inputs = tuple(inputs)
    454 
    455         if outputs is NotSpecified:

/build/src/qexec_repo/zipline_repo/zipline/pipeline/term.py in __getitem__(self, key)
    206     @expect_types(key=Asset)
    207     def __getitem__(self, key):
--> 208         if isinstance(self, LoadableTerm):
    209             raise NonSliceableTerm(term=self)
    210         return Slice(self, key)

/build/src/qexec_repo/zipline_repo/zipline/utils/input_validation.pyc in _check(func, argname, argvalue)
    443                     'funcname': get_funcname(func),
    444                     'argname': argname,
--> 445                     'actual': actual(argvalue),
    446                 },
    447             )

TypeError: zipline.pipeline.term.__getitem__() expected a value of type zipline.assets._assets.Asset for argument 'key', but got int instead.
In [50]:
Returns?
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: