Update app.py
Browse files
app.py
CHANGED
|
@@ -20,27 +20,23 @@ def plot_cum_returns(data, title):
|
|
| 20 |
return fig
|
| 21 |
|
| 22 |
def plot_efficient_frontier_and_max_sharpe(mu, S):
|
| 23 |
-
# Optimize portfolio for max Sharpe ratio and plot it out with efficient frontier curve
|
| 24 |
ef = EfficientFrontier(mu, S)
|
| 25 |
fig, ax = plt.subplots(figsize=(6,4))
|
| 26 |
ef_max_sharpe = copy.deepcopy(ef)
|
| 27 |
plotting.plot_efficient_frontier(ef, ax=ax, show_assets=False)
|
| 28 |
-
# Find the max sharpe portfolio
|
| 29 |
ef_max_sharpe.max_sharpe(risk_free_rate=0.02)
|
| 30 |
ret_tangent, std_tangent, _ = ef_max_sharpe.portfolio_performance()
|
| 31 |
ax.scatter(std_tangent, ret_tangent, marker="*", s=100, c="r", label="Max Sharpe")
|
| 32 |
-
# Generate random portfolios with random weights
|
| 33 |
n_samples = 1000
|
| 34 |
w = np.random.dirichlet(np.ones(ef.n_assets), n_samples)
|
| 35 |
rets = w.dot(ef.expected_returns)
|
| 36 |
stds = np.sqrt(np.diag(w @ ef.cov_matrix @ w.T))
|
| 37 |
sharpes = rets / stds
|
| 38 |
ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")
|
| 39 |
-
# Output
|
| 40 |
ax.legend()
|
| 41 |
return fig
|
| 42 |
|
| 43 |
-
def output_results(start_date, end_date, tickers_string):
|
| 44 |
tickers = tickers_string.split(',')
|
| 45 |
|
| 46 |
# Get Stock Prices
|
|
@@ -73,10 +69,18 @@ def output_results(start_date, end_date, tickers_string):
|
|
| 73 |
'{}%'.format((annual_volatility*100).round(2)), \
|
| 74 |
'{}%'.format((sharpe_ratio*100).round(2))
|
| 75 |
|
| 76 |
-
weights_df = pd.DataFrame.from_dict(weights, orient
|
| 77 |
-
weights_df = weights_df.reset_index()
|
| 78 |
weights_df.columns = ['Tickers', 'Weights']
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
# Calculate returns of portfolio with optimized weights
|
| 81 |
stocks_df['Optimized Portfolio'] = 0
|
| 82 |
for ticker, weight in weights.items():
|
|
@@ -85,8 +89,8 @@ def output_results(start_date, end_date, tickers_string):
|
|
| 85 |
# Plot Cumulative Returns of Optimized Portfolio
|
| 86 |
fig_cum_returns_optimized = plot_cum_returns(stocks_df['Optimized Portfolio'], 'Cumulative Returns of Optimized Portfolio Starting with ₹100')
|
| 87 |
|
| 88 |
-
return fig_cum_returns_optimized, weights_df, fig_efficient_frontier, fig_corr,
|
| 89 |
-
expected_annual_return, annual_volatility, sharpe_ratio, fig_indiv_prices, fig_cum_returns
|
| 90 |
|
| 91 |
|
| 92 |
with gr.Blocks() as app:
|
|
@@ -101,6 +105,7 @@ with gr.Blocks() as app:
|
|
| 101 |
tickers_string = gr.Textbox("TCS.NS,INFY.NS,RELIANCE.NS,HDFCBANK.NS,ICICIBANK.NS,SBIN.NS",
|
| 102 |
label='Enter all stock tickers to be included in portfolio separated \
|
| 103 |
by commas WITHOUT spaces, e.g. "TCS.NS,INFY.NS,RELIANCE.NS,HDFCBANK.NS,ICICIBANK.NS,SBIN.NS"')
|
|
|
|
| 104 |
btn = gr.Button("Get Optimized Portfolio")
|
| 105 |
|
| 106 |
with gr.Row():
|
|
@@ -122,9 +127,13 @@ with gr.Blocks() as app:
|
|
| 122 |
with gr.Row():
|
| 123 |
fig_indiv_prices = gr.Plot(label="Price of Individual Stocks")
|
| 124 |
fig_cum_returns = gr.Plot(label="Cumulative Returns of Individual Stocks Starting with ₹100")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
btn.click(fn=output_results, inputs=[start_date, end_date, tickers_string],
|
| 127 |
-
outputs=[fig_cum_returns_optimized, weights_df, fig_efficient_frontier, fig_corr,
|
| 128 |
-
|
| 129 |
|
| 130 |
-
app.launch()
|
|
|
|
| 20 |
return fig
|
| 21 |
|
| 22 |
def plot_efficient_frontier_and_max_sharpe(mu, S):
|
|
|
|
| 23 |
ef = EfficientFrontier(mu, S)
|
| 24 |
fig, ax = plt.subplots(figsize=(6,4))
|
| 25 |
ef_max_sharpe = copy.deepcopy(ef)
|
| 26 |
plotting.plot_efficient_frontier(ef, ax=ax, show_assets=False)
|
|
|
|
| 27 |
ef_max_sharpe.max_sharpe(risk_free_rate=0.02)
|
| 28 |
ret_tangent, std_tangent, _ = ef_max_sharpe.portfolio_performance()
|
| 29 |
ax.scatter(std_tangent, ret_tangent, marker="*", s=100, c="r", label="Max Sharpe")
|
|
|
|
| 30 |
n_samples = 1000
|
| 31 |
w = np.random.dirichlet(np.ones(ef.n_assets), n_samples)
|
| 32 |
rets = w.dot(ef.expected_returns)
|
| 33 |
stds = np.sqrt(np.diag(w @ ef.cov_matrix @ w.T))
|
| 34 |
sharpes = rets / stds
|
| 35 |
ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")
|
|
|
|
| 36 |
ax.legend()
|
| 37 |
return fig
|
| 38 |
|
| 39 |
+
def output_results(start_date, end_date, tickers_string, investment_amount):
|
| 40 |
tickers = tickers_string.split(',')
|
| 41 |
|
| 42 |
# Get Stock Prices
|
|
|
|
| 69 |
'{}%'.format((annual_volatility*100).round(2)), \
|
| 70 |
'{}%'.format((sharpe_ratio*100).round(2))
|
| 71 |
|
| 72 |
+
weights_df = pd.DataFrame.from_dict(weights, orient='index').reset_index()
|
|
|
|
| 73 |
weights_df.columns = ['Tickers', 'Weights']
|
| 74 |
|
| 75 |
+
# Get the latest prices
|
| 76 |
+
latest_prices = get_latest_prices(stocks_df)
|
| 77 |
+
|
| 78 |
+
# Allocate the stocks based on the given budget
|
| 79 |
+
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=investment_amount)
|
| 80 |
+
allocation, leftover = da.lp_portfolio()
|
| 81 |
+
|
| 82 |
+
allocation_df = pd.DataFrame(list(allocation.items()), columns=['Ticker', 'Shares'])
|
| 83 |
+
|
| 84 |
# Calculate returns of portfolio with optimized weights
|
| 85 |
stocks_df['Optimized Portfolio'] = 0
|
| 86 |
for ticker, weight in weights.items():
|
|
|
|
| 89 |
# Plot Cumulative Returns of Optimized Portfolio
|
| 90 |
fig_cum_returns_optimized = plot_cum_returns(stocks_df['Optimized Portfolio'], 'Cumulative Returns of Optimized Portfolio Starting with ₹100')
|
| 91 |
|
| 92 |
+
return fig_cum_returns_optimized, weights_df, fig_efficient_frontier, fig_corr, \
|
| 93 |
+
expected_annual_return, annual_volatility, sharpe_ratio, fig_indiv_prices, fig_cum_returns, allocation_df, leftover
|
| 94 |
|
| 95 |
|
| 96 |
with gr.Blocks() as app:
|
|
|
|
| 105 |
tickers_string = gr.Textbox("TCS.NS,INFY.NS,RELIANCE.NS,HDFCBANK.NS,ICICIBANK.NS,SBIN.NS",
|
| 106 |
label='Enter all stock tickers to be included in portfolio separated \
|
| 107 |
by commas WITHOUT spaces, e.g. "TCS.NS,INFY.NS,RELIANCE.NS,HDFCBANK.NS,ICICIBANK.NS,SBIN.NS"')
|
| 108 |
+
investment_amount = gr.Number(label="Investment Amount (in ₹)")
|
| 109 |
btn = gr.Button("Get Optimized Portfolio")
|
| 110 |
|
| 111 |
with gr.Row():
|
|
|
|
| 127 |
with gr.Row():
|
| 128 |
fig_indiv_prices = gr.Plot(label="Price of Individual Stocks")
|
| 129 |
fig_cum_returns = gr.Plot(label="Cumulative Returns of Individual Stocks Starting with ₹100")
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
allocation_df = gr.DataFrame(label="Stock Allocation")
|
| 133 |
+
leftover = gr.Number(label="Leftover Amount (in ₹)")
|
| 134 |
|
| 135 |
+
btn.click(fn=output_results, inputs=[start_date, end_date, tickers_string, investment_amount],
|
| 136 |
+
outputs=[fig_cum_returns_optimized, weights_df, fig_efficient_frontier, fig_corr, \
|
| 137 |
+
expected_annual_return, annual_volatility, sharpe_ratio, fig_indiv_prices, fig_cum_returns, allocation_df, leftover])
|
| 138 |
|
| 139 |
+
app.launch()
|