I wanted to restrict my universe to a certain index such as S&P 500.
I thought "Dollar-Volume Universe" is not what I was looking for, so I modified one of example codes in the Help page. I was wondering if my code is correct.
If historical S&P 500 component list at a certain point in the past can be easily found, I can verify whether this code is working well or not. However, I found it is pretty hard to find such component data.. so I have no way of checking the output is correct or not at this point.
class MarketCap(CustomFactor):
# Pre-declare inputs and window_length
inputs = [USEquityPricing.close, morningstar.valuation.shares_outstanding]
window_length = 1
# Compute market cap value
def compute(self, today, assets, out, close, shares):
out[:] = close[-1] * shares[-1]
def initialize(context):
pipe = Pipeline()
attach_pipeline(pipe, 'example')
# Construct the custom factor
mkt_cap = MarketCap()
pipe.add(mkt_cap, 'mkt_cap')
pipe.add(mkt_cap.rank(ascending=False), 'mkt_cap_rank')
# Use screen to narrow the universe
pipe.set_screen(mkt_cap.top(100))
def before_trading_start(context, data):
context.output = pipeline_output('example')
context.large_cap = context.output.sort(['mkt_cap'], ascending=False)#.iloc[:10]
update_universe(context.large_cap.index)
def handle_data(context, data):
log.info("\n" + str(context.large_cap.head()))
log.info("\n" + str(context.large_cap.tail()))