def test_cvar_example():
    beta = 0.95
    df = get_data()
    mu = expected_returns.mean_historical_return(df)
    historical_rets = expected_returns.returns_from_prices(df).dropna()

    cv = EfficientCVaR(mu, historical_rets, beta=beta)
    w = cv.min_cvar()

    assert isinstance(w, dict)
    assert set(w.keys()) == set(cv.tickers)
    np.testing.assert_almost_equal(cv.weights.sum(), 1)
    assert all([i >= -1e-5 for i in w.values()])

    np.testing.assert_allclose(
        cv.portfolio_performance(),
        (0.17745746040573562, 0.017049502122532853),
        rtol=1e-4,
        atol=1e-4,
    )

    cvar = cv.portfolio_performance()[1]
    portfolio_rets = historical_rets @ cv.weights

    var_hist = portfolio_rets.quantile(1 - beta)
    cvar_hist = -portfolio_rets[portfolio_rets < var_hist].mean()
    np.testing.assert_almost_equal(cvar_hist, cvar, decimal=3)
Пример #2
0
def test_efficient_risk_market_neutral():
    cv = EfficientCVaR(*setup_efficient_cvar(data_only=True), weight_bounds=(-1, 1))
    w = cv.efficient_risk(0.025, market_neutral=True)
    assert isinstance(w, dict)
    assert set(w.keys()) == set(cv.tickers)
    np.testing.assert_almost_equal(cv.weights.sum(), 0)
    assert (cv.weights < 1).all() and (cv.weights > -1).all()
    np.testing.assert_allclose(
        cv.portfolio_performance(),
        (0.5895653670063358, 0.025),
        rtol=1e-4,
        atol=1e-4,
    )
def test_cvar_example_short():
    df = get_data()
    mu = expected_returns.mean_historical_return(df)
    historical_rets = expected_returns.returns_from_prices(df).dropna()
    cv = EfficientCVaR(
        mu,
        historical_rets,
        weight_bounds=(-1, 1),
    )
    w = cv.efficient_return(0.2, market_neutral=True)
    assert isinstance(w, dict)
    assert set(w.keys()) == set(cv.tickers)
    np.testing.assert_almost_equal(cv.weights.sum(), 0)

    np.testing.assert_allclose(
        cv.portfolio_performance(),
        (0.2, 0.013406209257292611),
        rtol=1e-4,
        atol=1e-4,
    )
def test_efficient_return_short():
    cv = EfficientCVaR(*setup_efficient_cvar(data_only=True),
                       weight_bounds=(-3.0, 3.0))
    w = cv.efficient_return(0.26)
    assert isinstance(w, dict)
    assert set(w.keys()) == set(cv.tickers)
    np.testing.assert_almost_equal(cv.weights.sum(), 1)
    np.testing.assert_allclose(
        cv.portfolio_performance(),
        (0.26, 0.01804624747353764),
        rtol=1e-4,
        atol=1e-4,
    )
    cvar = cv.portfolio_performance()[1]

    ef_long_only = EfficientCVaR(*setup_efficient_cvar(data_only=True),
                                 weight_bounds=(0.0, 1.0))
    ef_long_only.efficient_return(0.26)
    long_only_cvar = ef_long_only.portfolio_performance()[1]

    assert long_only_cvar > cvar
def test_es_return_sample():
    df = get_data()
    mu = expected_returns.mean_historical_return(df)
    S = risk_models.sample_cov(df)

    # Generate a 1y sample of daily data
    np.random.seed(0)
    mu_daily = (1 + mu)**(1 / 252) - 1
    S_daily = S / 252
    sample_rets = pd.DataFrame(np.random.multivariate_normal(
        mu_daily, S_daily, 300),
                               columns=mu.index)

    cv = EfficientCVaR(mu, sample_rets)
    w = cv.efficient_return(0.2)

    assert isinstance(w, dict)
    assert set(w.keys()) == set(cv.tickers)
    np.testing.assert_almost_equal(cv.weights.sum(), 1)
    assert all([i >= -1e-5 for i in w.values()])

    np.testing.assert_allclose(
        cv.portfolio_performance(),
        (0.20, 0.01789275427676941),
        rtol=1e-4,
        atol=1e-4,
    )
    # Cover verbose param case
    np.testing.assert_equal(cv.portfolio_performance(verbose=True),
                            cv.portfolio_performance())
def test_cvar_example_weekly():
    beta = 0.95
    df = get_data()
    df = df.resample("W").first()
    mu = expected_returns.mean_historical_return(df, frequency=52)
    historical_rets = expected_returns.returns_from_prices(df).dropna()
    cv = EfficientCVaR(mu, historical_rets, beta=beta)
    cv.efficient_return(0.2)
    np.testing.assert_allclose(
        cv.portfolio_performance(),
        (0.2, 0.03447723250708958),
        rtol=1e-4,
        atol=1e-4,
    )

    cvar = cv.portfolio_performance()[1]
    portfolio_rets = historical_rets @ cv.weights

    var_hist = portfolio_rets.quantile(1 - beta)
    cvar_hist = -portfolio_rets[portfolio_rets < var_hist].mean()
    np.testing.assert_almost_equal(cvar_hist, cvar, decimal=3)
def test_cvar_no_returns():
    # Issue 324
    df = get_data()
    historical_rets = expected_returns.returns_from_prices(df).dropna()
    assert EfficientCVaR(None, historical_rets)
def test_cvar_errors():
    df = get_data()
    mu = expected_returns.mean_historical_return(df)
    historical_rets = expected_returns.returns_from_prices(df)

    with pytest.warns(UserWarning):
        EfficientCVaR(mu, historical_rets)

    historical_rets = historical_rets.dropna(axis=0, how="any")
    assert EfficientCVaR(mu, historical_rets)

    cv = setup_efficient_cvar()

    with pytest.raises(NotImplementedError):
        cv.min_volatility()

    with pytest.raises(NotImplementedError):
        cv.max_sharpe()

    with pytest.raises(NotImplementedError):
        cv.max_quadratic_utility()

    with pytest.raises(ValueError):
        # Beta must be between 0 and 1
        cv = EfficientCVaR(mu, historical_rets, 1)

    with pytest.warns(UserWarning):
        cv = EfficientCVaR(mu, historical_rets, 0.1)

    with pytest.raises(OptimizationError):
        # Must be <= max expected return
        cv = EfficientCVaR(mu, historical_rets)
        cv.efficient_return(target_return=np.abs(mu).max() + 0.01)

    with pytest.raises(AttributeError):
        # list not supported.
        EfficientCVaR(mu, historical_rets.to_numpy().tolist())

    historical_rets = historical_rets.iloc[:, :-1]
    with pytest.raises(ValueError):
        EfficientCVaR(mu, historical_rets)