-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualization_fallback.py
More file actions
336 lines (275 loc) · 10.3 KB
/
visualization_fallback.py
File metadata and controls
336 lines (275 loc) · 10.3 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
"""
Fallback visualization module using matplotlib when Plotly fails
"""
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
import pandas as pd
import numpy as np
from typing import Dict, List, Tuple, Optional
import io
import base64
class MatplotlibVisualizer:
"""Fallback visualizer using matplotlib when Plotly is not available"""
def __init__(self, theme: str = "light"):
"""
Initialize visualizer
Args:
theme: Theme to use ('light' or 'dark')
"""
self.theme = theme
self.setup_style()
def setup_style(self):
"""Setup matplotlib style"""
if self.theme == "dark":
plt.style.use('dark_background')
self.colors = ['#00d4ff', '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57']
else:
plt.style.use('default')
self.colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b']
# Set default figure size
plt.rcParams['figure.figsize'] = (10, 6)
plt.rcParams['font.size'] = 10
def plot_to_base64(self, fig) -> str:
"""Convert matplotlib figure to base64 string for Streamlit"""
buffer = io.BytesIO()
fig.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
buffer.seek(0)
image_base64 = base64.b64encode(buffer.read()).decode()
buffer.close()
return image_base64
def plot_efficient_frontier(self, efficient_frontier_data: pd.DataFrame,
optimal_portfolio: Dict = None) -> str:
"""
Create efficient frontier plot
Args:
efficient_frontier_data: DataFrame with portfolio data
optimal_portfolio: Dictionary with optimal portfolio data
Returns:
Base64 encoded image string
"""
fig, ax = plt.subplots(figsize=(10, 6))
# Plot random portfolios
scatter = ax.scatter(
efficient_frontier_data['volatility'],
efficient_frontier_data['return'],
c=efficient_frontier_data['sharpe_ratio'],
cmap='viridis',
alpha=0.6,
s=30
)
# Add colorbar
cbar = plt.colorbar(scatter, ax=ax)
cbar.set_label('Sharpe Ratio')
# Plot optimal portfolio if provided
if optimal_portfolio and 'metrics' in optimal_portfolio:
metrics = optimal_portfolio['metrics']
ax.scatter(
metrics['volatility'],
metrics['expected_return'],
c='red',
s=100,
marker='*',
label='Optimal Portfolio'
)
ax.set_xlabel('Volatility (Risk)')
ax.set_ylabel('Expected Return')
ax.set_title('Efficient Frontier')
ax.legend()
ax.grid(True, alpha=0.3)
return self.plot_to_base64(fig)
def plot_portfolio_weights(self, weights: Dict[str, float]) -> str:
"""
Create pie chart for portfolio weights
Args:
weights: Dictionary with stock symbols and weights
Returns:
Base64 encoded image string
"""
fig, ax = plt.subplots(figsize=(8, 8))
symbols = list(weights.keys())
weight_values = list(weights.values())
wedges, texts, autotexts = ax.pie(
weight_values,
labels=symbols,
autopct='%1.1f%%',
colors=self.colors[:len(symbols)],
startangle=90
)
ax.set_title('Portfolio Allocation')
# Improve text readability
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')
return self.plot_to_base64(fig)
def plot_capm_analysis(self, capm_results: pd.DataFrame, sml_data: pd.DataFrame) -> str:
"""
Create CAPM Security Market Line plot
Args:
capm_results: DataFrame with CAPM analysis results
sml_data: DataFrame with SML data points
Returns:
Base64 encoded image string
"""
fig, ax = plt.subplots(figsize=(10, 6))
# Plot Security Market Line
ax.plot(
sml_data['beta'],
sml_data['expected_return'],
'b--',
linewidth=2,
label='Security Market Line'
)
# Plot individual stocks
for symbol in capm_results.index:
ax.scatter(
capm_results.loc[symbol, 'beta'],
capm_results.loc[symbol, 'actual_return'],
s=100,
label=symbol,
alpha=0.7
)
# Add stock symbol as annotation
ax.annotate(
symbol,
(capm_results.loc[symbol, 'beta'], capm_results.loc[symbol, 'actual_return']),
xytext=(5, 5),
textcoords='offset points',
fontsize=8
)
ax.set_xlabel('Beta (Systematic Risk)')
ax.set_ylabel('Expected Return')
ax.set_title('CAPM Analysis - Security Market Line')
ax.legend()
ax.grid(True, alpha=0.3)
return self.plot_to_base64(fig)
def plot_stock_forecasts(self, symbol: str, historical_prices: pd.Series,
forecast_data: pd.DataFrame) -> str:
"""
Create stock price forecast plot
Args:
symbol: Stock symbol
historical_prices: Historical price data
forecast_data: Forecast data with confidence intervals
Returns:
Base64 encoded image string
"""
fig, ax = plt.subplots(figsize=(12, 6))
# Plot historical prices
ax.plot(
historical_prices.index,
historical_prices.values,
'b-',
linewidth=2,
label='Historical Prices'
)
# Plot forecast
ax.plot(
forecast_data['date'],
forecast_data['forecast'],
'r--',
linewidth=2,
label='Forecast'
)
# Plot confidence intervals if available
if 'lower_bound' in forecast_data.columns and 'upper_bound' in forecast_data.columns:
ax.fill_between(
forecast_data['date'],
forecast_data['lower_bound'],
forecast_data['upper_bound'],
alpha=0.3,
color='red',
label='Confidence Interval'
)
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.set_title(f'{symbol} Price Forecast')
ax.legend()
ax.grid(True, alpha=0.3)
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
plt.tight_layout()
return self.plot_to_base64(fig)
def plot_correlation_heatmap(self, correlation_matrix: pd.DataFrame) -> str:
"""
Create correlation heatmap
Args:
correlation_matrix: Correlation matrix DataFrame
Returns:
Base64 encoded image string
"""
fig, ax = plt.subplots(figsize=(10, 8))
# Create heatmap
sns.heatmap(
correlation_matrix,
annot=True,
cmap='RdBu_r',
center=0,
square=True,
fmt='.2f',
ax=ax
)
ax.set_title('Stock Correlation Matrix')
return self.plot_to_base64(fig)
def plot_risk_return_scatter(self, individual_metrics: pd.DataFrame) -> str:
"""
Create risk-return scatter plot for individual stocks
Args:
individual_metrics: DataFrame with individual stock metrics
Returns:
Base64 encoded image string
"""
fig, ax = plt.subplots(figsize=(10, 6))
scatter = ax.scatter(
individual_metrics['Volatility'],
individual_metrics['Expected Return'],
c=individual_metrics['Sharpe Ratio'],
cmap='viridis',
s=100,
alpha=0.7
)
# Add stock labels
for symbol in individual_metrics.index:
ax.annotate(
symbol,
(individual_metrics.loc[symbol, 'Volatility'],
individual_metrics.loc[symbol, 'Expected Return']),
xytext=(5, 5),
textcoords='offset points',
fontsize=8
)
# Add colorbar
cbar = plt.colorbar(scatter, ax=ax)
cbar.set_label('Sharpe Ratio')
ax.set_xlabel('Volatility (Risk)')
ax.set_ylabel('Expected Return')
ax.set_title('Risk-Return Analysis')
ax.grid(True, alpha=0.3)
return self.plot_to_base64(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