Hi guys, I am still new to pipeline. I have gotten some variables in my pipeline and they have been attached, now to the pipeline. I am now struggling to get them into a loop so I can purchase the stock.
from quantopian.pipeline import Pipeline
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters import Q500US
from quantopian.pipeline.factors import AverageDollarVolume,SimpleMovingAverage
def initialize(context):
spy=Q500US()
ev = morningstar.valuation.enterprise_value.latest
mean_50 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=50,mask=spy)
mean_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200, mask=spy)
cf=morningstar.cash_flow_statement.free_cash_flow.latest
fin_health=morningstar.asset_classification.financial_health_grade.latest
earnings=morningstar.balance_sheet.retained_earnings.latest
pipe=Pipeline()
ma_cross=mean_50>mean_200
free_cash=cf.percentile_between(90,100)
earn=earnings.percentile_between(90,100)
mkt_cap =ev.percentile_between(90,100)
looking for 90% percentile in mkt_cap, earnings, and free cash flow
pipe.set_screen(ma_cross & free_cash & earn & mkt_cap)
pipe.add(free_cash,"fc")
# Attach the pipeline to the algorithm (basically store the pipe object reference and give it a name for easy use later)
pipe.add(fin_health,"fin_health")
attach_pipeline(pipe,'my_pipeline')
def weight(context):
long_weight=1.0/len(context.longs)
return long_weight
def before_trading_start(context,data):
context.output=pipeline_output('my_pipeline')
print(context.output)
context.longs = context.output[context.output['fc']].index.tolist()
context.long_weight = weight(context)
#how do I get context.longs in a loop?
print(context.longs)
def rebalance(context,data):
for stock in context.portfolio.positions:
if stock not in context.longs and data.can_trade(stock):
order_target_percent(stock,0)
for stock in context.longs:
if data.can_trade(stock):
order_target_percent(stock,context.long_weight)