-
Notifications
You must be signed in to change notification settings - Fork 0
/
time_series_analysis_204.py
1543 lines (1255 loc) · 64.1 KB
/
time_series_analysis_204.py
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# time_series_analysis_204.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Standard library imports
import os
import random
import webbrowser
import winsound
import time
# Third-party imports for data handling and numerical operations
'''
Use numpy 1.26.4
'''
import numpy as np
import pandas as pd
# Statistical modeling and diagnostics from statsmodels
import statsmodels.tsa.arima.model as arima_model
import statsmodels.api as sm
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf, pacf
from statsmodels.stats.diagnostic import acorr_ljungbox, het_breuschpagan, het_white
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
from multiprocessing import Pool
# Additional statistical tools from scipy
from scipy import stats
from scipy.stats import binomtest
# Visualization libraries
import matplotlib.pyplot as plt
import plotly.express as px
# Time series analysis with auto_arima from pmdarima
from pmdarima import auto_arima
# Terminal coloring with colorama
from colorama import Back, Fore, Style, init
# Initialize colorama for colored text output in the console
init(autoreset=True)
# Define constants for various text styles and colors
HEADER_BG = Back.BLUE
HEADER_FG = Fore.WHITE
HIGHLIGHT_BG = Back.GREEN
HIGHLIGHT_FG = Fore.WHITE
INFO_FG = Fore.CYAN
WARNING_FG = Fore.RED
PROMPT_FG = Fore.YELLOW
DESC_FG = Fore.YELLOW
OPTION_FG = Fore.GREEN
BORDER = Fore.BLUE
RESET = Style.RESET_ALL
# Minimum number of data points required for analysis
MIN_DATA_POINTS = 10
# List of available foreground colors for random text coloring
COLORS = [
Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA,
Fore.CYAN, Fore.WHITE
]
# Function to return text with random colors
def random_color_text(text):
return ''.join(random.choice(COLORS) + char for char in text) + Style.RESET_ALL
# Function to display the title screen of the program
def display_title_screen():
title = ("SmoothTrend: Holt-Winters, Holt, Simple Exponential Smoothing, ARIMA/SARIMA "
"and Trend Analysis Program v2.04")
author = "Author: C. van der Kaay (2024)"
options = (
"1. View full run-down",
"2. Proceed with the program"
)
# Print the title screen with styled text
print(HEADER_BG + HEADER_FG + Style.BRIGHT + "\n" + "=" * 50)
print(Fore.LIGHTWHITE_EX + Style.BRIGHT + f"{title.center(50)}")
print("=" * 50 + Style.RESET_ALL)
print(INFO_FG + "\nProgram Summary:")
print("This program performs advanced time series analysis using Holt-Winters, Holt Exponential Smoothing, "
"Simple Exponential Smoothing, and ARIMA/SARIMA methods. Key features include:")
print("- Data input: Manual entry or import from CSV files")
print("- Trend detection using Mann-Kendall and Cox-Stuart tests")
print("- Stationarity testing with Augmented Dickey-Fuller test")
print("- Seasonality detection using Fast Fourier Transform (FFT) and spectral analysis")
print("- Detailed residual analysis including Ljung-Box, Shapiro-Wilk, and Kolmogorov-Smirnov tests")
print("- Heteroscedasticity tests: Breusch-Pagan, White, and Spearman's rank correlation")
print("- Descriptive statistics computation: mean, median, mode, standard deviation, skewness, kurtosis, etc.")
print("- Data visualization: static and interactive plots, decomposition plots, residual plots, and ACF/PACF plots")
print("- Lag plot analysis to check for randomness")
print("- Forecasting with prediction intervals and error statistics (MSE, MAE, RMSE, MAPE)")
print("- Optimal parameter selection for each smoothing method")
print("- Automatic model selection for ARIMA/SARIMA using auto_arima, handling both seasonal and non-seasonal data")
print("- Seasonal decomposition for trend, seasonal, and residual components")
print("- Interactive data visualization using Plotly")
print("- Parallel processing for improved performance in parameter optimization")
print("- Comprehensive model selection guidance based on data characteristics")
print("- Debug mode for detailed calculation viewing")
print(INFO_FG + "\n" + "=" * 50)
print(author)
print("=" * 50 + Style.RESET_ALL)
print()
# Print each option on a new line
for option in options:
print(option)
# Function to display the full run-down of the program features
def view_full_rundown():
print(HEADER_BG + HEADER_FG + Style.BRIGHT + "\n" + "=" * 70)
print("Full Program Run-down".center(70))
print("=" * 70 + Style.RESET_ALL)
print(INFO_FG + "\nThis program offers comprehensive time series analysis with the following features:")
print("\n1. Data Input and Preprocessing:")
print(" - Manual data entry or import from CSV files")
print(" - Minimum data point requirement to ensure reliable analysis")
print(" - Descriptive statistics computation (mean, median, mode, standard deviation, skewness, etc.)")
print("\n2. Trend Analysis:")
print(" a. Mann-Kendall test:")
print(" - Non-parametric test for monotonic trends in time series")
print(" - Robust to outliers and non-normal distributions")
print(" b. Cox-Stuart test:")
print(" - Another non-parametric test for detecting trends")
print(" - Compares first and second half of the data series")
print("\n3. Stationarity Testing:")
print(" - Augmented Dickey-Fuller (ADF) test:")
print(" - Tests the null hypothesis of a unit root in the time series")
print(" - Helps determine if differencing is needed for further analysis")
print("\n4. Seasonality and Spectral Analysis:")
print(" - Automatic detection of seasonality using Fast Fourier Transform (FFT)")
print(" - Spectral analysis to identify significant frequencies in the data")
print(" - Seasonal decomposition to separate trend, seasonal, and residual components")
print("\n5. Exponential Smoothing Models:")
print(" a. Holt-Winters Exponential Smoothing:")
print(" - Triple exponential smoothing for data with trend and seasonality")
print(" - Optimal selection of alpha, beta, and gamma parameters")
print(" b. Holt Exponential Smoothing:")
print(" - Double exponential smoothing for data with trend")
print(" - Optimal selection of alpha and beta parameters")
print(" c. Simple Exponential Smoothing:")
print(" - Single exponential smoothing for data without clear trend or seasonality")
print(" - Optimal selection of alpha parameter")
print("\n6. ARIMA/SARIMA Modeling:")
print(" - Automatic order selection using auto_arima")
print(" - Fits ARIMA (Autoregressive Integrated Moving Average) or SARIMA (Seasonal ARIMA) model to the data")
print(" - Automatically detects and handles both seasonal and non-seasonal time series")
print(" - Uses detected seasonality to inform model selection")
print(" - Capable of modeling complex patterns including trends, cycles, and seasonality")
print("\n7. Forecasting:")
print(" - Generation of point forecasts for user-specified number of periods")
print(" - Calculation of prediction intervals for forecasts")
print(" - Computation of error statistics: MSE, MAE, RMSE, MAPE")
print("\n8. Residual Analysis:")
print(" a. Ljung-Box test for autocorrelation in residuals")
print(" b. Shapiro-Wilk test for normality of residuals")
print(" c. Kolmogorov-Smirnov test for normality of residuals")
print(" d. Heteroscedasticity tests:")
print(" - Breusch-Pagan test")
print(" - White's test")
print(" - Spearman's rank correlation test")
print("\n9. Data Visualization:")
print(" - Static plots using Matplotlib:")
print(" * Original data plot")
print(" * Fitted values and forecasts plot")
print(" * Residual plot")
print(" * Autocorrelation Function (ACF) plot")
print(" * Partial autocorrelation Function (PACF) plot")
print(" * Seasonal decomposition plot")
print(" * Lag plot")
print(" - Interactive plot using Plotly (opens in web browser)")
print("\n10. Additional Features:")
print(" - Debug mode for viewing detailed calculations during analysis")
print(" - Option to rerun analysis, start over, or quit at various stages")
print(" - Colorized console output for improved readability")
print(" - Sound alerts for warnings and errors")
print("\nThe program guides you through each step, allowing you to choose the appropriate")
print("analysis methods based on your data characteristics and research questions.")
print("Results are presented with both statistical outputs and visualizations to aid interpretation.")
print("\n" + "=" * 70)
input(PROMPT_FG + "\nPress Enter to proceed with the program..." + Style.RESET_ALL)
# Prints a formatted menu for selecting a modeling method with descriptions and color-coded text.
def print_menu():
border_line = BORDER + "-" * 78 + RESET
print(border_line)
print(PROMPT_FG + "\nBased on the trend and seasonality analysis we've performed, you can choose an "
+ " " * 18 + "\n"
+ "appropriate modeling method. "
+ " " * 53)
print("While the analysis can guide your choice, the final decision depends on your " + " " * 13)
print("understanding of the data and the specific forecasting needs. " + " " * 28)
print(border_line)
print(PROMPT_FG + "Here are the available modeling methods:" + " " * 36)
print(border_line)
methods = [
("Holt-Winters Exponential Smoothing",
"Best for data with clear trend and seasonality",
"Handles level, trend, and seasonal components"),
("Holt Exponential Smoothing",
"Suitable for data with trend but no seasonality",
"Handles level and trend components"),
("Simple Exponential Smoothing",
"Ideal for data without clear trend or seasonality",
"Focuses on the level component only"),
("ARIMA/SARIMA (Autoregressive Integrated Moving Average)",
"Versatile method that can handle various patterns",
"Can accommodate trend, seasonality, and complex autocorrelations\nAutomatically detects and applies seasonal "
"or non-seasonal modeling as appropriate")
]
for i, (title, desc1, desc2) in enumerate(methods, 1):
print(OPTION_FG + f"{i}. {title}" + " " * (78 - len(title) - 3))
print(DESC_FG + f" - {desc1}" + " " * (78 - len(desc1) - 7))
print(DESC_FG + f" - {desc2}" + " " * (78 - len(desc2) - 7))
if i < len(methods):
print(border_line)
print(border_line)
# Function that takes residuals as an argument and plots the ACF. Used in
# classes: HoltWintersExponentialSmoothing, HoltExponentialSmoothing, SimpleExponentialSmoothing, and ARIMA.
def plot_residual_acf(residuals):
max_lags = len(residuals) - 1
plot_acf(np.array(residuals), lags=np.arange(1, max_lags + 1))
plt.title('Residual Autocorrelation Function (ACF)', fontsize=14)
plt.xlabel('Lags', fontsize=12)
plt.ylabel('Autocorrelation', fontsize=12)
plt.grid(True)
plt.show()
def plot_residual_pacf(residuals):
max_lags = len(residuals) // 2 # Set the maximum number of lags to 50% of the sample size
plot_pacf(np.array(residuals), lags=max_lags)
plt.title('Residual Partial Autocorrelation Function (PACF)', fontsize=14)
plt.xlabel('Lags', fontsize=12)
plt.ylabel('Partial Autocorrelation', fontsize=12)
plt.grid(True)
plt.show()
# Evaluates autocorrelation in residuals using the Ljung-Box test and alerts if there are too few residuals or errors.
def perform_residual_analysis(residuals):
if len(residuals) <= 1:
winsound.Beep(1000, 500)
print(WARNING_FG + "Not enough residuals to perform analysis.")
return
try:
lb_result = acorr_ljungbox(residuals, lags=[min(10, len(residuals) // 2)], return_df=True)
lb_pvalue = lb_result['lb_pvalue'].iloc[0]
print(f"\n1. **Ljung-Box Test**")
print(f" - **Purpose:** Tests for the presence of autocorrelation in residuals.")
print(f" - **p-value:** {lb_pvalue:.4f}")
if lb_pvalue < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be autocorrelated.")
else:
print(" - **Interpretation:** No significant autocorrelation detected in residuals.")
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error during residual analysis: {e}")
# Plot the Autocorrelation Function (ACF) of the residuals. Used in
# classes: HoltWintersExponentialSmoothing, HoltExponentialSmoothing, SimpleExponentialSmoothing, and ARIMA.
def plot_residuals(residuals):
plt.figure(figsize=(10, 6))
time_periods = range(1, len(residuals))
plt.plot(time_periods, residuals[1:], marker='o', linestyle='-', color='b')
plt.title('Residuals Over Time', fontsize=14)
plt.xlabel('Time', fontsize=12)
plt.ylabel('Residual', fontsize=12)
plt.axhline(y=0, color='r', linestyle='--', linewidth=1.5)
plt.grid(True)
plt.show()
# Lag plot to check whether a data set or time series is random or not
def plot_lag(data, lag=1):
plt.figure(figsize=(10, 6))
plt.scatter(data[:-lag], data[lag:])
plt.xlabel(f'y(t)')
plt.ylabel(f'y(t+{lag})')
plt.title(f'Lag Plot (lag={lag})')
plt.grid(True)
plt.show()
# Function to calculate descriptive statistics of the given data
def calculate_descriptive_statistics(data):
mean = np.mean(data)
std_dev = np.std(data)
cv = std_dev / mean if mean != 0 else np.nan
mean_absolute_deviation = np.mean(np.abs(data - mean))
median_absolute_deviation = np.median(np.abs(data - np.median(data)))
mode_result = stats.mode(data)
if hasattr(mode_result, 'mode'):
mode = mode_result.mode
else:
mode = mode_result[0]
stats_dict = {
'Count': len(data),
'Mean': mean,
'Median': np.median(data),
'Mode': mode,
'Range': np.ptp(data),
'Skewness': stats.skew(data),
'Kurtosis': stats.kurtosis(data),
'Variance': np.var(data),
'Standard Deviation': std_dev,
'Coefficient of Variation': cv,
'IQR': stats.iqr(data),
'Semi-IQR': stats.iqr(data) / 2,
'Mean Absolute Deviation': mean_absolute_deviation,
'Median Absolute Deviation': median_absolute_deviation
}
return stats_dict
# Function to display descriptive statistics
def display_descriptive_statistics(stats_dict):
print_section_header("Descriptive Statistics")
for key, value in stats_dict.items():
if key == 'Count':
print(f"{key}: {value}")
elif key == 'Coefficient of Variation':
print(f"{key}: {value:.4%}")
else:
print(f"{key}: {value:.4f}")
# Mann-Kendall test for trend detection
def mk_test(x, alpha=0.05):
n = len(x)
s = 0
for k in range(n - 1):
for j in range(k + 1, n):
s += np.sign(x[j] - x[k])
unique_x = np.unique(x)
g = len(unique_x)
if n == g:
var_s = (n * (n - 1) * (2 * n + 5)) / 18
else:
tp = np.array([np.sum(x == ux) for ux in unique_x])
var_s = (n * (n - 1) * (2 * n + 5) - np.sum(tp * (tp - 1) * (2 * tp + 5))) / 18
z = 0
if s > 0:
z = (s - 1) / np.sqrt(var_s)
elif s == 0:
z = 0
elif s < 0:
z = (s + 1) / np.sqrt(var_s)
p = 2*(1 - stats.norm.cdf(abs(z)))
h = abs(z) > stats.norm.ppf(1 - alpha / 2)
return h, p, z
# Cox-Stuart test for trend detection
def cox_stuart_test(data):
n = len(data)
m = n // 2
if n % 2 != 0:
data = data[:-1]
diff = [data[i + m] - data[i] for i in range(m)]
pos_diff = sum(d > 0 for d in diff)
neg_diff = sum(d < 0 for d in diff)
result = binomtest(pos_diff, pos_diff + neg_diff, alternative='two-sided')
p_value = result.pvalue
return p_value
# Augmented Dickey-Fuller (ADF) test for stationarity
def adf_test(data):
result = adfuller(data)
if isinstance(result, (tuple, list)):
p_value = result[1]
else:
p_value = result
return p_value
# Class for Holt-Winters Exponential Smoothing
class HoltWintersExponentialSmoothing:
def __init__(self, alpha, beta, gamma, season_length):
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.season_length = season_length
self.level = None
self.trend = None
self.season = []
self.residuals = []
self.fitted_values = []
def fit(self, data):
if len(data) < 2 * self.season_length:
winsound.Beep(1000, 500)
print(WARNING_FG + "Need at least two full season lengths of data to initialize.")
return
self.level = np.mean(data[:self.season_length])
self.trend = (np.mean(data[self.season_length:2*self.season_length]) -
np.mean(data[:self.season_length])) / self.season_length
self.season = [data[i] - self.level for i in range(self.season_length)]
self.fitted_values = []
self.residuals = []
for i in range(len(data)):
if i == 0:
fitted_value = self.level + self.trend + self.season[i % self.season_length]
else:
last_level = self.level
self.level = self.alpha * (data[i] - self.season[i % self.season_length]) + \
(1 - self.alpha) * (self.level + self.trend)
self.trend = self.beta * (self.level - last_level) + (1 - self.beta) * self.trend
self.season[i % self.season_length] = self.gamma * (data[i] - self.level) + \
(1 - self.gamma) * self.season[i % self.season_length]
fitted_value = self.level + self.trend + self.season[i % self.season_length]
self.fitted_values.append(fitted_value)
self.residuals.append(data[i] - fitted_value)
return self.fitted_values
def forecast(self, periods):
forecasts = []
for t in range(1, periods + 1):
forecasts.append(self.level + t * self.trend + self.season[t % self.season_length])
mse = np.mean(np.array(self.residuals) ** 2)
pred_intervals = [(f - 1.96 * np.sqrt(mse), f + 1.96 * np.sqrt(mse)) for f in forecasts]
return forecasts, pred_intervals
def calculate_statistics(self, data):
errors = [d - f for d, f in zip(data, self.fitted_values)]
mse = sum(e ** 2 for e in errors) / len(errors)
mae = sum(abs(e) for e in errors) / len(errors)
rmse = mse ** 0.5
non_zero_data = [(d, e) for d, e in zip(data, errors) if d != 0]
if non_zero_data:
mape = sum(abs(e / d) for d, e in non_zero_data) / len(non_zero_data) * 100
else:
mape = float('inf')
return mse, mae, rmse, mape
# Perform residual analysis
def perform_residual_analysis(self):
perform_residual_analysis(self.residuals)
def check_residual_normality(self):
try:
_, shapiro_p_value = stats.shapiro(self.residuals)
_, ks_p_value = stats.kstest(self.residuals, 'norm', args=(np.mean(self.residuals), np.std(self.residuals)))
return shapiro_p_value, ks_p_value
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error checking residual normality: {e}")
return None, None
def check_heteroscedasticity(self):
if len(self.residuals) != len(self.fitted_values):
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error: Mismatch in the number of residuals ({len(self.residuals)}) "
f"and fitted values ({len(self.fitted_values)}).")
return
try:
bp_test = breusch_pagan_test(self.residuals, self.fitted_values)
print(f"\n4. **Breusch-Pagan Test**")
print(f" - **Purpose:** Tests for heteroscedasticity (changing variance) in residuals.")
print(f" - **p-value:** {bp_test:.4f}")
if bp_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(Breusch-Pagan test).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(Breusch-Pagan test).")
white_test = white_test_heteroscedasticity(self.residuals, self.fitted_values)
print(f"\n5. **White's Test**")
print(f" - **Purpose:** Another test for heteroscedasticity in residuals.")
print(f" - **p-value:** {white_test:.4f}")
if white_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic (White's test).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(White's test).")
spearman_p_value = heteroscedasticity_test(self.residuals, self.fitted_values)
print(f"\n6. **Spearman's Rank Correlation Test**")
print(f" - **Purpose:** Tests for heteroscedasticity using rank correlation.")
print(f" - **p-value:** {spearman_p_value:.4f}")
if spearman_p_value < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(Spearman's rank correlation).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(Spearman's rank correlation).")
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error during heteroscedasticity test: {e}")
def plot_residuals(self):
plot_residuals(self.residuals)
# Plot Autocorrelation Function (ACF) of residuals
def plot_residual_acf(self):
plot_residual_acf(self.residuals)
def plot_residual_pacf(self):
plot_residual_pacf(self.residuals)
# Class for Holt Exponential Smoothing
class HoltExponentialSmoothing:
def __init__(self, alpha, beta):
self.alpha = alpha
self.beta = beta
self.level = None
self.trend = None
self.residuals = []
self.fitted_values = []
# Fit the model to the data
def fit(self, data):
if len(data) < 2:
winsound.Beep(1000, 500)
print(WARNING_FG + "Need at least two data points to initialize.")
return
# Initialize the level and trend
self.level = np.mean(data[:4])
self.trend = np.mean(np.diff(data[:4]))
self.fitted_values = []
self.residuals = []
for i in range(len(data)):
if i == 0:
fitted_value = self.level
else:
last_level = self.level
self.level = self.alpha * data[i] + (1 - self.alpha) * (self.level + self.trend)
self.trend = self.beta * (self.level - last_level) + (1 - self.beta) * self.trend
fitted_value = self.level
self.fitted_values.append(fitted_value)
self.residuals.append(data[i] - fitted_value)
self.fitted_values.pop(0)
self.residuals.pop(0)
return self.fitted_values
# Forecast future values
def forecast(self, periods):
forecasts = [self.level + t * self.trend for t in range(1, periods + 1)]
mse = np.mean(np.array(self.residuals) ** 2)
pred_intervals = []
for t in range(1, periods + 1):
interval_range = 1.96 * np.sqrt(mse * (1 + t * self.alpha + (t ** 2) * self.beta))
forecast_mean = forecasts[t - 1]
pred_intervals.append((forecast_mean - interval_range, forecast_mean + interval_range))
return forecasts, pred_intervals
# Calculate error statistics
def calculate_statistics(self, data):
errors = [d - f for d, f in zip(data[1:], self.fitted_values)]
mse = sum(e ** 2 for e in errors) / len(errors)
mae = sum(abs(e) for e in errors) / len(errors)
rmse = mse ** 0.5
non_zero_data = [(d, e) for d, e in zip(data[1:], errors) if d != 0]
if non_zero_data:
mape = sum(abs(e / d) for d, e in non_zero_data) / len(non_zero_data) * 100
else:
mape = float('inf')
return mse, mae, rmse, mape
# Perform residual analysis
def perform_residual_analysis(self):
perform_residual_analysis(self.residuals)
# Check normality of residuals
def check_residual_normality(self):
try:
_, shapiro_p_value = stats.shapiro(self.residuals)
_, ks_p_value = stats.kstest(self.residuals, 'norm', args=(np.mean(self.residuals), np.std(self.residuals)))
return shapiro_p_value, ks_p_value
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error checking residual normality: {e}")
return None, None
# Check for heteroscedasticity
def check_heteroscedasticity(self):
if len(self.residuals) != len(self.fitted_values):
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error: Mismatch in the number of residuals ({len(self.residuals)}) "
f"and fitted values ({len(self.fitted_values)}).")
return
try:
bp_test = breusch_pagan_test(self.residuals, self.fitted_values)
print(f"\n4. **Breusch-Pagan Test**")
print(f" - **Purpose:** Tests for heteroscedasticity (changing variance) in residuals.")
print(f" - **p-value:** {bp_test:.4f}")
if bp_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(Breusch-Pagan test).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(Breusch-Pagan test).")
white_test = white_test_heteroscedasticity(self.residuals, self.fitted_values)
print(f"\n5. **White's Test**")
print(f" - **Purpose:** Another test for heteroscedasticity in residuals.")
print(f" - **p-value:** {white_test:.4f}")
if white_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic (White's test).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(White's test).")
spearman_p_value = heteroscedasticity_test(self.residuals, self.fitted_values)
print(f"\n6. **Spearman's Rank Correlation Test**")
print(f" - **Purpose:** Tests for heteroscedasticity using rank correlation.")
print(f" - **p-value:** {spearman_p_value:.4f}")
if spearman_p_value < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(Spearman's rank correlation).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(Spearman's rank correlation).")
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error during heteroscedasticity test: {e}")
# Plot residuals over time
def plot_residuals(self):
plot_residuals(self.residuals)
# Plot Autocorrelation Function (ACF) of residuals
def plot_residual_acf(self):
plot_residual_acf(self.residuals)
def plot_residual_pacf(self):
plot_residual_pacf(self.residuals)
# Class for Simple Exponential Smoothing
class SimpleExponentialSmoothing:
def __init__(self, alpha):
self.alpha = alpha
self.level = None
self.residuals = []
self.fitted_values = []
# Fit the model to the data
def fit(self, data):
if len(data) < 2:
winsound.Beep(1000, 500)
print(WARNING_FG + "Need at least two data points to initialize.")
return
self.level = data[0]
self.fitted_values = [self.level]
for i in range(1, len(data)):
self.level = self.alpha * data[i] + (1 - self.alpha) * self.level
self.fitted_values.append(self.level)
self.residuals.append(data[i] - self.level)
return self.fitted_values
# Forecast future values
def forecast(self, periods):
forecasts = [self.level] * periods
mse = np.mean(np.array(self.residuals) ** 2)
pred_intervals = [(f - 1.96 * np.sqrt(mse), f + 1.96 * np.sqrt(mse)) for f in forecasts]
return forecasts, pred_intervals
# Calculate error statistics
def calculate_statistics(self, data):
errors = [d - f for d, f in zip(data, self.fitted_values)]
mse = sum(e ** 2 for e in errors) / len(errors)
mae = sum(abs(e) for e in errors) / len(errors)
rmse = mse ** 0.5
non_zero_data = [(d, e) for d, e in zip(data, errors) if d != 0]
if non_zero_data:
mape = sum(abs(e / d) for d, e in non_zero_data) / len(non_zero_data) * 100
else:
mape = float('inf')
return mse, mae, rmse, mape
# Perform residual analysis
def perform_residual_analysis(self):
perform_residual_analysis(self.residuals)
# Check normality of residuals
def check_residual_normality(self):
try:
_, shapiro_p_value = stats.shapiro(self.residuals)
_, ks_p_value = stats.kstest(self.residuals, 'norm', args=(np.mean(self.residuals), np.std(self.residuals)))
return shapiro_p_value, ks_p_value
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error checking residual normality: {e}")
return None, None
# Check for heteroscedasticity
def check_heteroscedasticity(self):
if len(self.residuals) != len(self.fitted_values):
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error: Mismatch in the number of residuals ({len(self.residuals)}) "
f"and fitted values ({len(self.fitted_values)}).")
return
try:
bp_test = breusch_pagan_test(self.residuals, self.fitted_values)
print(f"\n4. **Breusch-Pagan Test**")
print(f" - **Purpose:** Tests for heteroscedasticity (changing variance) in residuals.")
print(f" - **p-value:** {bp_test:.4f}")
if bp_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(Breusch-Pagan test).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(Breusch-Pagan test).")
white_test = white_test_heteroscedasticity(self.residuals, self.fitted_values)
print(f"\n5. **White's Test**")
print(f" - **Purpose:** Another test for heteroscedasticity in residuals.")
print(f" - **p-value:** {white_test:.4f}")
if white_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(White's test).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals "
"(White's test).")
spearman_p_value = heteroscedasticity_test(self.residuals, self.fitted_values)
print(f"\n6. **Spearman's Rank Correlation Test**")
print(f" - **Purpose:** Tests for heteroscedasticity using rank correlation.")
print(f" - **p-value:** {spearman_p_value:.4f}")
if spearman_p_value < 0.05:
print(WARNING_FG + " - **Interpretation:** Warning: Residuals may be heteroscedastic "
"(Spearman's rank correlation).")
else:
print(" - **Interpretation:** No significant heteroscedasticity detected in residuals"
" (Spearman's rank correlation).")
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error during heteroscedasticity test: {e}")
# Plot residuals over time
def plot_residuals(self):
plot_residuals(self.residuals)
# Plot Autocorrelation Function (ACF) of residuals
def plot_residual_acf(self):
plot_residual_acf(self.residuals)
# Plot Partial Autocorrelation Function (PACF) of residuals
def plot_residual_pacf(self):
plot_residual_pacf(self.residuals)
class CustomARIMA:
def __init__(self, seasonal_period=None):
self.model = None
self.results = None
self.residuals = []
self.fitted_values = []
self.order = None
self.seasonal_order = None
self.seasonal_period = seasonal_period
self.auto_model = None
def fit(self, data):
# Use pmdarima's auto_arima to find the best ARIMA order
if self.seasonal_period:
auto_model = auto_arima(data, seasonal=True, m=self.seasonal_period,
trace=True, error_action='ignore', suppress_warnings=True)
self.order = auto_model.order
self.seasonal_order = auto_model.seasonal_order
self.model = arima_model.ARIMA(data, order=self.order, seasonal_order=self.seasonal_order)
else:
auto_model = auto_arima(data, seasonal=False, trace=True,
error_action='ignore', suppress_warnings=True)
self.order = auto_model.order
self.model = arima_model.ARIMA(data, order=self.order)
self.results = self.model.fit()
self.fitted_values = self.results.fittedvalues
self.residuals = self.results.resid
if self.seasonal_order:
print(INFO_FG + f"Auto ARIMA selected a seasonal ARIMA{self.order}{self.seasonal_order} model.")
else:
print(INFO_FG + f"Auto ARIMA selected a non-seasonal ARIMA{self.order} model.")
print(f"AIC of the selected model: {self.results.aic:.2f}")
return self.fitted_values
def forecast(self, periods):
forecast_result = self.results.get_forecast(steps=periods)
forecasts = forecast_result.predicted_mean
conf_int = forecast_result.conf_int()
if isinstance(conf_int, pd.DataFrame):
pred_intervals = list(zip(conf_int.iloc[:, 0], conf_int.iloc[:, 1]))
else: # numpy array
pred_intervals = list(zip(conf_int[:, 0], conf_int[:, 1]))
return forecasts, pred_intervals
def calculate_statistics(self, data):
errors = np.array(self.residuals)
mse = np.mean(errors ** 2)
mae = np.mean(np.abs(errors))
rmse = np.sqrt(mse)
data_np = np.array(data)
mape = np.mean(np.abs(errors / data_np)) * 100 if np.all(data_np != 0) else float('inf')
return mse, mae, rmse, mape
def perform_residual_analysis(self):
perform_residual_analysis(self.residuals)
def check_residual_normality(self):
try:
_, shapiro_p_value = stats.shapiro(self.residuals)
_, ks_p_value = stats.kstest(self.residuals, 'norm', args=(np.mean(self.residuals), np.std(self.residuals)))
return shapiro_p_value, ks_p_value
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error checking residual normality: {e}")
return None, None
def check_heteroscedasticity(self):
if len(self.residuals) != len(self.fitted_values):
print(WARNING_FG + f"Error: Mismatch in the number of residuals ({len(self.residuals)}) "
f"and fitted values ({len(self.fitted_values)})." + Style.RESET_ALL)
return
try:
bp_test = breusch_pagan_test(self.residuals, self.fitted_values)
white_test = white_test_heteroscedasticity(self.residuals, self.fitted_values)
spearman_p_value = heteroscedasticity_test(self.residuals, self.fitted_values)
print(f"\n4. **Breusch-Pagan Test**")
print(f" - **Purpose:** Tests for heteroscedasticity (changing variance) in residuals.")
print(f" - **p-value:** {bp_test:.4f}")
if bp_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Reject the null hypothesis. "
"There is evidence to suggest the residuals are heteroscedastic." + Style.RESET_ALL)
else:
print(" - **Interpretation:** Fail to reject the null hypothesis. There is not enough evidence "
"to conclude the residuals are heteroscedastic.")
print(f"\n5. **White's Test**")
print(f" - **Purpose:** Another test for heteroscedasticity in residuals.")
print(f" - **p-value:** {white_test:.4f}")
if white_test < 0.05:
print(WARNING_FG + " - **Interpretation:** Reject the null hypothesis. "
"There is evidence to suggest the residuals are heteroscedastic." + Style.RESET_ALL)
else:
print(" - **Interpretation:** Fail to reject the null hypothesis. There is not enough evidence "
"to conclude the residuals are heteroscedastic.")
print(f"\n6. **Spearman's Rank Correlation Test**")
print(f" - **Purpose:** Tests for heteroscedasticity using rank correlation.")
print(f" - **p-value:** {spearman_p_value:.4f}")
if spearman_p_value < 0.05:
print(WARNING_FG + " - **Interpretation:** Reject the null hypothesis. "
"There is evidence to suggest the residuals are heteroscedastic." + Style.RESET_ALL)
else:
print(" - **Interpretation:** Fail to reject the null hypothesis. There is not enough evidence "
"to conclude the residuals are heteroscedastic.")
except Exception as e:
winsound.Beep(1000, 500)
print(WARNING_FG + f"Error during heteroscedasticity test: {e}")
return None, None, None
def plot_residuals(self):
plot_residuals(self.residuals)
def plot_residual_acf(self):
plot_residual_acf(self.residuals)
def plot_residual_pacf(self):
plot_residual_pacf(self.residuals)
# Plot the actual data, fitted values, forecasts, and prediction intervals
def plot_results(data, fitted_values, forecasts, pred_intervals, exclude_initial_fitted=1):
plt.figure(figsize=(12, 6))
plt.plot(range(len(data)), data, label='Actual Data', marker='o', linestyle='-', color='b')
plt.plot(range(exclude_initial_fitted + 1, len(fitted_values) + 1), fitted_values[exclude_initial_fitted:],
label='Fitted Values', linestyle='--', color='g')
forecast_range = range(len(data), len(data) + len(forecasts))
plt.plot(forecast_range, forecasts, label='Forecasts', linestyle=':', color='r')
lower_bounds = [pi[0] for pi in pred_intervals]
upper_bounds = [pi[1] for pi in pred_intervals]
plt.fill_between(forecast_range, lower_bounds, upper_bounds, color='gray', alpha=0.3, label='Prediction Interval')
plt.xlabel('Time Period', fontsize=12)
plt.ylabel('Value', fontsize=12)
plt.title('Exponential Smoothing: Data, Fitted Values, and Forecasts', fontsize=14)
plt.legend()
plt.grid(True)
plt.show()
# Perform the Ljung-Box test for autocorrelation in residuals
def ljung_box_test(residuals, lags=None):
if lags is None:
lags = min(10, len(residuals) // 2)
result = acorr_ljungbox(residuals, lags=[lags])
return result['lb_pvalue'].iloc[0]
# Test for heteroscedasticity in residuals using Spearman's rank correlation
def heteroscedasticity_test(residuals, fitted_values):