Skip to content

Commit

Permalink
Update plot docs
Browse files Browse the repository at this point in the history
  • Loading branch information
dcajasn committed Mar 6, 2024
1 parent 86d8180 commit e18c64c
Show file tree
Hide file tree
Showing 5 changed files with 417 additions and 205 deletions.
41 changes: 35 additions & 6 deletions docs/source/plot.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,26 @@ Example
end = '2019-12-30'

# Tickers of assets
tickers = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'APA', 'MMC', 'JPM',
'ZION', 'PSA', 'BAX', 'BMY', 'LUV', 'PCAR', 'TXT', 'TMO',
'DE', 'MSFT', 'HPQ', 'SEE', 'VZ', 'CNP', 'NI', 'T', 'BA']
tickers.sort()
assets = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'APA', 'MMC', 'JPM',
'ZION', 'PSA', 'BAX', 'BMY', 'LUV', 'PCAR', 'TXT', 'TMO',
'DE', 'MSFT', 'HPQ', 'SEE', 'VZ', 'CNP', 'NI', 'T', 'BA']
assets.sort()
# Tickers of factors
factors = ['MTUM', 'QUAL', 'VLUE', 'SIZE', 'USMV']
factors.sort()

tickers = assets + factors
tickers.sort()

# Downloading the data
data = yf.download(tickers, start = start, end = end)
data = data.loc[:,('Adj Close', slice(None))]
data.columns = tickers
assets = data.pct_change().dropna()
returns = data.pct_change().dropna()

Y = assets
Y = returns[assets]
X = returns[factors]
# Creating the Portfolio Object
port = rp.Portfolio(returns=Y)
Expand All @@ -67,6 +75,9 @@ Example

port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=0.94)
mu = port.mu
cov = port.cov

# Estimate the portfolio that maximizes the risk adjusted return ratio
w1 = port.optimization(model='Classic', rm=rm, obj='Sharpe', rf=0.0, l=0, hist=True)

Expand All @@ -76,6 +87,24 @@ Example
# Estimate the risk parity portfolio for semi standard deviation
w2 = port.rp_optimization(model='Classic', rm=rm, rf=0, b=None, hist=True)

# Estimate the risk parity portfolio for semi standard deviation
w2 = port.rp_optimization(model='Classic', rm=rm, rf=0, b=None, hist=True)

# Estimate the risk parity portfolio for risk factors
port.factors = X
port.factors_stats(method_mu=method_mu,
method_cov=method_cov,
feature_selection='stepwise',
dict_risk=dict(stepwise='Forward'))
w3 = port.rp_optimization(model='FC', rm='MV', rf=0, b_f=None)

# Estimate the risk parity portfolio for principal components
port.factors = X
port.factors_stats(method_mu=method_mu,
method_cov=method_cov,
feature_selection='PCR',
dict_risk=dict(n_components=0.95))
w4 = port.rp_optimization(model='FC', rm='MV', rf=0, b_f=None)


