<jupyter_start><jupyter_text>Optimize Portfolio for Min. Risk (Volatility)<jupyter_code>#Portfolio Optimization
#Calculate he expected returs, annualized sample covarinace matrix of asset returns
mu = expected_returns.mean_historical_return(stocks_df)
S = risk_models.sample_cov(stocks_df)

#Optimize for the max Sharpe Ratio
ef = EfficientFrontier(mu, S)
weights = ef.min_volatility()
cleaned_weights = ef.clean_weights()

ef.save_weights_to_file("weights.txt")  # saves to file
print(cleaned_weights)
# Plot the Markov Efficient Frontier for Min. Risk (Volatility)
#Portfolio Optimization
#Calculate he expected returns, annualized sample covarinace matrix of asset returns
mu = expected_returns.mean_historical_return(stocks_df)
S = risk_models.sample_cov(stocks_df)

#Optimize for the minimum risk (volatility)
ef = EfficientFrontier(mu, S)
ef.add_constraint(lambda w: sum(w[0:]) == 1)

#Plot instance 
fig, ax = plt.subplots()
plotting.plot_efficient_frontier(ef, ax=ax, show_assets=False)

#Find the Tangency Portfolio
ef.min_volatility()
ret_tangent, std_tangent, _ = ef.portfolio_performance()
ax.scatter(std_tangent, ret_tangent, marker="*", s=100, c="r", label="Minimum Risk")


# Generate random portfolios
n_samples = 10000
w = np.random.dirichlet(np.ones(len(mu)), n_samples)
rets = w.dot(mu)
stds = np.sqrt(np.diag(w @ S @ w.T))
sharpes = rets / stds
ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")

# Output
ax.set_title("Efficient Frontier with random portfolios")
ax.legend()
plt.tight_layout()
plt.savefig("ef_scatter.png", dpi=200)
plt.show()
#Get the Discrete Allocation  of each share per stock
from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices

latest_prices = get_latest_prices(stocks_df)
weights = cleaned_weights

da = DiscreteAllocation(weights, latest_prices, total_portfolio_value= 1000000)

allocation, leftover = da.lp_portfolio()

print('Discrete Allocation:', allocation)
print('Funds Balance: ${:.2f}'. format(leftover))<jupyter_output>Discrete Allocation: {'VOO': 2323}
Funds Balance: $250.50<jupyter_text>Optimize portfolio for Efficient Risk (Volatility = 30%)<jupyter_code>#Portfolio Optimization
#Calculate he expected returs, annualized sample covarinace matrix of asset returns
mu = expected_returns.mean_historical_return(stocks_df)
S = risk_models.sample_cov(stocks_df)

#Optimize for the max Sharpe Ratio
ef = EfficientFrontier(mu, S)
weights = ef.efficient_risk(0.275)
cleaned_weights = ef.clean_weights()

ef.save_weights_to_file("weights.txt")  # saves to file
print(cleaned_weights)
#Asset clasifcation for Efficient Risk Portfolio
# Plot the Markov Efficient Frontier for Efficient Risk
#Portfolio Optimization
#Calculate he expected returns, annualized sample covarinace matrix of asset returns
mu = expected_returns.mean_historical_return(stocks_df)
S = risk_models.sample_cov(stocks_df)

#Optimize for the Efficient Risk
ef = EfficientFrontier(mu, S)
ef.add_constraint(lambda w: sum(w[0:]) == 1)

#Plot instance 
fig, ax = plt.subplots()
plotting.plot_efficient_frontier(ef, ax=ax, show_assets=False)

#Find the Tangency Portfolio

ef.efficient_risk(0.30)
ret_tangent, std_tangent, _ = ef.portfolio_performance()
ax.scatter(std_tangent, ret_tangent, marker="*", s=100, c="r", label="Efficient Risk")


# Generate random portfolios
n_samples = 10000
w = np.random.dirichlet(np.ones(len(mu)), n_samples)
rets = w.dot(mu)
stds = np.sqrt(np.diag(w @ S @ w.T))
sharpes = rets / stds
ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")

# Output
ax.set_title("Efficient Frontier with random portfolios")
ax.legend()
plt.tight_layout()
plt.savefig("ef_scatter.png", dpi=200)
plt.show()
#Get the Discrete Allocation  of each share per stock (Efficient Risk; Volatility =  30%
from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices

latest_prices = get_latest_prices(stocks_df)
weights = cleaned_weights

da = DiscreteAllocation(weights, latest_prices, total_portfolio_value= 1000000)

allocation, leftover = da.lp_portfolio()

print('Discrete Allocation:', allocation)
print('Funds Balance: ${:.2f}'. format(leftover))<jupyter_output>Discrete Allocation: {'ETH-USD': 90, 'VOO': 1482}
Funds Balance: $1017.56
{'fraction_non_alphanumeric': 0.11113738472452116, 'fraction_numerical': 0.017498226531094823, 'mean_word_length': 7.087954110898662, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '360012', 'license': 'MIT', 'n_tokens_mistral': 1616, 'n_tokens_neox': 1464, 'n_words': 358, 'path': 'ETH_Price.ipynb', 'repo_name': 'aguidot/project3space', 'size': '4229'}