Thank you very much Dan!
I've implemented the process of your Custom Factor Class in my 52 week high algorithm, but I seem to be receiving errors when the Pipeline integrates the column and screen data. I get an "AttributeError: 'int' object has no attribute 'ndim'" error when compiling. I know that the "new52WeekHigh" data is in an unacceptable format for the Pipeline and my the solution may be as simple as defining my own factor to process the new52WeekHigh data. If that is the case, I'm not sure how to create a factor that calls another factor (calling 'CloseOnN' from within 'new52WeekHigh'). I may be making a stupid mistake or missing something very fundamental, but I do not fully understand how the Pipeline works. By the way, I know what you mean by performing the calculation over a single array after population instead of using a loop, and I plan to simplify the code later by doing just that.
Again, thank you very much,
James
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage, AverageDollarVolume, Latest
class CloseOnN(CustomFactor):
inputs = [USEquityPricing.close]
window_length = 1
def compute(self, today, assets, out, close):
out[:] = close[0]
def initialize(context):
recentHigh = CloseOnN(window_length = 252)
pastHigh = CloseOnN(window_length = 7)
new52WeekHigh = 0
index = 251
while index > 7:
if (CloseOnN(window_length = index)) > pastHigh:
pastHigh = CloseOnN(window_length = index)
index = index -1
while (index > 0) and (index < 8):
if (CloseOnN(window_length = index)) > recentHigh:
recentHigh = CloseOnN(window_length = index)
index = index -1
if recentHigh > pastHigh:
new52WeekHigh = 1
else:
new52WeekHigh = 0
volume = Latest(inputs=[USEquityPricing.volume])
price = Latest(inputs=[USEquityPricing.close],window_length=1)
pipe_screen = ((price > 1.0) & (price < 20.0) & (new52WeekHigh > 0))
pipe_columns = {'volume':volume, 'price':price, 'new52WeekHigh':new52WeekHigh}
pipe = Pipeline(columns=pipe_columns,screen=pipe_screen)
attach_pipeline(pipe, 'test')
def before_trading_start(context, data):
output = pipeline_output('test')
context.my_securities = output.sort('volume', ascending=False).iloc[:50]
print len(context.my_securities)
context.security_list = context.my_securities.index
log.info("\n" + str(context.my_securities.head(5)))