-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualization.py
More file actions
380 lines (322 loc) · 12.5 KB
/
visualization.py
File metadata and controls
380 lines (322 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Visualization utilities for the Investor Decision Support System
Provides functions for creating interactive charts and plots
"""
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
from typing import Dict, List, Tuple, Optional
import matplotlib.pyplot as plt
import seaborn as sns
class FinancialVisualizer:
"""Class for creating financial visualizations"""
def __init__(self, theme: str = "plotly_white"):
"""
Initialize visualizer
Args:
theme: Plotly theme to use
"""
self.theme = theme
self.colors = px.colors.qualitative.Set3
def plot_efficient_frontier(self, efficient_frontier_data: pd.DataFrame,
optimal_portfolio: Dict = None) -> go.Figure:
"""
Create efficient frontier plot
Args:
efficient_frontier_data: DataFrame with portfolio data
optimal_portfolio: Dictionary with optimal portfolio data
Returns:
Plotly figure
"""
fig = go.Figure()
# Plot random portfolios
fig.add_trace(go.Scatter(
x=efficient_frontier_data['volatility'],
y=efficient_frontier_data['return'],
mode='markers',
marker=dict(
size=8,
color=efficient_frontier_data['sharpe_ratio'],
colorscale='Viridis',
showscale=True,
colorbar=dict(title="Sharpe Ratio")
),
name='Random Portfolios',
hovertemplate='<b>Volatility:</b> %{x:.3f}<br>' +
'<b>Return:</b> %{y:.3f}<br>' +
'<b>Sharpe Ratio:</b> %{marker.color:.3f}<extra></extra>'
))
# Plot optimal portfolio if provided
if optimal_portfolio and 'metrics' in optimal_portfolio:
metrics = optimal_portfolio['metrics']
fig.add_trace(go.Scatter(
x=[metrics['volatility']],
y=[metrics['expected_return']],
mode='markers',
marker=dict(
size=15,
color='red',
symbol='star'
),
name='Optimal Portfolio',
hovertemplate='<b>Optimal Portfolio</b><br>' +
'<b>Volatility:</b> %{x:.3f}<br>' +
'<b>Return:</b> %{y:.3f}<br>' +
'<b>Sharpe Ratio:</b> ' + f"{metrics['sharpe_ratio']:.3f}<extra></extra>"
))
fig.update_layout(
title='Efficient Frontier',
xaxis_title='Volatility (Risk)',
yaxis_title='Expected Return',
template=self.theme,
height=500
)
return fig
def plot_portfolio_weights(self, weights: Dict[str, float]) -> go.Figure:
"""
Create pie chart for portfolio weights
Args:
weights: Dictionary with stock symbols and weights
Returns:
Plotly figure
"""
symbols = list(weights.keys())
weight_values = list(weights.values())
fig = go.Figure(data=[go.Pie(
labels=symbols,
values=weight_values,
hovertemplate='<b>%{label}</b><br>Weight: %{percent}<extra></extra>'
)])
fig.update_layout(
title='Portfolio Allocation',
template=self.theme,
height=400
)
return fig
def plot_capm_analysis(self, capm_results: pd.DataFrame, sml_data: pd.DataFrame) -> go.Figure:
"""
Create CAPM Security Market Line plot
Args:
capm_results: DataFrame with CAPM analysis results
sml_data: DataFrame with SML data points
Returns:
Plotly figure
"""
fig = go.Figure()
# Plot Security Market Line
fig.add_trace(go.Scatter(
x=sml_data['beta'],
y=sml_data['expected_return'],
mode='lines',
name='Security Market Line',
line=dict(color='blue', dash='dash')
))
# Plot individual stocks
for symbol in capm_results.index:
fig.add_trace(go.Scatter(
x=[capm_results.loc[symbol, 'beta']],
y=[capm_results.loc[symbol, 'actual_return']],
mode='markers+text',
text=[symbol],
textposition='top center',
name=symbol,
hovertemplate=f'<b>{symbol}</b><br>' +
'<b>Beta:</b> %{x:.3f}<br>' +
'<b>Actual Return:</b> %{y:.3f}<br>' +
'<b>Expected Return:</b> ' + f"{capm_results.loc[symbol, 'expected_return']:.3f}<extra></extra>"
))
fig.update_layout(
title='CAPM Analysis - Security Market Line',
xaxis_title='Beta (Systematic Risk)',
yaxis_title='Expected Return',
template=self.theme,
height=500
)
return fig
def plot_stock_forecasts(self, symbol: str, historical_prices: pd.Series,
forecast_data: pd.DataFrame) -> go.Figure:
"""
Create stock price forecast plot
Args:
symbol: Stock symbol
historical_prices: Historical price data
forecast_data: Forecast data with confidence intervals
Returns:
Plotly figure
"""
fig = go.Figure()
# Plot historical prices
fig.add_trace(go.Scatter(
x=historical_prices.index,
y=historical_prices.values,
mode='lines',
name='Historical Prices',
line=dict(color='blue')
))
# Plot forecast
fig.add_trace(go.Scatter(
x=forecast_data['date'],
y=forecast_data['forecast'],
mode='lines',
name='Forecast',
line=dict(color='red', dash='dash')
))
# Plot confidence intervals if available
if 'lower_bound' in forecast_data.columns and 'upper_bound' in forecast_data.columns:
fig.add_trace(go.Scatter(
x=forecast_data['date'],
y=forecast_data['upper_bound'],
mode='lines',
line=dict(width=0),
showlegend=False,
hoverinfo='skip'
))
fig.add_trace(go.Scatter(
x=forecast_data['date'],
y=forecast_data['lower_bound'],
mode='lines',
line=dict(width=0),
fill='tonexty',
fillcolor='rgba(255,0,0,0.2)',
name='Confidence Interval',
hoverinfo='skip'
))
fig.update_layout(
title=f'{symbol} Price Forecast',
xaxis_title='Date',
yaxis_title='Price',
template=self.theme,
height=500
)
return fig
def plot_correlation_heatmap(self, correlation_matrix: pd.DataFrame) -> go.Figure:
"""
Create correlation heatmap
Args:
correlation_matrix: Correlation matrix DataFrame
Returns:
Plotly figure
"""
fig = go.Figure(data=go.Heatmap(
z=correlation_matrix.values,
x=correlation_matrix.columns,
y=correlation_matrix.index,
colorscale='RdBu',
zmid=0,
text=np.round(correlation_matrix.values, 2),
texttemplate='%{text}',
textfont={"size": 10},
hovertemplate='<b>%{y} vs %{x}</b><br>Correlation: %{z:.3f}<extra></extra>'
))
fig.update_layout(
title='Stock Correlation Matrix',
template=self.theme,
height=500
)
return fig
def plot_risk_return_scatter(self, individual_metrics: pd.DataFrame) -> go.Figure:
"""
Create risk-return scatter plot for individual stocks
Args:
individual_metrics: DataFrame with individual stock metrics
Returns:
Plotly figure
"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x=individual_metrics['Volatility'],
y=individual_metrics['Expected Return'],
mode='markers+text',
text=individual_metrics.index,
textposition='top center',
marker=dict(
size=10,
color=individual_metrics['Sharpe Ratio'],
colorscale='Viridis',
showscale=True,
colorbar=dict(title="Sharpe Ratio")
),
hovertemplate='<b>%{text}</b><br>' +
'<b>Volatility:</b> %{x:.3f}<br>' +
'<b>Expected Return:</b> %{y:.3f}<br>' +
'<b>Sharpe Ratio:</b> %{marker.color:.3f}<extra></extra>'
))
fig.update_layout(
title='Risk-Return Analysis',
xaxis_title='Volatility (Risk)',
yaxis_title='Expected Return',
template=self.theme,
height=500
)
return fig
def plot_portfolio_performance(self, portfolio_metrics: Dict,
individual_metrics: pd.DataFrame) -> go.Figure:
"""
Create portfolio performance comparison plot
Args:
portfolio_metrics: Dictionary with portfolio metrics
individual_metrics: DataFrame with individual stock metrics
Returns:
Plotly figure
"""
fig = go.Figure()
# Plot individual stocks
fig.add_trace(go.Scatter(
x=individual_metrics['Volatility'],
y=individual_metrics['Expected Return'],
mode='markers',
marker=dict(size=8, color='lightblue'),
name='Individual Stocks',
hovertemplate='<b>%{text}</b><br>' +
'<b>Volatility:</b> %{x:.3f}<br>' +
'<b>Expected Return:</b> %{y:.3f}<extra></extra>'
))
# Plot portfolio
fig.add_trace(go.Scatter(
x=[portfolio_metrics['volatility']],
y=[portfolio_metrics['expected_return']],
mode='markers',
marker=dict(size=15, color='red', symbol='star'),
name='Portfolio',
hovertemplate='<b>Portfolio</b><br>' +
'<b>Volatility:</b> %{x:.3f}<br>' +
'<b>Expected Return:</b> %{y:.3f}<br>' +
'<b>Sharpe Ratio:</b> ' + f"{portfolio_metrics['sharpe_ratio']:.3f}<extra></extra>"
))
fig.update_layout(
title='Portfolio vs Individual Stocks',
xaxis_title='Volatility (Risk)',
yaxis_title='Expected Return',
template=self.theme,
height=500
)
return fig
def create_kpi_cards(self, metrics: Dict) -> List[Dict]:
"""
Create KPI card data for Streamlit
Args:
metrics: Dictionary with financial metrics
Returns:
List of dictionaries with KPI data
"""
kpi_cards = []
# Define KPI mappings
kpi_mappings = {
'expected_return': {'label': 'Expected Return', 'format': '{:.2%}', 'color': 'green'},
'volatility': {'label': 'Volatility', 'format': '{:.2%}', 'color': 'orange'},
'sharpe_ratio': {'label': 'Sharpe Ratio', 'format': '{:.3f}', 'color': 'blue'},
'beta': {'label': 'Beta', 'format': '{:.3f}', 'color': 'purple'},
'alpha': {'label': 'Alpha', 'format': '{:.2%}', 'color': 'red'}
}
for key, value in metrics.items():
if key in kpi_mappings:
mapping = kpi_mappings[key]
formatted_value = mapping['format'].format(value)
kpi_cards.append({
'label': mapping['label'],
'value': formatted_value,
'color': mapping['color']
})
return kpi_cards