I think if possible I should do this set of code through pipeline:
"""
Calculate z-score for all stocks in list
"""
# Get pricing data for the last month
stock_price = data.history(stock, 'price', 30, '1d')
# Calculate the returns from past prices
stock_returns = stock_price.pct_change()[1:]
# Calculate z-score of the current returns
zscore = (np.mean(stock_returns[-5]) - np.mean(stock_returns)) / np.std(stock_returns, ddof = 2)
return zscore
and keep this set of code to use long_weight and short_weight in the optimize API to optimize weights with leverage and position constraints:
"""
Calculate weights to be optimized
"""
# Initialize lists
context.longs = []
context.shorts = []
context.zscore= 0.00
long_weight=0.00
short_weight=0.00
"""
Implement this logic within pipeline
"""
for stock in context.my_securities:
context.zscore = calculate_zscore(stock,data)
if get_open_orders():
return
# Determine percent of portfolio that can be invested
available_percent = max(2.0 - context.account.leverage, 0.0)
# When to go long
if context.zscore < -1.65:
context.longs.append(stock)
# When to go short
if context.zscore > 1.65:
context.shorts.append(stock)
if len(context.longs) > 0:
# Distribute the available percent across longs
long_weight = (0.8 * available_percent) / len(context.longs)
if len(context.shorts) > 0:
# Distribute the available percent across shorts
short_weight = (-0.2 * available_percent) / len(context.shorts)
return long_weight, short_weight
Thoughts?