Maybe something like this?
# data.history returns a pandas dataframe. rows are dates. columns are securities.
hist = data.history(context.alle, "price", 200, "1d")
# pandas dataframes can easily perform math over all securities in a single statement
# the result is a pandas series which is magically now indexed by security
sma_200 = hist.mean(axis=0)
sma_50 = hist.iloc[-50:].mean(axis=0)
# put the two series together into a single dataframe for easy manipulation
my_data = pd.concat([sma_200, sma_50], axis=1)
# name the columns to be something readible
my_data.columns = ['sma_200', 'sma_50']
# use the pandas query method to perform whatever logic one wishes on the columns.
# This becomes your 'buy rule'
# it will return a list with only those securities that pass
buy_rule = 'sma_50 > sma_200'
ps = my_data.query(buy_rule).index.tolist()
# to get the number of securities which pass use len()
# set the weight but consider the situation where len = 0
weight = 1.0 / len(ps)
weight = 0.0
# order the target value of all stocks which pass your criteria
for stock in ps:
# close out all current positions which don't meet the criteria
for stock in context.portfolio.positions:
if stock not in ps and data.can_trade(stock):
Since you are using daily data only, pipeline should maybe be used rather than the 'data.history' method. It will be faster and the 'rules' may be easier by using the factor methods. Just an idea. See attached algorithm which is a modified version of the original.