statstudio 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from scipy import stats
|
|
7
|
+
from statsmodels.tsa.arima.model import ARIMA
|
|
8
|
+
from statsmodels.tsa.holtwinters import ExponentialSmoothing
|
|
9
|
+
from statsmodels.tsa.stattools import acf, adfuller, kpss, pacf
|
|
10
|
+
|
|
11
|
+
from statstudio.stats.results import AnalysisResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _series(df: pd.DataFrame, column: str) -> pd.Series:
|
|
15
|
+
if column not in df.columns:
|
|
16
|
+
raise KeyError(column)
|
|
17
|
+
series = pd.to_numeric(df[column], errors="coerce")
|
|
18
|
+
if isinstance(df.index, pd.DatetimeIndex):
|
|
19
|
+
series.index = df.index
|
|
20
|
+
else:
|
|
21
|
+
series.index = pd.RangeIndex(len(series), name="Observation")
|
|
22
|
+
return series.dropna()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _x_values(series: pd.Series) -> list:
|
|
26
|
+
return [str(v) if isinstance(v, (pd.Timestamp, np.datetime64)) else v for v in series.index]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def time_series_summary(df: pd.DataFrame, column: str, period: int | None = None) -> AnalysisResult:
|
|
30
|
+
series = _series(df, column)
|
|
31
|
+
if len(series) < 2:
|
|
32
|
+
raise ValueError("At least two observations are required.")
|
|
33
|
+
differences = series.diff().dropna()
|
|
34
|
+
table = pd.DataFrame(
|
|
35
|
+
[
|
|
36
|
+
{
|
|
37
|
+
"Column": column,
|
|
38
|
+
"N": len(series),
|
|
39
|
+
"Start": str(series.index[0]),
|
|
40
|
+
"End": str(series.index[-1]),
|
|
41
|
+
"Mean": float(series.mean()),
|
|
42
|
+
"Std Dev": float(series.std()),
|
|
43
|
+
"Min": float(series.min()),
|
|
44
|
+
"Max": float(series.max()),
|
|
45
|
+
"First Difference Std Dev": float(differences.std()) if len(differences) else np.nan,
|
|
46
|
+
"Period": period,
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
)
|
|
50
|
+
result = AnalysisResult(title=f"Time Series Summary: {column}", analysis_type="ts_summary", params={"column": column, "period": period})
|
|
51
|
+
result.add_table("Summary", table)
|
|
52
|
+
line_frame = pd.DataFrame({"Index": _x_values(series), "Value": series.to_numpy()})
|
|
53
|
+
result.add_plot("line", {"x": "Index", "y": "Value"}, title=f"Time Series: {column}", data=line_frame)
|
|
54
|
+
result.summary = f"{len(series)} observations from {series.index[0]} to {series.index[-1]}."
|
|
55
|
+
return result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def acf_pacf(df: pd.DataFrame, column: str, lags: int = 20) -> AnalysisResult:
|
|
59
|
+
series = _series(df, column)
|
|
60
|
+
if len(series) < 3:
|
|
61
|
+
raise ValueError("At least three observations are required for ACF and PACF.")
|
|
62
|
+
lags = max(1, min(lags, len(series) - 1))
|
|
63
|
+
acf_values = acf(series, nlags=lags, fft=False)
|
|
64
|
+
pacf_values = pacf(series, nlags=lags, method="ywm")
|
|
65
|
+
acf_frame = pd.DataFrame(
|
|
66
|
+
{
|
|
67
|
+
"Lag": np.arange(len(acf_values)),
|
|
68
|
+
"ACF": acf_values,
|
|
69
|
+
"PACF": pacf_values[: len(acf_values)],
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
result = AnalysisResult(title=f"ACF and PACF: {column}", analysis_type="acf_pacf", params={"column": column, "lags": lags})
|
|
73
|
+
result.add_table("Autocorrelations", acf_frame)
|
|
74
|
+
result.add_plot("acf_pacf", {"lags": list(range(len(acf_values))), "acf": acf_values.tolist(), "pacf": pacf_values[: len(acf_values)].tolist()}, title=f"ACF and PACF: {column}")
|
|
75
|
+
result.summary = f"Computed {lags} lags for {len(series)} observations."
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def stationarity_tests(df: pd.DataFrame, column: str) -> AnalysisResult:
|
|
80
|
+
series = _series(df, column)
|
|
81
|
+
rows = []
|
|
82
|
+
try:
|
|
83
|
+
adf_result = adfuller(series, autolag="AIC")
|
|
84
|
+
rows.append(
|
|
85
|
+
{
|
|
86
|
+
"Test": "Augmented Dickey-Fuller",
|
|
87
|
+
"Statistic": adf_result[0],
|
|
88
|
+
"p-value": adf_result[1],
|
|
89
|
+
"Lags": adf_result[2],
|
|
90
|
+
"N": adf_result[3],
|
|
91
|
+
"Conclusion": "Stationary" if adf_result[1] < 0.05 else "Non-stationary",
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
rows.append({"Test": "Augmented Dickey-Fuller", "Statistic": np.nan, "p-value": np.nan, "Conclusion": str(exc)})
|
|
96
|
+
try:
|
|
97
|
+
kpss_result = kpss(series, regression="c", nlags="auto")
|
|
98
|
+
rows.append(
|
|
99
|
+
{
|
|
100
|
+
"Test": "KPSS",
|
|
101
|
+
"Statistic": kpss_result[0],
|
|
102
|
+
"p-value": kpss_result[1],
|
|
103
|
+
"Lags": kpss_result[2],
|
|
104
|
+
"N": len(series),
|
|
105
|
+
"Conclusion": "Non-stationary" if kpss_result[1] < 0.05 else "Stationary",
|
|
106
|
+
}
|
|
107
|
+
)
|
|
108
|
+
except Exception as exc:
|
|
109
|
+
rows.append({"Test": "KPSS", "Statistic": np.nan, "p-value": np.nan, "Conclusion": str(exc)})
|
|
110
|
+
result = AnalysisResult(title=f"Stationarity Tests: {column}", analysis_type="stationarity", params={"column": column})
|
|
111
|
+
result.add_table("Tests", pd.DataFrame(rows))
|
|
112
|
+
result.summary = "ADF tests the null of a unit root; KPSS tests the null of stationarity."
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def decomposition(df: pd.DataFrame, column: str, period: int, model: str = "additive") -> AnalysisResult:
|
|
117
|
+
series = _series(df, column)
|
|
118
|
+
if period < 2:
|
|
119
|
+
raise ValueError("Period must be at least 2.")
|
|
120
|
+
if len(series) < 2 * period:
|
|
121
|
+
raise ValueError("At least two full periods are required.")
|
|
122
|
+
values = series.to_numpy(dtype=float)
|
|
123
|
+
count = len(values)
|
|
124
|
+
if period % 2 == 0:
|
|
125
|
+
weights = np.r_[0.5, np.ones(period - 1), 0.5] / period
|
|
126
|
+
else:
|
|
127
|
+
weights = np.ones(period) / period
|
|
128
|
+
trend_values = np.convolve(values, weights, mode="valid")
|
|
129
|
+
pad = (len(weights) - 1) // 2
|
|
130
|
+
trend = np.full(count, np.nan)
|
|
131
|
+
trend[pad:pad + len(trend_values)] = trend_values
|
|
132
|
+
|
|
133
|
+
if model == "multiplicative":
|
|
134
|
+
if np.nanmin(trend) <= 0:
|
|
135
|
+
raise ValueError("Multiplicative decomposition requires a positive trend.")
|
|
136
|
+
detrended = values / trend
|
|
137
|
+
else:
|
|
138
|
+
detrended = values - trend
|
|
139
|
+
|
|
140
|
+
seasonal_values = np.full(period, np.nan)
|
|
141
|
+
for phase in range(period):
|
|
142
|
+
phase_values = detrended[phase::period]
|
|
143
|
+
finite = phase_values[np.isfinite(phase_values)]
|
|
144
|
+
if len(finite):
|
|
145
|
+
seasonal_values[phase] = float(np.mean(finite))
|
|
146
|
+
if model == "multiplicative":
|
|
147
|
+
finite_seasonal = seasonal_values[np.isfinite(seasonal_values)]
|
|
148
|
+
if len(finite_seasonal) and float(np.mean(finite_seasonal)) != 0:
|
|
149
|
+
seasonal_values = seasonal_values / float(np.mean(finite_seasonal))
|
|
150
|
+
else:
|
|
151
|
+
finite_seasonal = seasonal_values[np.isfinite(seasonal_values)]
|
|
152
|
+
if len(finite_seasonal):
|
|
153
|
+
seasonal_values = seasonal_values - float(np.mean(finite_seasonal))
|
|
154
|
+
seasonal = seasonal_values[np.arange(count) % period]
|
|
155
|
+
|
|
156
|
+
if model == "multiplicative":
|
|
157
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
158
|
+
residual = values / (trend * seasonal)
|
|
159
|
+
else:
|
|
160
|
+
residual = values - trend - seasonal
|
|
161
|
+
|
|
162
|
+
table = pd.DataFrame(
|
|
163
|
+
{
|
|
164
|
+
"Index": _x_values(series),
|
|
165
|
+
"Observed": values,
|
|
166
|
+
"Trend": trend,
|
|
167
|
+
"Seasonal": seasonal,
|
|
168
|
+
"Residual": residual,
|
|
169
|
+
}
|
|
170
|
+
)
|
|
171
|
+
result = AnalysisResult(title=f"Seasonal Decomposition: {column}", analysis_type="decomposition", params={"column": column, "period": period, "model": model})
|
|
172
|
+
result.add_table("Components", table.head(200))
|
|
173
|
+
result.add_plot("decomposition", {}, title=f"Seasonal Decomposition: {column}", data=table)
|
|
174
|
+
result.summary = f"{model.title()} decomposition with period {period}."
|
|
175
|
+
return result
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def arima_forecast(
|
|
179
|
+
df: pd.DataFrame,
|
|
180
|
+
column: str,
|
|
181
|
+
order: tuple[int, int, int] = (1, 1, 0),
|
|
182
|
+
seasonal_order: tuple[int, int, int, int] | None = None,
|
|
183
|
+
steps: int = 12,
|
|
184
|
+
) -> AnalysisResult:
|
|
185
|
+
series = _series(df, column)
|
|
186
|
+
if len(series) < 10:
|
|
187
|
+
raise ValueError("At least ten observations are recommended for ARIMA.")
|
|
188
|
+
try:
|
|
189
|
+
model = ARIMA(series, order=order, seasonal_order=seasonal_order or (0, 0, 0, 0))
|
|
190
|
+
fit = model.fit()
|
|
191
|
+
except Exception as exc:
|
|
192
|
+
raise ValueError(f"ARIMA fit failed: {exc}") from exc
|
|
193
|
+
forecast = fit.get_forecast(steps=steps)
|
|
194
|
+
mean = forecast.predicted_mean
|
|
195
|
+
conf = forecast.conf_int()
|
|
196
|
+
if isinstance(series.index, pd.DatetimeIndex) and len(series) > 1:
|
|
197
|
+
freq = pd.infer_freq(series.index) or "D"
|
|
198
|
+
future_index = pd.date_range(series.index[-1], periods=steps + 1, freq=freq)[1:]
|
|
199
|
+
else:
|
|
200
|
+
start = int(series.index[-1]) if not isinstance(series.index[-1], pd.Timestamp) else len(series)
|
|
201
|
+
future_index = pd.RangeIndex(start + 1, start + 1 + steps, name="Observation")
|
|
202
|
+
forecast_table = pd.DataFrame(
|
|
203
|
+
{
|
|
204
|
+
"Forecast": mean.to_numpy(),
|
|
205
|
+
"CI Low": conf.iloc[:, 0].to_numpy(),
|
|
206
|
+
"CI High": conf.iloc[:, 1].to_numpy(),
|
|
207
|
+
},
|
|
208
|
+
index=future_index,
|
|
209
|
+
).reset_index().rename(columns={"index": "Index"})
|
|
210
|
+
actual_frame = pd.DataFrame({"Index": _x_values(series), "Actual": series.to_numpy()})
|
|
211
|
+
plot_frame = pd.concat(
|
|
212
|
+
[
|
|
213
|
+
actual_frame,
|
|
214
|
+
pd.DataFrame(
|
|
215
|
+
{
|
|
216
|
+
"Index": [str(v) if isinstance(v, pd.Timestamp) else v for v in future_index],
|
|
217
|
+
"Forecast": mean.to_numpy(),
|
|
218
|
+
"CI Low": conf.iloc[:, 0].to_numpy(),
|
|
219
|
+
"CI High": conf.iloc[:, 1].to_numpy(),
|
|
220
|
+
}
|
|
221
|
+
),
|
|
222
|
+
],
|
|
223
|
+
ignore_index=True,
|
|
224
|
+
)
|
|
225
|
+
result = AnalysisResult(
|
|
226
|
+
title=f"ARIMA Forecast: {column}",
|
|
227
|
+
analysis_type="arima",
|
|
228
|
+
params={"column": column, "order": list(order), "seasonal_order": list(seasonal_order or (0, 0, 0, 0)), "steps": steps},
|
|
229
|
+
)
|
|
230
|
+
result.add_table("Forecast", forecast_table)
|
|
231
|
+
result.add_table(
|
|
232
|
+
"Model Metrics",
|
|
233
|
+
pd.DataFrame(
|
|
234
|
+
[
|
|
235
|
+
("Order", str(order)),
|
|
236
|
+
("Seasonal order", str(seasonal_order or (0, 0, 0, 0))),
|
|
237
|
+
("AIC", fit.aic),
|
|
238
|
+
("BIC", fit.bic),
|
|
239
|
+
("N", len(series)),
|
|
240
|
+
],
|
|
241
|
+
columns=["Metric", "Value"],
|
|
242
|
+
),
|
|
243
|
+
)
|
|
244
|
+
result.add_plot("forecast", {"x": "Index", "actual": "Actual", "forecast": "Forecast", "lower": "CI Low", "upper": "CI High"}, title=f"ARIMA Forecast: {column}", data=plot_frame)
|
|
245
|
+
result.summary = f"ARIMA{order} forecast for {steps} periods. AIC = {fit.aic:.4g}."
|
|
246
|
+
return result
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def exponential_smoothing(
|
|
250
|
+
df: pd.DataFrame,
|
|
251
|
+
column: str,
|
|
252
|
+
trend: str | None = "add",
|
|
253
|
+
seasonal: str | None = None,
|
|
254
|
+
period: int | None = None,
|
|
255
|
+
steps: int = 12,
|
|
256
|
+
) -> AnalysisResult:
|
|
257
|
+
series = _series(df, column)
|
|
258
|
+
try:
|
|
259
|
+
model = ExponentialSmoothing(
|
|
260
|
+
series,
|
|
261
|
+
trend=trend,
|
|
262
|
+
seasonal=seasonal,
|
|
263
|
+
seasonal_periods=period if seasonal else None,
|
|
264
|
+
initialization_method="estimated",
|
|
265
|
+
)
|
|
266
|
+
fit = model.fit()
|
|
267
|
+
forecast = fit.forecast(steps)
|
|
268
|
+
except Exception as exc:
|
|
269
|
+
raise ValueError(f"Exponential smoothing failed: {exc}") from exc
|
|
270
|
+
frame = pd.DataFrame({"Index": [str(i) for i in forecast.index], "Forecast": forecast.to_numpy()})
|
|
271
|
+
result = AnalysisResult(
|
|
272
|
+
title=f"Exponential Smoothing: {column}",
|
|
273
|
+
analysis_type="exponential_smoothing",
|
|
274
|
+
params={"column": column, "trend": trend, "seasonal": seasonal, "period": period, "steps": steps},
|
|
275
|
+
)
|
|
276
|
+
result.add_table("Forecast", frame)
|
|
277
|
+
result.add_table("Model Metrics", pd.DataFrame([("AIC", fit.aic), ("BIC", fit.bic), ("N", len(series))], columns=["Metric", "Value"]))
|
|
278
|
+
result.summary = f"Forecast for {steps} periods; AIC = {fit.aic:.4g}."
|
|
279
|
+
return result
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def stl_decomposition(
|
|
285
|
+
df: pd.DataFrame,
|
|
286
|
+
column: str,
|
|
287
|
+
period: int,
|
|
288
|
+
seasonal: int = 7,
|
|
289
|
+
robust: bool = False,
|
|
290
|
+
) -> AnalysisResult:
|
|
291
|
+
from statsmodels.tsa.seasonal import STL
|
|
292
|
+
|
|
293
|
+
series = _series(df, column)
|
|
294
|
+
if period < 2:
|
|
295
|
+
raise ValueError("Period must be at least 2.")
|
|
296
|
+
if len(series) < 2 * period:
|
|
297
|
+
raise ValueError("At least two full periods are required.")
|
|
298
|
+
seasonal = max(3, int(seasonal))
|
|
299
|
+
if seasonal % 2 == 0:
|
|
300
|
+
seasonal += 1
|
|
301
|
+
try:
|
|
302
|
+
outcome = STL(series, period=period, seasonal=seasonal, robust=robust).fit()
|
|
303
|
+
except Exception as exc:
|
|
304
|
+
raise ValueError(f"STL decomposition failed: {exc}") from exc
|
|
305
|
+
table = pd.DataFrame(
|
|
306
|
+
{
|
|
307
|
+
"Index": _x_values(series),
|
|
308
|
+
"Observed": series.to_numpy(),
|
|
309
|
+
"Trend": outcome.trend.to_numpy(),
|
|
310
|
+
"Seasonal": outcome.seasonal.to_numpy(),
|
|
311
|
+
"Residual": outcome.resid.to_numpy(),
|
|
312
|
+
}
|
|
313
|
+
)
|
|
314
|
+
trend_strength = max(0.0, 1 - float(np.var(outcome.resid)) / float(np.var(outcome.trend + outcome.resid))) if np.var(outcome.trend + outcome.resid) else np.nan
|
|
315
|
+
seasonal_strength = max(0.0, 1 - float(np.var(outcome.resid)) / float(np.var(outcome.seasonal + outcome.resid))) if np.var(outcome.seasonal + outcome.resid) else np.nan
|
|
316
|
+
result = AnalysisResult(title=f"STL Decomposition: {column}", analysis_type="stl", params={"column": column, "period": period, "seasonal": seasonal, "robust": robust})
|
|
317
|
+
result.add_table("Components", table.head(500))
|
|
318
|
+
result.add_table("Strengths", pd.DataFrame([{"Trend Strength": trend_strength, "Seasonal Strength": seasonal_strength, "Remainder SD": float(np.std(outcome.resid))}]))
|
|
319
|
+
result.add_plot("decomposition", {}, title=f"STL Decomposition: {column}", data=table)
|
|
320
|
+
result.summary = f"STL decomposition with period {period}; seasonal strength {seasonal_strength:.3f}."
|
|
321
|
+
return result
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _future_index(series: pd.Series, horizon: int):
|
|
325
|
+
if isinstance(series.index, pd.DatetimeIndex) and len(series) > 1:
|
|
326
|
+
freq = pd.infer_freq(series.index) or "D"
|
|
327
|
+
return pd.date_range(series.index[-1], periods=horizon + 1, freq=freq)[1:]
|
|
328
|
+
last = series.index[-1]
|
|
329
|
+
if isinstance(last, (int, np.integer)):
|
|
330
|
+
start = int(last) + 1
|
|
331
|
+
else:
|
|
332
|
+
start = len(series) + 1
|
|
333
|
+
return pd.RangeIndex(start, start + horizon, name="Observation")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _forecast_intervals(
|
|
337
|
+
series: pd.Series,
|
|
338
|
+
method: str,
|
|
339
|
+
horizon: int,
|
|
340
|
+
period: int | None,
|
|
341
|
+
mean: pd.Series,
|
|
342
|
+
level: float | None,
|
|
343
|
+
) -> tuple[pd.Series, pd.Series]:
|
|
344
|
+
z_value = float(stats.norm.ppf(1 - (1 - (level or 95) / 100) / 2))
|
|
345
|
+
steps = np.arange(1, horizon + 1, dtype=float)
|
|
346
|
+
n = max(2, len(series))
|
|
347
|
+
sd = float(np.nanstd(np.asarray(series, dtype=float), ddof=1))
|
|
348
|
+
if method == "mean":
|
|
349
|
+
half = z_value * sd * np.sqrt(1 + 1 / n)
|
|
350
|
+
half = np.full(horizon, half)
|
|
351
|
+
elif method == "drift":
|
|
352
|
+
differences = series.diff().dropna()
|
|
353
|
+
sd = float(differences.std(ddof=1))
|
|
354
|
+
half = z_value * sd * np.sqrt(steps * (1 + steps / n))
|
|
355
|
+
elif method == "snaive":
|
|
356
|
+
period_value = max(1, int(period or 1))
|
|
357
|
+
residuals = (series - series.shift(period_value)).dropna()
|
|
358
|
+
sd = float(residuals.std(ddof=1))
|
|
359
|
+
half = z_value * sd * np.sqrt(np.floor((steps - 1) / period_value) + 1)
|
|
360
|
+
else:
|
|
361
|
+
differences = series.diff().dropna()
|
|
362
|
+
sd = float(differences.std(ddof=1))
|
|
363
|
+
half = z_value * sd * np.sqrt(steps)
|
|
364
|
+
half = np.nan_to_num(half, nan=0.0, posinf=0.0, neginf=0.0)
|
|
365
|
+
return mean - half, mean + half
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _naive_forecast(series: pd.Series, method: str, horizon: int, period: int | None):
|
|
369
|
+
values = series.to_numpy(dtype=float)
|
|
370
|
+
if method == "mean":
|
|
371
|
+
forecast = np.repeat(values.mean(), horizon)
|
|
372
|
+
elif method == "drift":
|
|
373
|
+
slope = (values[-1] - values[0]) / max(1, len(values) - 1)
|
|
374
|
+
forecast = values[-1] + slope * np.arange(1, horizon + 1)
|
|
375
|
+
elif method == "snaive":
|
|
376
|
+
period = period or 1
|
|
377
|
+
if len(values) < period:
|
|
378
|
+
raise ValueError("Seasonal naive forecasting needs at least one full period.")
|
|
379
|
+
forecast = np.array([values[-period + (i % period)] for i in range(horizon)])
|
|
380
|
+
else:
|
|
381
|
+
forecast = np.repeat(values[-1], horizon)
|
|
382
|
+
return forecast
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def forecast(
|
|
386
|
+
df: pd.DataFrame,
|
|
387
|
+
column: str,
|
|
388
|
+
method: str = "auto",
|
|
389
|
+
period: int | None = None,
|
|
390
|
+
horizon: int = 12,
|
|
391
|
+
level: float | None = 95.0,
|
|
392
|
+
order: tuple[int, int, int] = (1, 0, 0),
|
|
393
|
+
seasonal_order: tuple[int, int, int, int] | None = None,
|
|
394
|
+
manual_term: str = "none",
|
|
395
|
+
backtest: int = 0,
|
|
396
|
+
pulse: list[int] | None = None,
|
|
397
|
+
step: list[int] | None = None,
|
|
398
|
+
stl_window: int | None = None,
|
|
399
|
+
robust: bool = False,
|
|
400
|
+
) -> AnalysisResult:
|
|
401
|
+
from statsmodels.tsa.statespace.sarimax import SARIMAX
|
|
402
|
+
|
|
403
|
+
series = _series(df, column)
|
|
404
|
+
if len(series) < 8:
|
|
405
|
+
raise ValueError("At least eight observations are recommended for forecasting.")
|
|
406
|
+
method = method.lower()
|
|
407
|
+
requested_method = method
|
|
408
|
+
label = method
|
|
409
|
+
model_info: list[tuple[str, object]] = []
|
|
410
|
+
# Build intervention regressors over history (and future horizon).
|
|
411
|
+
exog = None
|
|
412
|
+
exog_future = None
|
|
413
|
+
interventions = list(pulse or []) + list(step or [])
|
|
414
|
+
if interventions:
|
|
415
|
+
total = len(series) + horizon
|
|
416
|
+
block = np.zeros((total, len(pulse or []) + len(step or [])))
|
|
417
|
+
column_index = 0
|
|
418
|
+
for position in pulse or []:
|
|
419
|
+
if 0 <= int(position) < total:
|
|
420
|
+
block[int(position), column_index] = 1.0
|
|
421
|
+
column_index += 1
|
|
422
|
+
for position in step or []:
|
|
423
|
+
if 0 <= int(position) < total:
|
|
424
|
+
block[int(position):, column_index] = 1.0
|
|
425
|
+
column_index += 1
|
|
426
|
+
exog = block[: len(series)]
|
|
427
|
+
exog_future = block[len(series):]
|
|
428
|
+
errors: list[str] = []
|
|
429
|
+
auto_ets = None
|
|
430
|
+
arima_aic = None
|
|
431
|
+
if method in {"auto", "ets"}:
|
|
432
|
+
try:
|
|
433
|
+
model = ExponentialSmoothing(series, trend="add", seasonal="add" if period and len(series) >= 2 * period else None, seasonal_periods=period if period else None, initialization_method="estimated")
|
|
434
|
+
fit = model.fit()
|
|
435
|
+
forecast_values = np.asarray(fit.forecast(horizon))
|
|
436
|
+
residual_sd = float(np.std(fit.resid))
|
|
437
|
+
mean = pd.Series(forecast_values, index=_future_index(series, horizon))
|
|
438
|
+
z_value = float(stats.norm.ppf(1 - (1 - (level or 95) / 100) / 2))
|
|
439
|
+
half = z_value * residual_sd * np.sqrt(np.arange(1, horizon + 1, dtype=float))
|
|
440
|
+
lower = mean - half
|
|
441
|
+
upper = mean + half
|
|
442
|
+
model_info.append(("Model", "ETS (additive)"))
|
|
443
|
+
model_info.append(("AIC", float(fit.aic)))
|
|
444
|
+
model_info.append(("Residual SD", residual_sd))
|
|
445
|
+
label = "ETS"
|
|
446
|
+
if method == "auto":
|
|
447
|
+
auto_ets = (float(fit.aic), mean.copy(), lower.copy(), upper.copy(), list(model_info), label)
|
|
448
|
+
method = "arima"
|
|
449
|
+
except Exception as exc:
|
|
450
|
+
errors.append(str(exc))
|
|
451
|
+
method = "arima"
|
|
452
|
+
if method in {"arima", "manual", "auto"}:
|
|
453
|
+
try:
|
|
454
|
+
model = SARIMAX(series, order=order, seasonal_order=seasonal_order or (0, 0, 0, 0), exog=exog, trend=manual_term if manual_term in {"c", "t", "ct"} else "n")
|
|
455
|
+
fit = model.fit(disp=False)
|
|
456
|
+
prediction = fit.get_forecast(steps=horizon, exog=exog_future)
|
|
457
|
+
mean = prediction.predicted_mean
|
|
458
|
+
conf = prediction.conf_int(alpha=1 - (level or 95) / 100)
|
|
459
|
+
lower = conf.iloc[:, 0]
|
|
460
|
+
upper = conf.iloc[:, 1]
|
|
461
|
+
model_info.append(("Model", f"ARIMA{order}" + (f" x {seasonal_order}" if seasonal_order else "")))
|
|
462
|
+
model_info.append(("AIC", float(fit.aic)))
|
|
463
|
+
model_info.append(("BIC", float(fit.bic)))
|
|
464
|
+
model_info.append(("Log likelihood", float(fit.llf)))
|
|
465
|
+
label = "ARIMA"
|
|
466
|
+
arima_aic = float(fit.aic)
|
|
467
|
+
if interventions:
|
|
468
|
+
names = [f"pulse[{p}]" for p in (pulse or [])] + [f"step[{s}]" for s in (step or [])]
|
|
469
|
+
coefficient_rows = []
|
|
470
|
+
param_names = list(getattr(fit.params, "index", range(len(fit.params))))
|
|
471
|
+
for name, value in zip(param_names, np.asarray(fit.params)):
|
|
472
|
+
if name in names or (isinstance(name, str) and ("x1" in name or "x2" in name)):
|
|
473
|
+
coefficient_rows.append({"Intervention": name, "Coefficient": float(value)})
|
|
474
|
+
if coefficient_rows:
|
|
475
|
+
model_info.append(("Interventions", len(coefficient_rows)))
|
|
476
|
+
fit.__dict__["_intervention_rows"] = coefficient_rows
|
|
477
|
+
except Exception as exc:
|
|
478
|
+
errors.append(str(exc))
|
|
479
|
+
mean = pd.Series(_naive_forecast(series, "naive", horizon, period), index=_future_index(series, horizon))
|
|
480
|
+
lower, upper = _forecast_intervals(series, "naive", horizon, period, mean, level)
|
|
481
|
+
model_info.append(("Model", "Naive fallback"))
|
|
482
|
+
label = "Naive"
|
|
483
|
+
if auto_ets is not None and (arima_aic is None or auto_ets[0] < arima_aic):
|
|
484
|
+
_, mean, lower, upper, model_info, label = auto_ets
|
|
485
|
+
elif method == "ets":
|
|
486
|
+
pass
|
|
487
|
+
elif method in {"mean", "drift", "naive", "snaive"}:
|
|
488
|
+
mean = pd.Series(_naive_forecast(series, method, horizon, period), index=_future_index(series, horizon))
|
|
489
|
+
lower, upper = _forecast_intervals(series, method, horizon, period, mean, level)
|
|
490
|
+
model_info.append(("Model", method.title()))
|
|
491
|
+
model_info.append(("Interval", f"Approximate normal residual intervals ({level or 95:g}%)"))
|
|
492
|
+
label = method.title()
|
|
493
|
+
elif method == "stl":
|
|
494
|
+
try:
|
|
495
|
+
from statsmodels.tsa.seasonal import STL
|
|
496
|
+
|
|
497
|
+
period_value = period or max(2, len(series) // 4)
|
|
498
|
+
outcome = STL(series, period=period_value, robust=robust).fit()
|
|
499
|
+
trend = outcome.trend
|
|
500
|
+
seasonal = outcome.seasonal
|
|
501
|
+
slope = (trend.iloc[-1] - trend.iloc[0]) / max(1, len(trend) - 1)
|
|
502
|
+
future_index = _future_index(series, horizon)
|
|
503
|
+
mean_values = []
|
|
504
|
+
for i in range(horizon):
|
|
505
|
+
mean_values.append(trend.iloc[-1] + slope * (i + 1) + seasonal.iloc[-(period_value - (i % period_value))])
|
|
506
|
+
mean = pd.Series(mean_values, index=future_index)
|
|
507
|
+
residual_sd = float(np.std(outcome.resid, ddof=1))
|
|
508
|
+
z_value = float(stats.norm.ppf(1 - (1 - (level or 95) / 100) / 2))
|
|
509
|
+
half = z_value * residual_sd * np.sqrt(np.arange(1, horizon + 1, dtype=float))
|
|
510
|
+
lower = mean - half
|
|
511
|
+
upper = mean + half
|
|
512
|
+
model_info.append(("Model", "STL + seasonal naive"))
|
|
513
|
+
model_info.append(("Interval", "Approximate residual intervals"))
|
|
514
|
+
label = "STL"
|
|
515
|
+
except Exception as exc:
|
|
516
|
+
raise ValueError(f"STL forecast failed: {exc}") from exc
|
|
517
|
+
else:
|
|
518
|
+
raise ValueError(f"Unknown forecast method: {method}")
|
|
519
|
+
|
|
520
|
+
future_index = _future_index(series, horizon)
|
|
521
|
+
mean = pd.Series(np.asarray(mean, dtype=float), index=future_index)
|
|
522
|
+
lower = pd.Series(np.asarray(lower, dtype=float), index=future_index)
|
|
523
|
+
upper = pd.Series(np.asarray(upper, dtype=float), index=future_index)
|
|
524
|
+
forecast_table = pd.DataFrame(
|
|
525
|
+
{
|
|
526
|
+
"Index": [str(v) if isinstance(v, pd.Timestamp) else v for v in future_index],
|
|
527
|
+
"Forecast": mean.to_numpy(),
|
|
528
|
+
"Lower": lower.to_numpy(),
|
|
529
|
+
"Upper": upper.to_numpy(),
|
|
530
|
+
}
|
|
531
|
+
)
|
|
532
|
+
actual_frame = pd.DataFrame({"Index": _x_values(series), "Actual": series.to_numpy()})
|
|
533
|
+
plot_frame = pd.concat(
|
|
534
|
+
[
|
|
535
|
+
actual_frame,
|
|
536
|
+
pd.DataFrame({"Index": [str(v) if isinstance(v, pd.Timestamp) else v for v in future_index], "Forecast": mean.to_numpy(), "Lower": lower.to_numpy(), "Upper": upper.to_numpy()}),
|
|
537
|
+
],
|
|
538
|
+
ignore_index=True,
|
|
539
|
+
)
|
|
540
|
+
result = AnalysisResult(
|
|
541
|
+
title=f"Forecast: {column}",
|
|
542
|
+
analysis_type="forecast",
|
|
543
|
+
params={
|
|
544
|
+
"column": column,
|
|
545
|
+
"method": requested_method,
|
|
546
|
+
"period": period,
|
|
547
|
+
"horizon": horizon,
|
|
548
|
+
"level": level,
|
|
549
|
+
"order": list(order),
|
|
550
|
+
"seasonal_order": list(seasonal_order or (0, 0, 0, 0)),
|
|
551
|
+
"manual_term": manual_term,
|
|
552
|
+
"backtest": backtest,
|
|
553
|
+
"pulse": list(pulse or []),
|
|
554
|
+
"step": list(step or []),
|
|
555
|
+
"robust": bool(robust),
|
|
556
|
+
},
|
|
557
|
+
)
|
|
558
|
+
result.add_table("Forecast", forecast_table)
|
|
559
|
+
result.add_table("Model", pd.DataFrame(model_info, columns=["Metric", "Value"]))
|
|
560
|
+
result.add_plot("forecast", {"x": "Index", "actual": "Actual", "forecast": "Forecast", "lower": "Lower", "upper": "Upper"}, title=f"Forecast: {column}", data=plot_frame)
|
|
561
|
+
summary = f"{label} forecast for {horizon} periods."
|
|
562
|
+
if backtest and backtest > 0:
|
|
563
|
+
try:
|
|
564
|
+
error_rows = _backtest(series, method, horizon, period, order, seasonal_order, int(backtest), pulse, step, manual_term)
|
|
565
|
+
if error_rows:
|
|
566
|
+
result.add_table("Backtest", pd.DataFrame(error_rows))
|
|
567
|
+
summary += f" Rolling backtest over {len(error_rows)} windows; RMSE = {pd.DataFrame(error_rows)['RMSE'].mean():.4g}."
|
|
568
|
+
except Exception:
|
|
569
|
+
pass
|
|
570
|
+
if errors and label in {"Naive", "Naive fallback"}:
|
|
571
|
+
summary += " Model fitting failed; used a naive forecast."
|
|
572
|
+
result.summary = summary
|
|
573
|
+
return result
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _backtest(
|
|
577
|
+
series: pd.Series,
|
|
578
|
+
method: str,
|
|
579
|
+
horizon: int,
|
|
580
|
+
period: int | None,
|
|
581
|
+
order,
|
|
582
|
+
seasonal_order,
|
|
583
|
+
windows: int,
|
|
584
|
+
pulse: list[int] | None = None,
|
|
585
|
+
step: list[int] | None = None,
|
|
586
|
+
manual_term: str = "none",
|
|
587
|
+
) -> list[dict[str, float]]:
|
|
588
|
+
from statsmodels.tsa.statespace.sarimax import SARIMAX
|
|
589
|
+
|
|
590
|
+
rows = []
|
|
591
|
+
total = len(series)
|
|
592
|
+
step_size = max(1, int(horizon))
|
|
593
|
+
exog = None
|
|
594
|
+
interventions = list(pulse or []) + list(step or [])
|
|
595
|
+
if interventions:
|
|
596
|
+
block = np.zeros((total, len(pulse or []) + len(step or [])))
|
|
597
|
+
column_index = 0
|
|
598
|
+
for position in pulse or []:
|
|
599
|
+
if 0 <= int(position) < total:
|
|
600
|
+
block[int(position), column_index] = 1.0
|
|
601
|
+
column_index += 1
|
|
602
|
+
for position in step or []:
|
|
603
|
+
if 0 <= int(position) < total:
|
|
604
|
+
block[int(position):, column_index] = 1.0
|
|
605
|
+
column_index += 1
|
|
606
|
+
exog = block
|
|
607
|
+
windows = max(1, min(windows, max(1, (total - 6) // step_size)))
|
|
608
|
+
for index in range(windows):
|
|
609
|
+
cutoff = total - (windows - index) * step_size
|
|
610
|
+
if cutoff < 6 or cutoff + step_size > total:
|
|
611
|
+
continue
|
|
612
|
+
train = series.iloc[:cutoff]
|
|
613
|
+
test = series.iloc[cutoff:cutoff + step_size]
|
|
614
|
+
if len(test) == 0:
|
|
615
|
+
continue
|
|
616
|
+
try:
|
|
617
|
+
if method in {"auto", "ets"}:
|
|
618
|
+
model = ExponentialSmoothing(train, trend="add", seasonal="add" if period and len(train) >= 2 * period else None, seasonal_periods=period if period else None, initialization_method="estimated").fit()
|
|
619
|
+
predicted = np.asarray(model.forecast(len(test)))
|
|
620
|
+
elif method in {"mean", "drift", "naive", "snaive"}:
|
|
621
|
+
predicted = _naive_forecast(train, method, len(test), period)
|
|
622
|
+
else:
|
|
623
|
+
train_exog = exog[:cutoff] if exog is not None else None
|
|
624
|
+
test_exog = exog[cutoff:cutoff + len(test)] if exog is not None else None
|
|
625
|
+
model = SARIMAX(
|
|
626
|
+
train,
|
|
627
|
+
order=order,
|
|
628
|
+
seasonal_order=seasonal_order or (0, 0, 0, 0),
|
|
629
|
+
exog=train_exog,
|
|
630
|
+
trend=manual_term if manual_term in {"c", "t", "ct"} else "n",
|
|
631
|
+
).fit(disp=False)
|
|
632
|
+
predicted = np.asarray(model.forecast(len(test), exog=test_exog))
|
|
633
|
+
except Exception:
|
|
634
|
+
continue
|
|
635
|
+
actual = test.to_numpy(dtype=float)
|
|
636
|
+
predicted = np.asarray(predicted, dtype=float)[: len(actual)]
|
|
637
|
+
if len(predicted) != len(actual):
|
|
638
|
+
continue
|
|
639
|
+
error = actual - predicted
|
|
640
|
+
nonzero = actual != 0
|
|
641
|
+
mape = float(np.mean(np.abs(error[nonzero] / actual[nonzero])) * 100) if np.any(nonzero) else np.nan
|
|
642
|
+
rows.append({"Window": index + 1, "Train N": len(train), "Test N": len(actual), "RMSE": float(np.sqrt(np.mean(error ** 2))), "MAE": float(np.mean(np.abs(error))), "MAPE": mape, "Bias": float(np.mean(error))})
|
|
643
|
+
return rows
|