Module Functions
Expand Down
29 changes: 20 additions & 9 deletions riskfolio/src/ParamsEstimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1589,7 +1589,16 @@ def black_litterman_bayesian(
return mu, cov, w


def bootstrapping(X, kind="stationary", q=0.05, n_sim=6000, window=3, diag=False, threshold=1e-15, seed=0):
def bootstrapping(
X,
kind="stationary",
q=0.05,
n_sim=6000,
window=3,
diag=False,
threshold=1e-15,
seed=0,
):
r"""
Estimates the uncertainty sets of mean and covariance matrix through the selected
bootstrapping method.
Expand Down Expand Up @@ -1664,7 +1673,7 @@ def bootstrapping(X, kind="stationary", q=0.05, n_sim=6000, window=3, diag=False
T, n = X.shape

mu = X.mean().to_numpy().reshape(1, n)
vec_Sigma = X.cov().to_numpy().reshape((1, n ** 2), order="F")
vec_Sigma = X.cov().to_numpy().reshape((1, n**2), order="F")

mus = np.zeros((n_sim, 1, n))
covs = np.zeros((n_sim, n, n))
Expand Down Expand Up @@ -1692,8 +1701,10 @@ def bootstrapping(X, kind="stationary", q=0.05, n_sim=6000, window=3, diag=False
mu_u = pd.DataFrame(mu_u, index=[0], columns=cols)

# Box Constraint for Covariance
cov_l = np.percentile(covs, q= q / 2 * 100, axis=0, keepdims=True).reshape(n, n)
cov_u = np.percentile(covs, q=(1 - q / 2) * 100, axis=0, keepdims=True).reshape(n, n)
cov_l = np.percentile(covs, q=q / 2 * 100, axis=0, keepdims=True).reshape(n, n)
cov_u = np.percentile(covs, q=(1 - q / 2) * 100, axis=0, keepdims=True).reshape(
n, n
)
cov_l = pd.DataFrame(cov_l, index=cols, columns=cols)
cov_u = pd.DataFrame(cov_u, index=cols, columns=cols)

Expand All @@ -1714,7 +1725,7 @@ def bootstrapping(X, kind="stationary", q=0.05, n_sim=6000, window=3, diag=False
cov_mu = pd.DataFrame(cov_mu, index=cols, columns=cols)

# Elliptical Constraint for Covariance
A_Sigma = covs.reshape((n_sim, n ** 2), order="F")
A_Sigma = covs.reshape((n_sim, n**2), order="F")
A_Sigma = A_Sigma - np.repeat(vec_Sigma, n_sim, axis=0)
cov_sigma = np.cov(A_Sigma, rowvar=False)
cov_sigma = af.cov_fix(cov_sigma, method="clipped", threshold=threshold)
Expand Down Expand Up @@ -1788,11 +1799,11 @@ def normal_simulation(X, q=0.05, n_sim=6000, diag=False, threshold=1e-15, seed=0

# Set initial parameters based on assumption of normality
mu = X.mean().to_numpy().reshape(1, n)
vec_Sigma = X.cov().to_numpy().reshape((1, n ** 2), order="F")
vec_Sigma = X.cov().to_numpy().reshape((1, n**2), order="F")
Sigma = X.cov().to_numpy()
cov_mu = Sigma/T
cov_mu = Sigma / T
K = cf.commutation_matrix(T=n, n=n)
I = np.identity(n ** 2)
I = np.identity(n**2)
cov_sigma = T * (I + K) @ np.kron(cov_mu, cov_mu)

# Box Constraint for Mean
Expand Down Expand Up @@ -1828,7 +1839,7 @@ def normal_simulation(X, q=0.05, n_sim=6000, diag=False, threshold=1e-15, seed=0
cov_mu = pd.DataFrame(cov_mu, index=cols, columns=cols)

# Elliptical Constraint for Covariance
A_Sigma = covs.reshape((n_sim, n ** 2), order="F")
A_Sigma = covs.reshape((n_sim, n**2), order="F")
A_Sigma = A_Sigma - np.repeat(vec_Sigma, n_sim, axis=0)
# cov_sigma = np.cov(A_Sigma, rowvar=False)
cov_sigma = af.cov_fix(cov_sigma, method="clipped", threshold=threshold)
Expand Down
38 changes: 19 additions & 19 deletions riskfolio/src/PlotFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def plot_frontier(
beta=None,
b_sim=None,
kappa=0.30,
solver='CLARABEL',
solver="CLARABEL",
cmap="viridis",
w=None,
label="Portfolio",
Expand Down Expand Up @@ -354,7 +354,7 @@ def plot_frontier(
ax = rp.plot_frontier(w_frontier=ws,
mu=mu,
cov=cov,
returns=returns,
returns=Y,
rm=rm,
rf=0,
alpha=0.05,
Expand Down Expand Up @@ -810,7 +810,7 @@ def plot_bar(
-------
::
ax = rp.plot_bar(w,
ax = rp.plot_bar(w1,
title='Portfolio',
kind="v",
others=0.05,
Expand Down Expand Up @@ -1106,7 +1106,7 @@ def plot_risk_con(
beta=None,
b_sim=None,
kappa=0.30,
solver='CLARABEL',
solver="CLARABEL",
percentage=False,
erc_line=True,
color="tab:blue",
Expand Down Expand Up @@ -1217,7 +1217,7 @@ def plot_risk_con(
ax = rp.plot_risk_con(w=w2,
cov=cov,
returns=returns,
returns=Y,
rm=rm,
rf=0,
alpha=0.05,
Expand Down Expand Up @@ -1342,7 +1342,7 @@ def plot_factor_risk_con(
beta=None,
b_sim=None,
kappa=0.30,
solver='CLARABEL',
solver="CLARABEL",
feature_selection="stepwise",
stepwise="Forward",
criterion="pvalue",
Expand Down Expand Up @@ -1489,10 +1489,10 @@ def plot_factor_risk_con(
-------
::
ax = rp.plot_factor_risk_con(w=w2,
ax = rp.plot_factor_risk_con(w=w3,
cov=cov,
returns=returns,
factors=factors,
returns=Y,
factors=X,
B=None,
const=True,
rm=rm,
Expand All @@ -1510,10 +1510,10 @@ def plot_factor_risk_con(
::
ax = rp.plot_factor_risk_con(w=w2,
ax = rp.plot_factor_risk_con(w=w4,
cov=cov,
returns=returns,
factors=factors,
returns=Y,
factors=X,
B=None,
const=True,
rm=rm,
Expand Down Expand Up @@ -1586,12 +1586,12 @@ def plot_factor_risk_con(
n_components=n_components,
)

if feature_selection == 'PCR':
n = len(RC_F)-1
X = ['PC ' + str(i) for i in range(1, n+1)]
if feature_selection == "PCR":
n = len(RC_F) - 1
X = ["PC " + str(i) for i in range(1, n + 1)]
else:
X = factors.columns.tolist()
X.append('Others')
X.append("Others")

if rm not in ["MDD", "ADD", "CDaR", "EDaR", "RLDaR", "UCI"]:
RC_F = RC_F * t_factor**0.5
Expand Down Expand Up @@ -1648,7 +1648,7 @@ def plot_hist(
alpha=0.05,
a_sim=100,
kappa=0.30,
solver='CLARABEL',
solver="CLARABEL",
bins=50,
height=6,
width=10,
Expand Down Expand Up @@ -2047,7 +2047,7 @@ def plot_drawdown(
w,
alpha=0.05,
kappa=0.30,
solver='CLARABEL',
solver="CLARABEL",
height=8,
width=10,
height_ratios=[2, 3],
Expand Down Expand Up @@ -2237,7 +2237,7 @@ def plot_table(
alpha=0.05,
a_sim=100,
kappa=0.30,
solver='CLARABEL',
solver="CLARABEL",
height=9,
width=12,
t_factor=252,
Expand Down
Loading

0 comments on commit e18c64c

Please sign in to comment.