I am trying to set the factor betas to zero, but scipy minimize 'cobyla' fails due to constraint violation. Anyone?

I get the following error when I set factor betas = zero.

Did not converge to a solution satisfying the constraints. See `maxcv`

for magnitude of violation.

Clone Algorithm

7

Loading...

There was an error loading this backtest.

Backtest from
to
with
initial capital

Cumulative performance:

Algorithm
Benchmark

Custom data:

Total Returns

--

Alpha

--

Beta

--

Sharpe

--

Sortino

--

Max Drawdown

--

Benchmark Returns

--

Volatility

--

Returns | 1 Month | 3 Month | 6 Month | 12 Month |

Alpha | 1 Month | 3 Month | 6 Month | 12 Month |

Beta | 1 Month | 3 Month | 6 Month | 12 Month |

Sharpe | 1 Month | 3 Month | 6 Month | 12 Month |

Sortino | 1 Month | 3 Month | 6 Month | 12 Month |

Volatility | 1 Month | 3 Month | 6 Month | 12 Month |

Max Drawdown | 1 Month | 3 Month | 6 Month | 12 Month |

import math import numpy as np import pandas as pd import talib from sklearn.decomposition import PCA import statsmodels.api as smapi from sklearn.covariance import OAS from scipy.optimize import minimize from sklearn.linear_model import LassoCV def getweights(params, cov, signal): cons = [] (m,n) = np.shape(params) for i in range(0, n): cons.append({'type': 'ineq', 'fun': lambda x, i=i: np.dot(x.T, params[:, i])}) cons.append({'type': 'ineq', 'fun': lambda x, i=i: -np.dot(x.T, params[:, i])}) cons.append({'type': 'ineq', 'fun': lambda x: np.dot(x, signal) - 0.01}) for i in range(0, m): cons.append({'type': 'ineq', 'fun': lambda x, i=i: 1 - abs(x[i]) }) cons.append({'type': 'ineq', 'fun': lambda x, i=i: abs(x[i]) - 0.1 }) x0 = [1.] * m res = minimize(lambda x: -np.dot(x.T, signal) / np.dot(np.dot(x.T, cov), x), x0, constraints = cons, method='cobyla',options={'maxiter':2000}) print res.message return res.x def initialize(context): schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes=30)) context.SPY = sid(19655) context.done = False def handle_data(context, data): pass def trade(context, data): prices = data.history(context.univ, "price", 120, "1d") prices = prices.dropna(axis=1) returns = prices.pct_change().dropna().values returns = returns * 1000. cov = OAS().fit(returns).covariance_ e, v = np.linalg.eig(cov) idx = e.argsort() comp = v[:, idx[-25:]] if comp[0, 0] < 0: comp *= -1 sources = np.dot(returns, comp) betas = np.zeros((np.shape(returns)[1], np.shape(sources)[1])) for i in range(0, np.shape(returns)[1]): model = smapi.RLM(returns[:, i], smapi.add_constant(sources)).fit() betas[i, :] = model.params[1:] signal = np.sum(returns[-15:, :], axis=0) / np.std(returns, axis=0) W = getweights(betas, cov, signal) den = np.sum(np.abs(W)) if den == 0: den = 1 wsum = 0 for i, sid in enumerate(prices): val = W[i] / den * context.portfolio.portfolio_value * 2. order_target_value(sid, val) wsum += val order_target_value(context.SPY, -wsum) def before_trading_start(context, data): if context.done: return context.done = True fundamental_df = get_fundamentals( query(fundamentals.valuation_ratios.ev_to_ebitda) .filter(fundamentals.valuation.market_cap != None) .filter(fundamentals.asset_classification.morningstar_sector_code == 309) .filter(fundamentals.company_reference.primary_exchange_id != "OTCPK") # no pink sheets .filter(fundamentals.share_class_reference.security_type == 'ST00000001') # common stock only .filter(~fundamentals.share_class_reference.symbol.contains('_WI')) # drop when-issued .filter(fundamentals.share_class_reference.is_primary_share == True) # remove ancillary classes .filter(fundamentals.share_class_reference.is_depositary_receipt == False) # !ADR/GDR .filter(fundamentals.valuation_ratios.ev_to_ebitda > 0) .order_by(fundamentals.valuation.market_cap.desc()).limit(25)).T context.univ = fundamental_df[0:25].index