29 lines
843 B
Python
29 lines
843 B
Python
from __future__ import annotations
|
||
|
||
import numpy as np
|
||
from statsmodels.tsa.holtwinters import ExponentialSmoothing
|
||
|
||
|
||
def forecast_next_n(y: np.ndarray, n: int) -> np.ndarray:
|
||
"""
|
||
轻量级预测:优先 Holt-Winters(对短序列也相对稳),失败则用简单移动平均。
|
||
"""
|
||
y = np.asarray(y, dtype=float)
|
||
if y.size < 3:
|
||
return np.repeat(y[-1] if y.size else 0.0, n)
|
||
|
||
try:
|
||
model = ExponentialSmoothing(
|
||
y,
|
||
trend="add",
|
||
seasonal=None,
|
||
initialization_method="estimated",
|
||
)
|
||
fit = model.fit(optimized=True)
|
||
return np.asarray(fit.forecast(n), dtype=float)
|
||
except Exception:
|
||
window = int(min(7, max(3, y.size // 2)))
|
||
avg = float(np.mean(y[-window:])) if y.size else 0.0
|
||
return np.repeat(avg, n)
|
||
|