Hello Quantopians,
Could someone please help me finish this algo. This is an attempt to re-create the minimum correlation algo based on the post here. I have been working on fixing the error for 5 hours now but still no luck. It throws me an error with the list of all the stocks selected.
I am not sure why I am not able to see the code in the posted backtest. So I am pasting all the code here.
from quantopian.pipeline.filters import Q500US
from quantopian.pipeline.factors import DailyReturns
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data import Fundamentals, USEquityPricing
import numpy as np
import math
import scipy
def initialize(context):
schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes = 30))
attach_pipeline(make_pipeline(), 'pipeline')
def make_pipeline():
m = Q500US()
ret = DailyReturns()
quality = ret
good = quality.top(20, mask = m)
bad = quality.bottom(20, mask = m)
pipe = Pipeline(columns={'good':good, 'bad':bad}, screen = (good | bad))
return pipe
def trade(context, data):
output = pipeline_output('pipeline')
longlist = output[output.good].index
shortlist = output[output.bad].index
prices = np.log(history(30, '1d', 'price').dropna(axis=1))
daily_R = prices.pct_change().dropna()
longs = get_reduced_correlation_weights(daily_R[longlist])
shorts = get_reduced_correlation_weights(daily_R[shortlist])
for stock in data:
if stock in shortlist:
order_target_percent(stock, -0.5 * shorts[stock])
elif stock in longlist:
order_target_percent(stock, 0.5 * longs[stock])
else:
order_target(stock, 0)
def get_reduced_correlation_weights(returns, risk_adjusted=True):
correlations = returns.corr()
adj_correlations = get_adjusted_cor_matrix(correlations)
initial_weights = adj_correlations.T.mean()
ranks = initial_weights.rank()
ranks /= ranks.sum()
weights = adj_correlations.dot(ranks)
weights /= weights.sum()
if risk_adjusted:
weights = weights / returns.std()
weights /= weights.sum()
return weights
def get_adjusted_cor_matrix(cor):
values = cor.values.flatten()
mu = np.mean(values)
sigma = np.std(values)
distribution = scipy.stats.norm(mu, sigma)
return 1 - cor.apply(lambda x: distribution.cdf(x))