Files
Crawl_demo/backend/app/services/forecast.py
2026-03-18 18:57:58 +08:00

29 lines
843 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)