forked from Kowsi/SP500-Performance-Analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimproved_code.py
More file actions
301 lines (246 loc) · 9.11 KB
/
Copy pathimproved_code.py
File metadata and controls
301 lines (246 loc) · 9.11 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
import pandas as pd
import plotly.graph_objects as go
from typing import List, Optional, Union
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def get_time_series_figure_improved(value: Optional[Union[List[str], str]]) -> go.Figure:
"""
Create a time series figure for given stock tickers.
Args:
value: List of ticker symbols or single ticker symbol
Returns:
go.Figure: Plotly figure object with time series data
"""
global master_df, button
# Input validation and normalization
if not value:
logger.info("No tickers provided, returning empty figure")
return go.Figure(layout={'template': 'plotly_dark'})
# Normalize input to list
tickers = [value] if isinstance(value, str) else value
if not tickers:
return go.Figure(layout={'template': 'plotly_dark'})
# Pre-fetch all data to avoid repeated calls in loop
ticker_data = {}
failed_tickers = []
for ticker in tickers:
try:
df = get_master_df(ticker)
if df is not None and not df.empty and ticker in df.columns:
ticker_data[ticker] = df
logger.info(f"{ticker}, master_df.shape: {df.shape}")
else:
failed_tickers.append(ticker)
logger.warning(f"No data available for ticker: {ticker}")
except Exception as e:
failed_tickers.append(ticker)
logger.error(f"Error fetching data for {ticker}: {e}")
# Log failed tickers
if failed_tickers:
logger.warning(f"Failed to fetch data for tickers: {failed_tickers}")
# Create traces using list comprehension for better performance
traces = [
go.Scatter(
x=df['Date'],
y=df[ticker],
name=ticker,
mode='lines',
hovertemplate=f'<b>{ticker}</b><br>' +
'Date: %{x}<br>' +
'Price: $%{y:.2f}<extra></extra>'
)
for ticker, df in ticker_data.items()
]
# Create figure with all traces at once
fig = go.Figure(data=traces)
# Configure layout
fig.update_xaxes(
rangeslider=dict(visible=True, bgcolor='white'),
rangeselector=dict(buttons=button, bgcolor='blue')
)
fig.update_layout(
template='plotly_dark',
yaxis_title='Price ($)',
xaxis_title='Date',
title='Stock Price Time Series',
hovermode='x unified',
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
)
)
return fig
def get_time_series_figure_alternative(value: Optional[Union[List[str], str]]) -> go.Figure:
"""
Alternative implementation using pandas operations for better performance.
Args:
value: List of ticker symbols or single ticker symbol
Returns:
go.Figure: Plotly figure object with time series data
"""
global master_df, button
# Input validation
if not value:
return go.Figure(layout={'template': 'plotly_dark'})
tickers = [value] if isinstance(value, str) else value
if not tickers:
return go.Figure(layout={'template': 'plotly_dark'})
# Batch process all tickers
all_data = []
for ticker in tickers:
try:
df = get_master_df(ticker)
if df is not None and not df.empty and ticker in df.columns:
# Create a copy with ticker info for melting
ticker_df = df[['Date', ticker]].copy()
ticker_df['Ticker'] = ticker
ticker_df = ticker_df.rename(columns={ticker: 'Price'})
all_data.append(ticker_df)
logger.info(f"{ticker}, master_df.shape: {df.shape}")
except Exception as e:
logger.error(f"Error processing {ticker}: {e}")
if not all_data:
logger.warning("No valid data found for any ticker")
return go.Figure(layout={'template': 'plotly_dark'})
# Combine all data
combined_df = pd.concat(all_data, ignore_index=True)
# Create figure using plotly express style approach
fig = go.Figure()
for ticker in combined_df['Ticker'].unique():
ticker_data = combined_df[combined_df['Ticker'] == ticker]
fig.add_trace(
go.Scatter(
x=ticker_data['Date'],
y=ticker_data['Price'],
name=ticker,
mode='lines',
hovertemplate=f'<b>{ticker}</b><br>' +
'Date: %{x}<br>' +
'Price: $%{y:.2f}<extra></extra>'
)
)
# Configure layout
fig.update_xaxes(
rangeslider=dict(visible=True, bgcolor='white'),
rangeselector=dict(buttons=button, bgcolor='blue')
)
fig.update_layout(
template='plotly_dark',
yaxis_title='Price ($)',
xaxis_title='Date',
title='Stock Price Time Series',
hovermode='x unified'
)
return fig
# Additional utility functions for better code organization
def validate_tickers(tickers: Union[List[str], str]) -> List[str]:
"""
Validate and normalize ticker input.
Args:
tickers: Single ticker or list of tickers
Returns:
List[str]: Validated list of ticker symbols
"""
if not tickers:
return []
if isinstance(tickers, str):
return [tickers.upper().strip()]
if isinstance(tickers, list):
return [ticker.upper().strip() for ticker in tickers if ticker and isinstance(ticker, str)]
return []
def create_error_figure(message: str = "No data available") -> go.Figure:
"""
Create a figure to display error messages.
Args:
message: Error message to display
Returns:
go.Figure: Figure with error message
"""
fig = go.Figure()
fig.add_annotation(
text=message,
xref="paper", yref="paper",
x=0.5, y=0.5,
showarrow=False,
font=dict(size=16, color="white")
)
fig.update_layout(
template='plotly_dark',
title="Error",
showlegend=False
)
return fig
# Performance optimized version with caching
class TimeSeriesPlotter:
"""
Class-based approach for better state management and caching.
"""
def __init__(self):
self.data_cache = {}
self.logger = logging.getLogger(self.__class__.__name__)
def get_cached_data(self, ticker: str) -> Optional[pd.DataFrame]:
"""Get data from cache or fetch if not available."""
if ticker not in self.data_cache:
try:
df = get_master_df(ticker)
if df is not None and not df.empty:
self.data_cache[ticker] = df
self.logger.info(f"Cached data for {ticker}, shape: {df.shape}")
else:
return None
except Exception as e:
self.logger.error(f"Error fetching data for {ticker}: {e}")
return None
return self.data_cache.get(ticker)
def create_time_series_figure(self, tickers: Optional[Union[List[str], str]]) -> go.Figure:
"""
Create optimized time series figure with caching.
Args:
tickers: List of ticker symbols or single ticker
Returns:
go.Figure: Plotly figure object
"""
validated_tickers = validate_tickers(tickers)
if not validated_tickers:
return create_error_figure("No valid tickers provided")
traces = []
successful_tickers = []
for ticker in validated_tickers:
df = self.get_cached_data(ticker)
if df is not None and ticker in df.columns:
traces.append(
go.Scatter(
x=df['Date'],
y=df[ticker],
name=ticker,
mode='lines',
hovertemplate=f'<b>{ticker}</b><br>' +
'Date: %{x}<br>' +
'Price: $%{y:.2f}<extra></extra>'
)
)
successful_tickers.append(ticker)
if not traces:
return create_error_figure("No data available for the selected tickers")
fig = go.Figure(data=traces)
# Configure layout
fig.update_xaxes(
rangeslider=dict(visible=True, bgcolor='white'),
rangeselector=dict(buttons=button, bgcolor='blue')
)
fig.update_layout(
template='plotly_dark',
yaxis_title='Price ($)',
xaxis_title='Date',
title=f'Time Series: {", ".join(successful_tickers)}',
hovermode='x unified'
)
return fig
# Example usage:
# plotter = TimeSeriesPlotter()
# fig = plotter.create_time_series_figure(['AAPL', 'GOOGL', 'MSFT'])