Faham commited on
Commit
629bac3
·
1 Parent(s): b92bfe9

REMOVE: redundant code and empty files

Browse files
Files changed (3) hide show
  1. Home.py +0 -9
  2. streamlit_app.py +0 -0
  3. test_prophet_accuracy.py +0 -373
Home.py CHANGED
@@ -1544,15 +1544,6 @@ def main():
1544
  # Rerun to display the new message (charts and news are cached)
1545
  st.rerun()
1546
 
1547
- # Clear chat button
1548
- # col1, col2 = st.columns([1, 4])
1549
- # with col1:
1550
- # if st.button("🗑️ Clear Chat History", key="clear_button"):
1551
- # st.session_state.messages = []
1552
- # st.rerun()
1553
- # with col2:
1554
- # st.markdown("*Chat history will be maintained during your session*")
1555
-
1556
 
1557
  if __name__ == "__main__":
1558
  main()
 
1544
  # Rerun to display the new message (charts and news are cached)
1545
  st.rerun()
1546
 
 
 
 
 
 
 
 
 
 
1547
 
1548
  if __name__ == "__main__":
1549
  main()
streamlit_app.py DELETED
File without changes
test_prophet_accuracy.py DELETED
@@ -1,373 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Prophet Accuracy Test Script
4
- Trains Prophet model on given ticker data up to June 2025 and tests predictions for July 2025.
5
- """
6
-
7
- import yfinance as yf
8
- import pandas as pd
9
- from prophet import Prophet
10
- from datetime import datetime
11
- import numpy as np
12
- from sklearn.metrics import (
13
- mean_absolute_error,
14
- mean_squared_error,
15
- mean_absolute_percentage_error,
16
- )
17
- import warnings
18
-
19
- warnings.filterwarnings("ignore")
20
-
21
- ticker = "AAPL"
22
-
23
-
24
- def get_aapl_data():
25
- """Get AAPL historical data."""
26
- print("📊 Fetching AAPL historical data...")
27
-
28
- # Get data for the past 2 years to have enough training data
29
- raw_data = yf.Ticker("AAPL")
30
- data = raw_data.history(period="2y")
31
-
32
- if data.empty:
33
- raise ValueError("No data received for AAPL")
34
-
35
- print(f"✅ Retrieved {len(data)} days of AAPL data")
36
- print(f"📅 Date range: {data.index.min().date()} to {data.index.max().date()}")
37
-
38
- return data
39
-
40
-
41
- def prepare_prophet_data(data, end_date):
42
- """Prepare data for Prophet training (up to end_date)."""
43
- print(f"\n🔧 Preparing Prophet data up to {end_date.date()}...")
44
-
45
- # Convert end_date to timezone-aware datetime to match data index
46
- if data.index.tz is not None:
47
- end_date = pd.Timestamp(end_date).tz_localize(data.index.tz)
48
-
49
- # Filter data up to end_date
50
- training_data = data[data.index <= end_date].copy()
51
-
52
- # Remove outliers using IQR method
53
- Q1 = training_data["Close"].quantile(0.25)
54
- Q3 = training_data["Close"].quantile(0.75)
55
- IQR = Q3 - Q1
56
- lower_bound = Q1 - 1.5 * IQR
57
- upper_bound = Q3 + 1.5 * IQR
58
-
59
- # Filter out outliers
60
- training_data = training_data[
61
- (training_data["Close"] >= lower_bound)
62
- & (training_data["Close"] <= upper_bound)
63
- ]
64
-
65
- print(
66
- f"📊 Removed outliers: {len(data[data.index <= end_date]) - len(training_data)} points"
67
- )
68
-
69
- # Prepare for Prophet (requires 'ds' and 'y' columns)
70
- prophet_data = training_data.reset_index()
71
- prophet_data["ds"] = prophet_data["Date"].dt.tz_localize(None) # Remove timezone
72
- prophet_data["y"] = prophet_data["Close"]
73
-
74
- # Select only required columns
75
- prophet_data = prophet_data[["ds", "y"]]
76
-
77
- print(f"✅ Training data prepared: {len(prophet_data)} days")
78
- print(
79
- f"📈 Price range: ${prophet_data['y'].min():.2f} - ${prophet_data['y'].max():.2f}"
80
- )
81
-
82
- return prophet_data
83
-
84
-
85
- def train_prophet_model(data):
86
- """Train Prophet model on the provided data."""
87
- print("\n🤖 Training Prophet model...")
88
-
89
- # Configure Prophet model with optimized parameters
90
- model = Prophet(
91
- yearly_seasonality=True,
92
- weekly_seasonality=True,
93
- daily_seasonality=False,
94
- changepoint_prior_scale=0.01, # Reduced for smoother trends
95
- seasonality_prior_scale=10.0, # Increased seasonality strength
96
- seasonality_mode="multiplicative",
97
- interval_width=0.8, # Tighter confidence intervals
98
- mcmc_samples=0, # Disable MCMC for faster training
99
- )
100
-
101
- # Add custom seasonalities for better stock patterns
102
- model.add_seasonality(name="monthly", period=30.5, fourier_order=5)
103
-
104
- model.add_seasonality(name="quarterly", period=91.25, fourier_order=8)
105
-
106
- # Train the model
107
- model.fit(data)
108
-
109
- print("✅ Prophet model trained successfully")
110
- return model
111
-
112
-
113
- def make_predictions(model, start_date, end_date):
114
- """Make predictions for the specified date range."""
115
- print(f"\n🔮 Making predictions from {start_date.date()} to {end_date.date()}...")
116
-
117
- # Calculate the number of days to predict
118
- days_to_predict = (end_date - start_date).days + 1
119
-
120
- # Create future dataframe
121
- future = model.make_future_dataframe(periods=days_to_predict)
122
- forecast = model.predict(future)
123
-
124
- # Filter predictions for the specified period
125
- predictions = forecast[
126
- (forecast["ds"] >= start_date) & (forecast["ds"] <= end_date)
127
- ].copy()
128
-
129
- print(f"✅ Generated {len(predictions)} predictions for {days_to_predict} days")
130
-
131
- return predictions
132
-
133
-
134
- def get_actual_july_data(data, start_date, end_date):
135
- """Get actual AAPL data for July."""
136
- print(f"\n📊 Fetching actual July data...")
137
-
138
- # Convert dates to timezone-aware datetime to match data index
139
- if data.index.tz is not None:
140
- start_date = pd.Timestamp(start_date).tz_localize(data.index.tz)
141
- end_date = pd.Timestamp(end_date).tz_localize(data.index.tz)
142
-
143
- # Get actual data for July
144
- actual_data = data[(data.index >= start_date) & (data.index <= end_date)].copy()
145
-
146
- print(f"✅ Retrieved {len(actual_data)} days of actual July data")
147
-
148
- return actual_data
149
-
150
-
151
- def calculate_accuracy_metrics(predictions, actual_data):
152
- """Calculate accuracy metrics."""
153
- print("\n📈 Calculating accuracy metrics...")
154
-
155
- # Prepare actual data with timezone-naive dates for merging
156
- actual_data_prepared = actual_data.reset_index().copy()
157
- actual_data_prepared["Date"] = actual_data_prepared["Date"].dt.tz_localize(None)
158
-
159
- # Merge predictions with actual data
160
- comparison = pd.merge(
161
- predictions[["ds", "yhat", "yhat_lower", "yhat_upper"]],
162
- actual_data_prepared[["Date", "Close"]],
163
- left_on="ds",
164
- right_on="Date",
165
- how="inner",
166
- )
167
-
168
- if comparison.empty:
169
- print("❌ No overlapping data found for comparison")
170
- return None
171
-
172
- # Calculate metrics
173
- mae = mean_absolute_error(comparison["Close"], comparison["yhat"])
174
- mse = mean_squared_error(comparison["Close"], comparison["yhat"])
175
- rmse = np.sqrt(mse)
176
- mape = mean_absolute_percentage_error(comparison["Close"], comparison["yhat"]) * 100
177
-
178
- # Calculate directional accuracy (up/down prediction)
179
- actual_direction = comparison["Close"].diff().dropna()
180
- predicted_direction = comparison["yhat"].diff().dropna()
181
-
182
- # Align the data
183
- min_len = min(len(actual_direction), len(predicted_direction))
184
- actual_direction = actual_direction.iloc[-min_len:]
185
- predicted_direction = predicted_direction.iloc[-min_len:]
186
-
187
- directional_accuracy = (
188
- np.mean((actual_direction > 0) == (predicted_direction > 0)) * 100
189
- )
190
-
191
- return {
192
- "mae": mae,
193
- "mse": mse,
194
- "rmse": rmse,
195
- "mape": mape,
196
- "directional_accuracy": directional_accuracy,
197
- "comparison_data": comparison,
198
- }
199
-
200
-
201
- def print_results(metrics, predictions, actual_data):
202
- """Print detailed results."""
203
- print("\n" + "=" * 60)
204
- print("📊 PROPHET ACCURACY TEST RESULTS")
205
- print("=" * 60)
206
-
207
- if metrics is None:
208
- print("❌ No metrics available - insufficient data for comparison")
209
- return
210
-
211
- print(f"\n📈 Accuracy Metrics:")
212
- print(f" Mean Absolute Error (MAE): ${metrics['mae']:.2f}")
213
- print(f" Mean Squared Error (MSE): {metrics['mse']:.2f}")
214
- print(f" Root Mean Squared Error (RMSE): ${metrics['rmse']:.2f}")
215
- print(f" Mean Absolute Percentage Error (MAPE): {metrics['mape']:.2f}%")
216
- print(f" Directional Accuracy: {metrics['directional_accuracy']:.1f}%")
217
-
218
- print(f"\n📊 Prediction Summary:")
219
- print(f" Training Period: Up to June 30, 2025")
220
- print(f" Test Period: July 1-25, 2025")
221
- print(f" Test Days: {len(metrics['comparison_data'])}")
222
-
223
- # Show some sample predictions vs actual
224
- comparison = metrics["comparison_data"]
225
- print(f"\n📋 Sample Predictions vs Actual (first 5 days):")
226
- print(f"{'Date':<12} {'Predicted':<12} {'Actual':<12} {'Error':<12}")
227
- print("-" * 50)
228
-
229
- for i in range(min(5, len(comparison))):
230
- row = comparison.iloc[i]
231
- error = row["Close"] - row["yhat"]
232
- print(
233
- f"{row['ds'].strftime('%Y-%m-%d'):<12} "
234
- f"${row['yhat']:<11.2f} "
235
- f"${row['Close']:<11.2f} "
236
- f"${error:<11.2f}"
237
- )
238
-
239
- print("\n" + "=" * 60)
240
-
241
-
242
- def test_multiple_configurations(data, training_end, test_start, test_end):
243
- """Test multiple Prophet configurations to find the best one."""
244
- print("\n🔬 Testing multiple Prophet configurations...")
245
-
246
- configurations = [
247
- {
248
- "name": "Default",
249
- "params": {
250
- "yearly_seasonality": True,
251
- "weekly_seasonality": True,
252
- "daily_seasonality": False,
253
- "changepoint_prior_scale": 0.05,
254
- "seasonality_mode": "multiplicative",
255
- },
256
- },
257
- {
258
- "name": "Optimized",
259
- "params": {
260
- "yearly_seasonality": True,
261
- "weekly_seasonality": True,
262
- "daily_seasonality": False,
263
- "changepoint_prior_scale": 0.01,
264
- "seasonality_prior_scale": 10.0,
265
- "seasonality_mode": "multiplicative",
266
- "interval_width": 0.8,
267
- "mcmc_samples": 0,
268
- },
269
- },
270
- {
271
- "name": "Conservative",
272
- "params": {
273
- "yearly_seasonality": True,
274
- "weekly_seasonality": False,
275
- "daily_seasonality": False,
276
- "changepoint_prior_scale": 0.001,
277
- "seasonality_mode": "additive",
278
- },
279
- },
280
- ]
281
-
282
- best_config = None
283
- best_mape = float("inf")
284
- results = []
285
-
286
- for config in configurations:
287
- print(f"\n🧪 Testing {config['name']} configuration...")
288
-
289
- try:
290
- # Prepare training data
291
- training_data = prepare_prophet_data(data, training_end)
292
-
293
- # Create and train model
294
- model = Prophet(**config["params"])
295
-
296
- # Add custom seasonalities for optimized config
297
- if config["name"] == "Optimized":
298
- model.add_seasonality(name="monthly", period=30.5, fourier_order=5)
299
- model.add_seasonality(name="quarterly", period=91.25, fourier_order=8)
300
-
301
- model.fit(training_data)
302
-
303
- # Make predictions
304
- predictions = make_predictions(model, test_start, test_end)
305
-
306
- # Get actual data
307
- actual_data = get_actual_july_data(data, test_start, test_end)
308
-
309
- # Calculate metrics
310
- metrics = calculate_accuracy_metrics(predictions, actual_data)
311
-
312
- if metrics:
313
- results.append({"config": config["name"], "metrics": metrics})
314
-
315
- if metrics["mape"] < best_mape:
316
- best_mape = metrics["mape"]
317
- best_config = config["name"]
318
-
319
- print(
320
- f"✅ {config['name']}: MAPE = {metrics['mape']:.2f}%, Directional = {metrics['directional_accuracy']:.1f}%"
321
- )
322
- else:
323
- print(f"❌ {config['name']}: No valid metrics")
324
-
325
- except Exception as e:
326
- print(f"❌ {config['name']}: Error - {e}")
327
-
328
- return best_config, results
329
-
330
-
331
- def main():
332
- """Main function to run the Prophet accuracy test."""
333
- print("🚀 Starting Prophet Accuracy Test for AAPL")
334
- print("=" * 60)
335
-
336
- try:
337
- # Define date ranges
338
- training_end = datetime(2025, 6, 30) # End of June 2025
339
- test_start = datetime(2025, 7, 1) # Start of July 2025
340
- test_end = datetime(2025, 7, 25) # End of July 2025 (up to 25th)
341
-
342
- print(f"📅 Training Period: Up to {training_end.date()}")
343
- print(f"📅 Test Period: {test_start.date()} to {test_end.date()}")
344
-
345
- # Get data
346
- data = get_aapl_data()
347
-
348
- # Test multiple configurations
349
- best_config, all_results = test_multiple_configurations(
350
- data, training_end, test_start, test_end
351
- )
352
-
353
- if best_config:
354
- print(f"\n🏆 Best configuration: {best_config}")
355
-
356
- # Use the best configuration for final results
357
- best_result = next(r for r in all_results if r["config"] == best_config)
358
- metrics = best_result["metrics"]
359
-
360
- # Print final results
361
- print_results(metrics, None, None)
362
- else:
363
- print("\n❌ No valid configurations found")
364
-
365
- except Exception as e:
366
- print(f"\n❌ Error during testing: {e}")
367
- import traceback
368
-
369
- traceback.print_exc()
370
-
371
-
372
- if __name__ == "__main__":
373
- main()