Harshithtd commited on
Commit
cae4a9c
·
verified ·
1 Parent(s): 2166ff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -36
app.py CHANGED
@@ -19,22 +19,7 @@ def plot_cum_returns(data, title):
19
  fig = px.line(daily_cum_returns, title=title)
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(',')
@@ -49,15 +34,15 @@ def output_results(start_date, end_date, tickers_string, investment_amount):
49
  fig_cum_returns = plot_cum_returns(stocks_df, 'Cumulative Returns of Individual Stocks Starting with ₹100')
50
 
51
  # Calculate and Plot Correlation Matrix between Stocks
52
- corr_df = stocks_df.corr().round(2)
53
- fig_corr = px.imshow(corr_df, text_auto=True, title = 'Correlation between Stocks')
54
 
55
  # Calculate expected returns and sample covariance matrix for portfolio optimization later
56
  mu = expected_returns.mean_historical_return(stocks_df)
57
  S = risk_models.sample_cov(stocks_df)
58
 
59
  # Plot efficient frontier curve
60
- fig_efficient_frontier = plot_efficient_frontier_and_max_sharpe(mu, S)
61
 
62
  # Get optimized weights
63
  ef = EfficientFrontier(mu, S)
@@ -66,8 +51,8 @@ def output_results(start_date, end_date, tickers_string, investment_amount):
66
  expected_annual_return, annual_volatility, sharpe_ratio = ef.portfolio_performance()
67
 
68
  expected_annual_return, annual_volatility, sharpe_ratio = '{}%'.format((expected_annual_return*100).round(2)), \
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']
@@ -89,8 +74,8 @@ def output_results(start_date, end_date, tickers_string, investment_amount):
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:
@@ -108,32 +93,31 @@ with gr.Blocks() as app:
108
  investment_amount = gr.Number(label="Investment Amount (in ₹)")
109
  btn = gr.Button("Get Optimized Portfolio")
110
 
111
- with gr.Row():
112
- gr.HTML("<h3>Optimized Portfolio Metrics</h3>")
113
 
114
  with gr.Row():
115
  expected_annual_return = gr.Text(label="Expected Annual Return")
116
- annual_volatility = gr.Text(label="Annual Volatility")
117
- sharpe_ratio = gr.Text(label="Sharpe Ratio")
118
 
119
  with gr.Row():
120
  fig_cum_returns_optimized = gr.Plot(label="Cumulative Returns of Optimized Portfolio (Starting Price of ₹100)")
121
- weights_df = gr.DataFrame(label="Optimized Weights of Each Ticker")
122
 
123
- with gr.Row():
124
- fig_efficient_frontier = gr.Plot(label="Efficient Frontier")
125
- fig_corr = gr.Plot(label="Correlation between Stocks")
126
 
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()
 
19
  fig = px.line(daily_cum_returns, title=title)
20
  return fig
21
 
22
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  def output_results(start_date, end_date, tickers_string, investment_amount):
25
  tickers = tickers_string.split(',')
 
34
  fig_cum_returns = plot_cum_returns(stocks_df, 'Cumulative Returns of Individual Stocks Starting with ₹100')
35
 
36
  # Calculate and Plot Correlation Matrix between Stocks
37
+ # corr_df = stocks_df.corr().round(2)
38
+ # fig_corr = px.imshow(corr_df, text_auto=True, title = 'Correlation between Stocks')
39
 
40
  # Calculate expected returns and sample covariance matrix for portfolio optimization later
41
  mu = expected_returns.mean_historical_return(stocks_df)
42
  S = risk_models.sample_cov(stocks_df)
43
 
44
  # Plot efficient frontier curve
45
+ #fig_efficient_frontier = plot_efficient_frontier_and_max_sharpe(mu, S)
46
 
47
  # Get optimized weights
48
  ef = EfficientFrontier(mu, S)
 
51
  expected_annual_return, annual_volatility, sharpe_ratio = ef.portfolio_performance()
52
 
53
  expected_annual_return, annual_volatility, sharpe_ratio = '{}%'.format((expected_annual_return*100).round(2)), \
54
+ '{}%'.format((annual_volatility*100).round(2)), \
55
+ '{}%'.format((sharpe_ratio*100).round(2))
56
 
57
  weights_df = pd.DataFrame.from_dict(weights, orient='index').reset_index()
58
  weights_df.columns = ['Tickers', 'Weights']
 
74
  # Plot Cumulative Returns of Optimized Portfolio
75
  fig_cum_returns_optimized = plot_cum_returns(stocks_df['Optimized Portfolio'], 'Cumulative Returns of Optimized Portfolio Starting with ₹100')
76
 
77
+ return fig_cum_returns_optimized, allocation_df, \
78
+ expected_annual_return, leftover.round(), fig_indiv_prices, fig_cum_returns
79
 
80
 
81
  with gr.Blocks() as app:
 
93
  investment_amount = gr.Number(label="Investment Amount (in ₹)")
94
  btn = gr.Button("Get Optimized Portfolio")
95
 
96
+ # with gr.Row():
97
+ # gr.HTML("<h3>Optimized Portfolio Metrics</h3>")
98
 
99
  with gr.Row():
100
  expected_annual_return = gr.Text(label="Expected Annual Return")
101
+ leftover = gr.Number(label="Leftover Amount (in ₹)")
 
102
 
103
  with gr.Row():
104
  fig_cum_returns_optimized = gr.Plot(label="Cumulative Returns of Optimized Portfolio (Starting Price of ₹100)")
105
+ allocation_df = gr.DataFrame(label="Stock Allocation")
106
 
107
+ # with gr.Row():
108
+ # fig_efficient_frontier = gr.Plot(label="Efficient Frontier")
109
+ # fig_corr = gr.Plot(label="Correlation between Stocks")
110
 
111
  with gr.Row():
112
  fig_indiv_prices = gr.Plot(label="Price of Individual Stocks")
113
  fig_cum_returns = gr.Plot(label="Cumulative Returns of Individual Stocks Starting with ₹100")
114
 
115
+ # with gr.Row():
116
+ # allocation_df = gr.DataFrame(label="Stock Allocation")
117
+ #leftover = gr.Number(label="Leftover Amount (in ₹)")
118
 
119
  btn.click(fn=output_results, inputs=[start_date, end_date, tickers_string, investment_amount],
120
+ outputs=[fig_cum_returns_optimized, allocation_df, \
121
+ expected_annual_return,leftover, fig_indiv_prices, fig_cum_returns])
122
 
123
  app.launch()