Exemplo n.º 1
0
def test_quasi_dag():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    hrp.optimize()
    clusters = hrp.clusters
    assert HRPOpt._get_quasi_diag(clusters)[:5] == [12, 6, 15, 14, 2]
Exemplo n.º 2
0
def test_dendrogram_plot():
    plt.figure()
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    hrp.optimize()

    ax = plotting.plot_dendrogram(hrp, showfig=False)
    assert len(ax.findobj()) == 185
    assert type(ax.findobj()[0]) == matplotlib.collections.LineCollection
    plt.clf()

    ax = plotting.plot_dendrogram(hrp, show_tickers=False, showfig=False)
    assert len(ax.findobj()) == 65
    assert type(ax.findobj()[0]) == matplotlib.collections.LineCollection
    plt.clf()
    plt.close()

    # Test that passing an unoptimized HRPOpt works, but issues a warning as
    #  this should already have been optimized according to the API.
    hrp = HRPOpt(returns)
    with pytest.warns(RuntimeWarning) as w:
        ax = plotting.plot_dendrogram(hrp, show_tickers=False, showfig=False)
        assert len(w) == 1
        assert (str(w[0].message) ==
                "hrp param has not been optimized.  Attempting optimization.")
        assert len(ax.findobj()) == 65
        assert type(ax.findobj()[0]) == matplotlib.collections.LineCollection
    plt.clf()
    plt.close()
Exemplo n.º 3
0
def hrp(my_portfolio, perf=True) -> list:
    # changed to take in desired timeline, the problem is that it would use all historical data

    ohlc = yf.download(
        my_portfolio.portfolio,
        start=my_portfolio.start_date,
        end=my_portfolio.end_date,
        progress=False,
    )
    prices = ohlc["Adj Close"].dropna(how="all")
    prices = prices.filter(my_portfolio.portfolio)

    # sometimes we will pick a date range where company isn't public we can't set price to 0 so it has to go to 1
    prices = prices.fillna(1)

    rets = expected_returns.returns_from_prices(prices)
    hrp = HRPOpt(rets)
    hrp.optimize()
    weights = hrp.clean_weights()

    wts = weights.items()

    result = []
    for val in wts:
        a, b = map(list, zip(*[val]))
        result.append(b)

    if perf is True:
        hrp.portfolio_performance(verbose=True)

    return flatten(result)
Exemplo n.º 4
0
def test_portfolio_performance():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    with pytest.raises(ValueError):
        hrp.portfolio_performance()
    hrp.optimize()
    assert hrp.portfolio_performance()
Exemplo n.º 5
0
def test_pass_cov_matrix():
    df = get_data()
    S = CovarianceShrinkage(df).ledoit_wolf()
    hrp = HRPOpt(cov_matrix=S)
    hrp.optimize()
    perf = hrp.portfolio_performance()
    assert perf[0] is None and perf[2] is None
    np.testing.assert_almost_equal(perf[1], 0.10002783894982334)
Exemplo n.º 6
0
def test_portfolio_performance():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    with pytest.raises(ValueError):
        hrp.portfolio_performance()
    hrp.optimize()
    np.testing.assert_allclose(
        hrp.portfolio_performance(),
        (0.21353402380950973, 0.17844159743748936, 1.084579081272277),
    )
Exemplo n.º 7
0
def test_dendrogram_plot():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    hrp.optimize()

    ax = Plotting.plot_dendrogram(hrp, showfig=False)
    assert len(ax.findobj()) == 185
    assert type(ax.findobj()[0]) == matplotlib.collections.LineCollection

    ax = Plotting.plot_dendrogram(hrp, show_tickers=False, showfig=False)
    assert len(ax.findobj()) == 65
    assert type(ax.findobj()[0]) == matplotlib.collections.LineCollection
Exemplo n.º 8
0
def test_hrp_errors():
    with pytest.raises(ValueError):
        hrp = HRPOpt()

    df = get_data()
    returns = df.pct_change().dropna(how="all")
    returns_np = returns.to_numpy()
    with pytest.raises(TypeError):
        hrp = HRPOpt(returns_np)

    hrp = HRPOpt(returns)
    with pytest.raises(ValueError):
        hrp.optimize(linkage_method="blah")
