def test_cov_to_corr(): df = get_data() rets = risk_models.returns_from_prices(df).dropna() test_corr = risk_models.cov_to_corr(rets.cov()) pd.testing.assert_frame_equal(test_corr, rets.corr()) with pytest.warns(RuntimeWarning) as w: test_corr_numpy = risk_models.cov_to_corr(rets.cov().values) assert len(w) == 1 assert str(w[0].message) == "cov_matrix is not a dataframe" np.testing.assert_array_almost_equal(test_corr_numpy, rets.corr().values)
def plot_covariance(cov_matrix, plot_correlation=False, show_tickers=True, ax=None): """Generate a basic plot of the covariance (or correlation) matrix, given a covariance matrix. Args: cov_matrix (pd.DataFrame, np.ndarray): covariance matrix plot_correlation (bool): whether to plot the correlation matrix instead, defaults to False. Optional. show_tickers (bool): whether to use tickers as labels (not recommended for large portfolios). Optional. Defaults to True. ax (matplolib.axis, None): Axis to plot on. Optional. New axis will be created if none is specified. Returns: matplotlib axis """ if plot_correlation: matrix = risk_models.cov_to_corr(cov_matrix) else: matrix = cov_matrix if ax is None: _, ax = plt.subplots() if show_tickers: ax.set_xticks(np.arange(0, matrix.shape[0], 1)) ax.set_xticklabels(matrix.index) ax.set_yticks(np.arange(0, matrix.shape[0], 1)) ax.set_yticklabels(matrix.index) plt.xticks(rotation=90) return ax
def test_corr_to_cov(): df = get_data() rets = risk_models.returns_from_prices(df).dropna() test_corr = risk_models.cov_to_corr(rets.cov()) new_cov = risk_models.corr_to_cov(test_corr, rets.std()) pd.testing.assert_frame_equal(new_cov, rets.cov()) with pytest.warns(RuntimeWarning) as w: cov_numpy = risk_models.corr_to_cov(test_corr.to_numpy(), rets.std()) assert len(w) == 1 assert str(w[0].message) == "corr_matrix is not a dataframe" assert isinstance(cov_numpy, pd.DataFrame) np.testing.assert_equal(cov_numpy.to_numpy(), new_cov.to_numpy())
def test_corr_to_cov(): df = get_data() rets = risk_models.returns_from_prices(df).dropna() test_corr = risk_models.cov_to_corr(rets.cov()) new_cov = risk_models.corr_to_cov(test_corr, rets.std()) pd.testing.assert_frame_equal(new_cov, rets.cov())
def CorrMap(sht, nameplot, S, color): fig = plt.figure(figsize=(8, 8)) corrmatrice = risk_models.cov_to_corr(S) ax = sns.heatmap(corrmatrice, annot=True, cmap=color) fig = ax.get_figure() sht.pictures.add(fig, name=nameplot, update=True)
def Markmain(): #Set Sheets sht = xw.Book.caller().sheets['Optim'] shtdata = xw.Book.caller().sheets['Data'] shtfodata = xw.Book.caller().sheets['FoDatas'] sht.range('F17').value = 'Optimizing...' #Clear Values sht.range('D23').expand().clear_contents() shtdata.range('A1').expand().clear_contents() shtdata.range('J1').expand().clear_contents() #Datas listticker = xw.Range('B3').expand().value startdate = sht.range('F3').value enddate = sht.range('F6').value traintestdate = sht.range( 'F4' ).value #Dataset is divided in two sub: train (optimization) and test for backtest #train, test = initialize(startdate, enddate, traintestdate, listticker) train, test, tickers = loaddata(shtfodata, startdate, enddate, traintestdate) #Copy Data in Data Range shtdata.range((1, 1)).value = train shtdata.range((1, len(tickers) + 3)).value = test #Set variables ModelOptim = sht.range('F7').value ReturnModel = sht.range('F8').value RiskModel = sht.range('F9').value RFrate = sht.range('F10').value MinWeight = sht.range('F11').value MaxWeight = sht.range('F12').value InitialAmountInPortfolio = sht.range('F13').value RefIndex = sht.range('F14').value Gamma = sht.range('F15').value EFBool = sht.range('F16').value pltweights, rdf, cleanW, S, mu, perf = optimMarkowitz( train, test, MinWeight, MaxWeight, ModelOptim, ReturnModel, RiskModel, Gamma, RFrate) numshares, left, listshares = getoptimprices(train, cleanW, InitialAmountInPortfolio) #Visualisation corrmatrice = risk_models.cov_to_corr(S) CorrMap(sht, 'CorrMatMark', corrmatrice, 'YlGnBu') backtest_static(pltweights, rdf, ModelOptim, traintestdate, enddate, RefIndex, sht) if EFBool == "YES": effrontier(mu, S, sht, 'EFMark') #sht.range('F23').options(transpose=True).value = listshares sht.range('D23').options(transpose=True).value = tickers sht.range('E23').options(transpose=True).value = pltweights sht.charts['MarkoWeights'].set_source_data( sht.range((23, 4), (22 + len(tickers), 5))) sht.range('D21').value = perf sht.range('F17').value = 'Optimization Done'