def __init__(self, table):
        mu = expected_returns.mean_historical_return(table)
        S = risk_models.sample_cov(table)

        # Optimise for maximal Sharpe ratio
        ef = EfficientFrontier(mu, S)
        ef.max_sharpe()  # Raw weights
        self.cleaned_weights = ef.clean_weights()
        print(self.cleaned_weights)
        ef.portfolio_performance(verbose=True)

        latest_prices = discrete_allocation.get_latest_prices(table)
        self.allocation, self.leftover = discrete_allocation.portfolio(
            self.cleaned_weights, latest_prices, total_portfolio_value=10000
        )
def test_portfolio_allocation_errors():
    df = get_data()
    e_ret = mean_historical_return(df)
    cov = sample_cov(df)
    ef = EfficientFrontier(e_ret, cov)
    w = ef.max_sharpe()
    latest_prices = discrete_allocation.get_latest_prices(df)

    with pytest.raises(TypeError):
        discrete_allocation.portfolio(ef.weights, latest_prices)

    with pytest.raises(TypeError):
        discrete_allocation.portfolio(w, latest_prices.values.tolist())

    with pytest.raises(ValueError):
        discrete_allocation.portfolio(w, latest_prices, min_allocation=0.5)

    with pytest.raises(ValueError):
        discrete_allocation.portfolio(w, latest_prices, total_portfolio_value=0)
def test_portfolio_allocation():
    df = get_data()
    e_ret = mean_historical_return(df)
    cov = sample_cov(df)
    ef = EfficientFrontier(e_ret, cov)
    w = ef.max_sharpe()

    latest_prices = discrete_allocation.get_latest_prices(df)
    allocation, leftover = discrete_allocation.portfolio(w, latest_prices)
    assert allocation == {
        "MA": 14,
        "FB": 12,
        "PFE": 51,
        "BABA": 5,
        "AAPL": 5,
        "AMZN": 0,
        "BBY": 9,
        "SBUX": 6,
        "GOOG": 1,
    }
    total = 0
    for ticker, num in allocation.items():
        total += num * latest_prices[ticker]
    np.testing.assert_almost_equal(total + leftover, 10000)
Esempio n. 4
0
def convert_to_no(x):
    allocation, leftover = discrete_allocation.portfolio(
        x.to_dict(), stocks.latest_prices, total_portfolio_value=2000)
    return pd.Series(allocation)
Esempio n. 5
0
weights_mv = ef.efficient_frontier[ef.tickers]
ww = weights_mv.loc[idx]
print(ww)

Ret = np.dot(ww, ef.expected_returns)
Vol = np.sqrt(np.dot(ww, np.dot(ef.cov_matrix, ww)))

ef.efficient_return(desired_return)
w_10 = ef.clean_weights()
w_10_clean = pd.Series({i: w_10[i] for i in w_10 if w_10[i] > 0})

print(w_10_clean)

from pypfopt import discrete_allocation

allocation, leftover = discrete_allocation.portfolio(
    w_10, stocks.latest_prices, total_portfolio_value=3000)
print(allocation)

# plot
ef.plot_mv_frontier()

ax = ef.plot_scatter_efficient(10000)

ax.plot(Vol, Ret, 'bo')

# plt.show()

##############


def convert_to_no(x):
Esempio n. 6
0
from pypfopt.value_at_risk import CVAROpt
from pypfopt import discrete_allocation


# Reading in the data; preparing expected returns and a risk model
df = pd.read_csv("tests/stock_prices.csv", parse_dates=True, index_col="date")
returns = df.pct_change().dropna(how="all")
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

# Long-only Maximum Sharpe portfolio, with discretised weights
ef = EfficientFrontier(mu, S)
weights = ef.max_sharpe()
ef.portfolio_performance(verbose=True)
latest_prices = discrete_allocation.get_latest_prices(df)
allocation, leftover = discrete_allocation.portfolio(weights, latest_prices)
print("Discrete allocation:", allocation)
print("Funds remaining: ${:.2f}".format(leftover))

"""
Expected annual return: 33.0%
Annual volatility: 21.7%
Sharpe Ratio: 1.43

Discrete allocation: {'MA': 14, 'FB': 12, 'PFE': 51, 'BABA': 5, 'AAPL': 5,
                      'AMZN': 0, 'BBY': 9, 'SBUX': 6, 'GOOG': 1}
Funds remaining: $12.15
"""

# Long-only minimum volatility portfolio, with a weight cap and regularisation
# e.g if we want at least 15/20 tickers to have non-neglible weights, and no
import pandas as pd
from pypfopt.efficient_frontier import EfficientFrontier
from pypfopt import risk_models
from pypfopt import expected_returns
from pypfopt import discrete_allocation

# Read in price data
df = pd.read_hdf("stock_prices.hdf5", "df")

# Calculate expected returns and sample covariance
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

# Optimise for maximal Sharpe ratio
ef = EfficientFrontier(mu, S)
raw_weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
print(cleaned_weights)
ef.portfolio_performance(verbose=True)

latest_prices = discrete_allocation.get_latest_prices(df)
allocation, leftover = discrete_allocation.portfolio(
    cleaned_weights, latest_prices, total_portfolio_value=10000)
print(allocation)
print("Funds remaining: ${:.2f}".format(leftover))