Ok, I'm trying to create a mask on a CustomFactor. My end goal is to find the Mean or Median P/E ratio of my base universe.
In this algo I just have a random custom factor that I'm trying to mask. I've spent about an hour playing around trying to mask my custom factor but keep getting the error you'll see below.
import numpy as np
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage, AverageDollarVolume
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
def do_something_expensive():
#This is just an example but I'm trying to figure out sum all pe_ratios first, then divide each securities PE by the total PE of the universe of stocks
total=morningstar.valuation_ratios.pe_ratio.sum()
PE=morningstar.valuation_ratios.pe_ratio.latest
return PE/total
class MyFactor(CustomFactor):
#I don't understand this input part. What needs to go here?
inputs=morningstar.valuation_ratios.pe_ratio.latest
#I don't understand what each of these arguments in the compute function mean either?
def compute(self, today, asset_ids, out, close):
out[:] = do_something_expensive(close)
def initialize(context):
pipe=Pipeline()
pipe=attach_pipeline(pipe, name='my_pipeline')
sma_10=SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10)
sma_30=SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30)
tradersentiment=stocktwits.bull_scored_messages.latest
tradersentiment2=stocktwits.bear_scored_messages.latest
screen1=tradersentiment>tradersentiment2
prices_under_5=2<sma_10<5
screen2=AverageDollarVolume(window_length=10, mask=prices_under_5).percentile_between(90,100)
finalverse=screen2&screen1
#I want to mask my custom factor to ONLY RUN on my securities listed by screen2, however I continue to get an error 'ValueError: Latest does not have multiple outputs. There was a runtime error on line 54.'
my_factor = MyFactor(mask=screen2)
pipe.add(sma_10, '10 day average')
pipe.add(sma_30, '30 day average')
pipe.add(tradersentiment, 'Bullish')
pipe.add(tradersentiment2, 'Bearish')
pipe.add(my_factor, 'my_factor')
pipe.set_screen(finalverse)
def before_trading_start(context, data):
results=pipeline_output('my_pipeline')
print results.head(10)
context.pipeline_results=results