Exemplo n.º 9
0
def HRP():

    sht = xw.Book.caller().sheets['Optim']
    sht.range('N17').value = 'Optimizing...'

    listticker = sht.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 = train.pct_change().dropna(), test.pct_change().dropna()
    hrp = HRPOpt(train)
    weights = hrp.optimize()
    perf = hrp.portfolio_performance(verbose=False)
    fig = plt.figure(figsize=(8, 8))
    ax = hrp.plot_dendrogram(showfig=False)  # to plot dendrogram
    fig = ax.get_figure()
    sht.range('P23').value = weights
    sht.range('P21').value = perf

    #Visualisation
    sht.pictures.add(fig, name="HRPCluster", update=True)
    sht.charts['HRPweights'].set_source_data(
        sht.range((23, 16), (22 + len(listticker), 17)))

    #Done
    sht.range('N17').value = 'Optimization Done'
Exemplo n.º 10
0
def test_weight_plot():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    w = hrp.optimize()

    ax = Plotting.plot_weights(w, showfig=False)
    assert len(ax.findobj()) == 197
Exemplo n.º 11
0
def test_hrp_portfolio():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    w = hrp.optimize()
    assert isinstance(w, dict)
    assert set(w.keys()) == set(df.columns)
    np.testing.assert_almost_equal(sum(w.values()), 1)
    assert all([i >= 0 for i in w.values()])
Exemplo n.º 12
0
def test_hrp_portfolio():
    df = get_data()
    returns = df.pct_change().dropna(how="all")
    hrp = HRPOpt(returns)
    w = hrp.optimize(linkage_method="single")

    # uncomment this line if you want generating a new file
    # pd.Series(w).to_csv(resource("weights_hrp.csv"))

    x = pd.read_csv(resource("weights_hrp.csv"), squeeze=True, index_col=0)
    pd.testing.assert_series_equal(
        x, pd.Series(w), check_names=False, check_less_precise=True
    )

    assert isinstance(w, dict)
    assert set(w.keys()) == set(df.columns)
    np.testing.assert_almost_equal(sum(w.values()), 1)
    assert all([i >= 0 for i in w.values()])
Exemplo n.º 13
0
 'XOM': 0.0,
 'RRC': 0.0,
 'BBY': 0.0,
 'MA': 0.0,
 'PFE': 0.0,
 'JPM': 0.14379,
 'SBUX': 0.0}

Expected annual return: 15.3%
Annual volatility: 28.7%
Sharpe Ratio: 0.46
"""

# Hierarchical risk parity
hrp = HRPOpt(returns)
weights = hrp.optimize()
hrp.portfolio_performance(verbose=True)
print(weights)
plotting.plot_dendrogram(hrp)  # to plot dendrogram
"""
Expected annual return: 10.8%
Annual volatility: 13.2%
Sharpe Ratio: 0.66

{'AAPL': 0.022258941278778397,
 'AMD': 0.02229402179669211,
 'AMZN': 0.016086842079875,
 'BABA': 0.07963382071794091,
 'BAC': 0.014409222455552262,
 'BBY': 0.0340641943824504,
 'FB': 0.06272994714663534,
Exemplo n.º 14
0
            x, y = p.get_xy()
            ax.annotate(f'{height:.0%}', (x + width / 2, y + height), ha='center', fontsize=20)
        st.set_option('deprecation.showPyplotGlobalUse', False)
        st.write(f"## Moroccan Assets Allocation using Efficient Frontier")
        st.pyplot()


################################## Herarchical Risk Parity ###############################################################


if model_name == 'HRP':

    hrp_ETF = HRPOpt(returns)
    hrp_Mor = HRPOpt(moroccan_stocks_returns)

    weights = hrp_ETF.optimize(linkage_method='single')
    wei = hrp_Mor.optimize(linkage_method='single')

    hrp_ETF.portfolio_performance(verbose=True)
    hrp_Mor.portfolio_performance(verbose=True)

    dfhrpETF = pd.DataFrame([weights])
    dfhrpMor = pd.DataFrame([wei])

    if len(ETF_name) == 0 & len(moroccan_stocks) == 0:
        st.write("Please select stocks!!!")
    if len(ETF_name) != 0:
        result_pct = dfhrpETF.div(dfhrpETF.sum(1), axis=0)
        ax = result_pct.plot(kind='bar', figsize=(20, 6), width=0.8, color=colors_list, edgecolor=None)
        plt.legend(labels=dfhrpETF.columns, fontsize=20)
        plt.xticks(fontsize=20)