Spaces:
Sleeping
Sleeping
Chronos Deploy commited on
Commit ·
fe4d950
0
Parent(s):
deploy: Chronos-2 order forecast dashboard
Browse files- .gitignore +8 -0
- README.md +21 -0
- app/dashboard.py +568 -0
- app/utils/__init__.py +0 -0
- app/utils/data.py +106 -0
- app/utils/forecast.py +138 -0
- requirements.txt +8 -0
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
models/
|
| 3 |
+
__pycache__/
|
| 4 |
+
*.pyc
|
| 5 |
+
*.png
|
| 6 |
+
data/
|
| 7 |
+
*.egg-info/
|
| 8 |
+
.env
|
README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Chronos-2 Order Forecast
|
| 3 |
+
emoji: 📦
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: streamlit
|
| 7 |
+
sdk_version: 1.55.0
|
| 8 |
+
app_file: app/dashboard.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Прогноз заказов · Chronos-2
|
| 13 |
+
|
| 14 |
+
Дашборд прогнозирования заказов на основе AutoGluon Chronos-2.
|
| 15 |
+
|
| 16 |
+
**Возможности:**
|
| 17 |
+
- Загрузка исторических данных (XLSX)
|
| 18 |
+
- Прогноз с учётом погоды Москвы (Open-Meteo)
|
| 19 |
+
- Производственный календарь РФ (isdayoff.ru)
|
| 20 |
+
- Сравнение прогноза с фактическими данными
|
| 21 |
+
- Экспорт прогноза в CSV
|
app/dashboard.py
ADDED
|
@@ -0,0 +1,568 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Дашборд прогнозирования заказов — Chronos-2
|
| 4 |
+
Запуск: streamlit run app/dashboard.py
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys, os
|
| 8 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
| 9 |
+
|
| 10 |
+
import streamlit as st
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import numpy as np
|
| 13 |
+
import plotly.graph_objects as go
|
| 14 |
+
from plotly.subplots import make_subplots
|
| 15 |
+
import io
|
| 16 |
+
|
| 17 |
+
from app.utils.data import load_orders, TYPE_META, build_calendar, fetch_weather
|
| 18 |
+
|
| 19 |
+
# ─────────────────────────────────────────────────────────────
|
| 20 |
+
# КОНФИГ СТРАНИЦЫ
|
| 21 |
+
# ─────────────────────────────────────────────────────────────
|
| 22 |
+
|
| 23 |
+
st.set_page_config(
|
| 24 |
+
page_title="Chronos-2 · Прогноз заказов",
|
| 25 |
+
page_icon="📦",
|
| 26 |
+
layout="wide",
|
| 27 |
+
initial_sidebar_state="expanded",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
st.markdown("""
|
| 31 |
+
<style>
|
| 32 |
+
.main { background-color: #0d1117; }
|
| 33 |
+
.stMetric { background: #161b22; border-radius: 8px; padding: 12px; }
|
| 34 |
+
div[data-testid="stMetricValue"] { font-size: 2rem; font-weight: bold; }
|
| 35 |
+
.upload-box { border: 2px dashed #30363d; border-radius: 8px; padding: 16px; }
|
| 36 |
+
h1, h2, h3 { color: #e6edf3 !important; }
|
| 37 |
+
</style>
|
| 38 |
+
""", unsafe_allow_html=True)
|
| 39 |
+
|
| 40 |
+
# ─────────────────────────────────────────────────────────────
|
| 41 |
+
# SIDEBAR
|
| 42 |
+
# ─────────────────────────────────────────────────────────────
|
| 43 |
+
|
| 44 |
+
with st.sidebar:
|
| 45 |
+
st.image("https://img.shields.io/badge/Chronos--2-AutoGluon-blue?style=for-the-badge", width=200)
|
| 46 |
+
st.title("⚙️ Настройки")
|
| 47 |
+
|
| 48 |
+
st.markdown("### 📂 Загрузка данных")
|
| 49 |
+
file_cur = st.file_uploader(
|
| 50 |
+
"Текущий период (обязательно)",
|
| 51 |
+
type=["xlsx", "xls"],
|
| 52 |
+
help="XLSX с колонками: Date, Кол-во ДД, Тип доставки"
|
| 53 |
+
)
|
| 54 |
+
file_prev = st.file_uploader(
|
| 55 |
+
"Прошлый год (опционально)",
|
| 56 |
+
type=["xlsx", "xls"],
|
| 57 |
+
help="Тот же формат, но данные прошлого года"
|
| 58 |
+
)
|
| 59 |
+
file_actual = st.file_uploader(
|
| 60 |
+
"Фактические данные (для сравнения)",
|
| 61 |
+
type=["xlsx", "xls"],
|
| 62 |
+
help="Реальные данные за прогнозный период"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
st.markdown("---")
|
| 66 |
+
st.markdown("### 📅 Прогноз")
|
| 67 |
+
forecast_days = st.slider("Горизонт прогноза (дней)", 7, 30, 14)
|
| 68 |
+
model_path = st.text_input("Папка модели", value="/tmp/models/dashboard")
|
| 69 |
+
|
| 70 |
+
run_btn = st.button("🚀 Запустить прогноз", type="primary",
|
| 71 |
+
disabled=(file_cur is None), use_container_width=True)
|
| 72 |
+
|
| 73 |
+
st.markdown("---")
|
| 74 |
+
st.markdown("### 📤 Экспорт")
|
| 75 |
+
export_btn = st.button("⬇️ Скачать прогноз CSV",
|
| 76 |
+
disabled="forecast_result" not in st.session_state,
|
| 77 |
+
use_container_width=True)
|
| 78 |
+
|
| 79 |
+
# ─────────────────────────────────────────────────────────────
|
| 80 |
+
# ОСНОВНАЯ ОБЛАСТЬ
|
| 81 |
+
# ─────────────────────────────────────────────────────────────
|
| 82 |
+
|
| 83 |
+
st.title("📦 Прогноз заказов · Chronos-2")
|
| 84 |
+
st.caption("Модель: AutoGluon 1.5 + Chronos-2 | Погода: Open-Meteo | Календарь: isdayoff.ru")
|
| 85 |
+
|
| 86 |
+
tabs = st.tabs(["📊 Обзор данных", "🔮 Прогноз", "📐 Сравнение с фактом"])
|
| 87 |
+
|
| 88 |
+
# ─────────────────────────────────────────────────────────────
|
| 89 |
+
# TAB 1: ОБЗОР ДАННЫХ
|
| 90 |
+
# ─────────────────────────────────────────────────────────────
|
| 91 |
+
|
| 92 |
+
with tabs[0]:
|
| 93 |
+
if file_cur is None:
|
| 94 |
+
st.info("Загрузите файл с историческими данными в боковой панели.")
|
| 95 |
+
else:
|
| 96 |
+
df = load_orders(file_cur)
|
| 97 |
+
|
| 98 |
+
# KPI
|
| 99 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 100 |
+
with col1: st.metric("Всего заказов", f"{df['count'].sum():,}".replace(",", " "))
|
| 101 |
+
with col2: st.metric("Дней в данных", df["date"].nunique())
|
| 102 |
+
with col3: st.metric("Период", f"{df['date'].min().strftime('%d.%m.%y')} — {df['date'].max().strftime('%d.%m.%y')}")
|
| 103 |
+
with col4: st.metric("Среднее в день", f"{df.groupby('date')['count'].sum().mean():.0f}")
|
| 104 |
+
|
| 105 |
+
st.markdown("---")
|
| 106 |
+
|
| 107 |
+
# Стековый график исторических данных
|
| 108 |
+
daily = df.groupby(["date", "type"])["count"].sum().unstack(fill_value=0)
|
| 109 |
+
daily.index = pd.to_datetime(daily.index)
|
| 110 |
+
types_in = sorted(daily.columns,
|
| 111 |
+
key=lambda t: TYPE_META.get(t, {}).get("order", 9))
|
| 112 |
+
|
| 113 |
+
fig = go.Figure()
|
| 114 |
+
for dtype in types_in:
|
| 115 |
+
meta = TYPE_META.get(dtype, {"short": dtype, "color": "#888"})
|
| 116 |
+
fig.add_trace(go.Bar(
|
| 117 |
+
x=daily.index, y=daily[dtype],
|
| 118 |
+
name=meta["short"], marker_color=meta["color"],
|
| 119 |
+
hovertemplate="%{x|%d %b}<br>%{y:,} заказов<extra>" + meta["short"] + "</extra>",
|
| 120 |
+
))
|
| 121 |
+
|
| 122 |
+
fig.update_layout(
|
| 123 |
+
barmode="stack",
|
| 124 |
+
title="История заказов по типу доставки",
|
| 125 |
+
paper_bgcolor="#0d1117", plot_bgcolor="#0d1117",
|
| 126 |
+
font_color="#e6edf3",
|
| 127 |
+
legend=dict(orientation="h", y=-0.15),
|
| 128 |
+
xaxis=dict(gridcolor="#1e2330"),
|
| 129 |
+
yaxis=dict(gridcolor="#1e2330"),
|
| 130 |
+
height=420,
|
| 131 |
+
)
|
| 132 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 133 |
+
|
| 134 |
+
# Разбивка по типам
|
| 135 |
+
col_a, col_b = st.columns(2)
|
| 136 |
+
with col_a:
|
| 137 |
+
st.markdown("#### По типу доставки")
|
| 138 |
+
type_summary = df.groupby("type")["count"].agg(["sum", "mean"]).round(0)
|
| 139 |
+
type_summary.columns = ["Итого", "В день (среднее)"]
|
| 140 |
+
type_summary["Доля %"] = (type_summary["Итого"] / type_summary["Итого"].sum() * 100).round(1)
|
| 141 |
+
st.dataframe(type_summary.sort_values("Итого", ascending=False), use_container_width=True)
|
| 142 |
+
|
| 143 |
+
with col_b:
|
| 144 |
+
st.markdown("#### По дням недели")
|
| 145 |
+
df["dow"] = df["date"].dt.day_name()
|
| 146 |
+
dow_order = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
|
| 147 |
+
dow_ru = ["Пн","Вт","Ср","Чт","Пт","Сб","Вс"]
|
| 148 |
+
dow_summary = df.groupby("dow")["count"].mean().reindex(dow_order)
|
| 149 |
+
fig2 = go.Figure(go.Bar(
|
| 150 |
+
x=dow_ru,
|
| 151 |
+
y=dow_summary.values,
|
| 152 |
+
marker_color=["#22c55e"]*5 + ["#f59e0b"]*2,
|
| 153 |
+
))
|
| 154 |
+
fig2.update_layout(
|
| 155 |
+
paper_bgcolor="#0d1117", plot_bgcolor="#0d1117",
|
| 156 |
+
font_color="#e6edf3", height=280,
|
| 157 |
+
yaxis=dict(gridcolor="#1e2330"),
|
| 158 |
+
showlegend=False,
|
| 159 |
+
)
|
| 160 |
+
st.plotly_chart(fig2, use_container_width=True)
|
| 161 |
+
|
| 162 |
+
# ─────────────────────────────────────────────────────────────
|
| 163 |
+
# ЗАПУСК ПРОГНОЗА
|
| 164 |
+
# ─────────────────────────────────────────────────────────────
|
| 165 |
+
|
| 166 |
+
if run_btn and file_cur is not None:
|
| 167 |
+
with st.spinner("Загружаем погоду и производственный календарь..."):
|
| 168 |
+
from app.utils.forecast import run_forecast
|
| 169 |
+
df_cur = load_orders(file_cur)
|
| 170 |
+
df_prev = load_orders(file_prev) if file_prev else None
|
| 171 |
+
|
| 172 |
+
with st.spinner(f"Обучаем Chronos-2 и строим прогноз на {forecast_days} дней..."):
|
| 173 |
+
try:
|
| 174 |
+
result = run_forecast(df_cur, df_prev, forecast_days, model_path)
|
| 175 |
+
st.session_state["forecast_result"] = result
|
| 176 |
+
st.session_state["df_cur"] = df_cur
|
| 177 |
+
st.success("Прогноз готов!")
|
| 178 |
+
st.rerun()
|
| 179 |
+
except Exception as e:
|
| 180 |
+
st.error(f"Ошибка: {e}")
|
| 181 |
+
|
| 182 |
+
# ─────────────────────────────────────────────────────────────
|
| 183 |
+
# TAB 2: ПРОГНОЗ
|
| 184 |
+
# ─────────────────────────────────────────────────────────────
|
| 185 |
+
|
| 186 |
+
with tabs[1]:
|
| 187 |
+
if "forecast_result" not in st.session_state:
|
| 188 |
+
st.info("Загрузите данные и нажмите 'Запустить прогноз'.")
|
| 189 |
+
else:
|
| 190 |
+
res = st.session_state["forecast_result"]
|
| 191 |
+
df_cur = st.session_state["df_cur"]
|
| 192 |
+
types = res["types"]
|
| 193 |
+
fut_dates = res["fut_dates"]
|
| 194 |
+
f_total = res["forecast_total"]
|
| 195 |
+
lo, hi = res["lo"], res["hi"]
|
| 196 |
+
w_fut = res["weather_fut"]
|
| 197 |
+
cal_fut = res["calendar_fut"]
|
| 198 |
+
|
| 199 |
+
# KPI
|
| 200 |
+
holidays_in_period = cal_fut["is_holiday"].sum()
|
| 201 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 202 |
+
with col1: st.metric("Прогноз всего", f"{int(f_total.sum()):,}".replace(",", " "))
|
| 203 |
+
with col2: st.metric("Среднее в день", f"{f_total.mean():.0f}")
|
| 204 |
+
with col3: st.metric("Период", f"{fut_dates[0].strftime('%d.%m')} — {fut_dates[-1].strftime('%d.%m.%Y')}")
|
| 205 |
+
with col4: st.metric("Праздников в периоде", int(holidays_in_period))
|
| 206 |
+
|
| 207 |
+
st.markdown("---")
|
| 208 |
+
|
| 209 |
+
# Главный график: история + прогноз
|
| 210 |
+
hist_daily = df_cur.groupby(["date","type"])["count"].sum().unstack(fill_value=0)
|
| 211 |
+
hist_daily.index = pd.to_datetime(hist_daily.index)
|
| 212 |
+
show_history = hist_daily.tail(30)
|
| 213 |
+
|
| 214 |
+
fig = make_subplots(
|
| 215 |
+
rows=2, cols=1,
|
| 216 |
+
row_heights=[0.72, 0.28],
|
| 217 |
+
shared_xaxes=True,
|
| 218 |
+
vertical_spacing=0.06,
|
| 219 |
+
subplot_titles=["Заказы: история + прогноз", "Погода Москвы"],
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# История (полупрозрачные бары)
|
| 223 |
+
for dtype in types:
|
| 224 |
+
if dtype not in show_history.columns: continue
|
| 225 |
+
meta = TYPE_META.get(dtype, {"short": dtype, "color": "#888"})
|
| 226 |
+
fig.add_trace(go.Bar(
|
| 227 |
+
x=show_history.index,
|
| 228 |
+
y=show_history[dtype],
|
| 229 |
+
name=meta["short"],
|
| 230 |
+
marker_color=meta["color"],
|
| 231 |
+
opacity=0.55,
|
| 232 |
+
legendgroup=dtype,
|
| 233 |
+
hovertemplate="%{x|%d %b}<br>%{y:,}<extra>" + meta["short"] + " (факт)</extra>",
|
| 234 |
+
), row=1, col=1)
|
| 235 |
+
|
| 236 |
+
# Прогноз — стековые бары
|
| 237 |
+
f_bottoms = np.zeros(len(fut_dates))
|
| 238 |
+
for dtype in types:
|
| 239 |
+
if dtype not in res["forecast_by_type"]: continue
|
| 240 |
+
meta = TYPE_META.get(dtype, {"short": dtype, "color": "#888"})
|
| 241 |
+
vals = res["forecast_by_type"][dtype]["mean"].reindex(fut_dates, fill_value=0).values
|
| 242 |
+
fig.add_trace(go.Bar(
|
| 243 |
+
x=list(fut_dates),
|
| 244 |
+
y=vals,
|
| 245 |
+
base=f_bottoms,
|
| 246 |
+
name=meta["short"],
|
| 247 |
+
marker_color=meta["color"],
|
| 248 |
+
opacity=0.95,
|
| 249 |
+
legendgroup=dtype,
|
| 250 |
+
showlegend=False,
|
| 251 |
+
hovertemplate="%{x|%d %b}<br>%{y:,}<extra>" + meta["short"] + " (прогноз)</extra>",
|
| 252 |
+
), row=1, col=1)
|
| 253 |
+
f_bottoms += vals
|
| 254 |
+
|
| 255 |
+
# Линия прогноза (итого)
|
| 256 |
+
fig.add_trace(go.Scatter(
|
| 257 |
+
x=list(fut_dates), y=f_total.values,
|
| 258 |
+
mode="lines+markers+text",
|
| 259 |
+
name="Прогноз (итого)",
|
| 260 |
+
line=dict(color="#f59e0b", width=2.5),
|
| 261 |
+
marker=dict(size=5),
|
| 262 |
+
text=[f"{int(v):,}".replace(",", "\u2009") for v in f_total.values],
|
| 263 |
+
textposition="top center",
|
| 264 |
+
textfont=dict(color="#f59e0b", size=9),
|
| 265 |
+
hovertemplate="%{x|%d %b}<br>Прогноз: %{y:,}<extra></extra>",
|
| 266 |
+
), row=1, col=1)
|
| 267 |
+
|
| 268 |
+
# Интервал неопределённости
|
| 269 |
+
fig.add_trace(go.Scatter(
|
| 270 |
+
x=list(fut_dates) + list(fut_dates[::-1]),
|
| 271 |
+
y=list(hi.values) + list(lo.values[::-1]),
|
| 272 |
+
fill="toself", fillcolor="rgba(245,158,11,0.15)",
|
| 273 |
+
line=dict(color="rgba(0,0,0,0)"),
|
| 274 |
+
name="Интервал 10–90%",
|
| 275 |
+
hoverinfo="skip",
|
| 276 |
+
), row=1, col=1)
|
| 277 |
+
|
| 278 |
+
# Разделитель история/прогноз
|
| 279 |
+
split_date = df_cur["date"].max()
|
| 280 |
+
fig.add_vline(x=split_date, line_dash="dash",
|
| 281 |
+
line_color="#374151", line_width=1.5)
|
| 282 |
+
fig.add_annotation(
|
| 283 |
+
x=split_date, y=1.02, xref="x", yref="paper",
|
| 284 |
+
text="прогноз →", showarrow=False,
|
| 285 |
+
font=dict(color="#6b7280", size=10),
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# Праздники
|
| 289 |
+
for i, row_c in cal_fut.iterrows():
|
| 290 |
+
if row_c["is_holiday"] == 1:
|
| 291 |
+
fig.add_vrect(
|
| 292 |
+
x0=row_c["date"] - pd.Timedelta(hours=12),
|
| 293 |
+
x1=row_c["date"] + pd.Timedelta(hours=12),
|
| 294 |
+
fillcolor="rgba(251,191,36,0.08)", line_width=0,
|
| 295 |
+
row=1, col=1,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
# Погода
|
| 299 |
+
temp_vals = w_fut[w_fut["date"].isin(fut_dates)]["temp_max"].astype(float)
|
| 300 |
+
prec_vals = w_fut[w_fut["date"].isin(fut_dates)]["precipitation"].astype(float)
|
| 301 |
+
snow_vals = w_fut[w_fut["date"].isin(fut_dates)]["snowfall"].astype(float)
|
| 302 |
+
w_dates = w_fut[w_fut["date"].isin(fut_dates)]["date"]
|
| 303 |
+
|
| 304 |
+
fig.add_trace(go.Bar(
|
| 305 |
+
x=w_dates, y=prec_vals, name="Осадки мм",
|
| 306 |
+
marker_color="#3b82f6", opacity=0.5,
|
| 307 |
+
), row=2, col=1)
|
| 308 |
+
fig.add_trace(go.Bar(
|
| 309 |
+
x=w_dates, y=snow_vals, name="Снег мм",
|
| 310 |
+
marker_color="#bfdbfe", opacity=0.8,
|
| 311 |
+
), row=2, col=1)
|
| 312 |
+
fig.add_trace(go.Scatter(
|
| 313 |
+
x=w_dates, y=temp_vals, name="Темп °C",
|
| 314 |
+
line=dict(color="#fbbf24", width=2),
|
| 315 |
+
yaxis="y3",
|
| 316 |
+
), row=2, col=1)
|
| 317 |
+
|
| 318 |
+
fig.update_layout(
|
| 319 |
+
barmode="stack",
|
| 320 |
+
paper_bgcolor="#0d1117", plot_bgcolor="#0d1117",
|
| 321 |
+
font_color="#e6edf3",
|
| 322 |
+
height=680,
|
| 323 |
+
legend=dict(orientation="h", y=-0.12, x=0),
|
| 324 |
+
xaxis=dict(gridcolor="#1e2330"),
|
| 325 |
+
yaxis=dict(gridcolor="#1e2330", title="Заказы"),
|
| 326 |
+
xaxis2=dict(gridcolor="#1e2330"),
|
| 327 |
+
yaxis2=dict(gridcolor="#1e2330", title="мм"),
|
| 328 |
+
)
|
| 329 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 330 |
+
|
| 331 |
+
# Таблица прогноза
|
| 332 |
+
st.markdown("#### Прогноз по дням")
|
| 333 |
+
table_rows = []
|
| 334 |
+
for dt in fut_dates:
|
| 335 |
+
cal_row = cal_fut[cal_fut["date"] == dt]
|
| 336 |
+
is_hol = int(cal_row["is_holiday"].values[0]) if len(cal_row) else 0
|
| 337 |
+
is_sh = int(cal_row["is_short"].values[0]) if len(cal_row) else 0
|
| 338 |
+
w_row = w_fut[w_fut["date"] == dt]
|
| 339 |
+
temp = float(w_row["temp_max"].values[0]) if len(w_row) else 0
|
| 340 |
+
prec = float(w_row["precipitation"].values[0]) if len(w_row) else 0
|
| 341 |
+
f_val = f_total.get(dt, 0)
|
| 342 |
+
lo_val = lo.get(dt, 0)
|
| 343 |
+
hi_val = hi.get(dt, 0)
|
| 344 |
+
flag = "🎉 Праздник" if is_hol else ("📋 Кор. день" if is_sh else "")
|
| 345 |
+
table_rows.append({
|
| 346 |
+
"Дата": dt.strftime("%d %b %Y (%a)"),
|
| 347 |
+
"Прогноз": int(f_val),
|
| 348 |
+
"Мин (10%)": int(lo_val),
|
| 349 |
+
"Макс (90%)": int(hi_val),
|
| 350 |
+
"Темп °C": f"{temp:.1f}",
|
| 351 |
+
"Осадки мм": f"{prec:.1f}",
|
| 352 |
+
"Статус": flag,
|
| 353 |
+
})
|
| 354 |
+
|
| 355 |
+
df_table = pd.DataFrame(table_rows)
|
| 356 |
+
st.dataframe(
|
| 357 |
+
df_table.style.background_gradient(subset=["Прогноз"], cmap="YlOrRd"),
|
| 358 |
+
use_container_width=True, hide_index=True,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
# ─────────────────────────────────────────────────────────────
|
| 362 |
+
# TAB 3: СРАВНЕНИЕ С ФАКТОМ
|
| 363 |
+
# ─────────────────────────────────────────────────────────────
|
| 364 |
+
|
| 365 |
+
with tabs[2]:
|
| 366 |
+
if "forecast_result" not in st.session_state:
|
| 367 |
+
st.info("Сначала запустите прогноз.")
|
| 368 |
+
elif file_actual is None:
|
| 369 |
+
st.info("Загрузите файл с фактическими данными в боковой панели.")
|
| 370 |
+
else:
|
| 371 |
+
res = st.session_state["forecast_result"]
|
| 372 |
+
df_actual = load_orders(file_actual)
|
| 373 |
+
fut_dates = res["fut_dates"]
|
| 374 |
+
f_total = res["forecast_total"]
|
| 375 |
+
lo, hi = res["lo"], res["hi"]
|
| 376 |
+
|
| 377 |
+
# Факт по дням
|
| 378 |
+
actual_daily = df_actual.groupby("date")["count"].sum()
|
| 379 |
+
actual_daily.index = pd.to_datetime(actual_daily.index)
|
| 380 |
+
|
| 381 |
+
# Метрики
|
| 382 |
+
common = [d for d in fut_dates if d in actual_daily.index]
|
| 383 |
+
if common:
|
| 384 |
+
act = actual_daily.reindex(common).values
|
| 385 |
+
fct = f_total.reindex(common).values
|
| 386 |
+
mae = np.abs(act - fct).mean()
|
| 387 |
+
mape = (np.abs(act - fct) / np.where(act > 0, act, 1) * 100).mean()
|
| 388 |
+
bias = (act - fct).mean()
|
| 389 |
+
rmse = np.sqrt(((act - fct)**2).mean())
|
| 390 |
+
in_interval = sum(1 for d in common
|
| 391 |
+
if lo.get(d, 0) <= actual_daily[d] <= hi.get(d, 0))
|
| 392 |
+
|
| 393 |
+
col1, col2, col3, col4, col5 = st.columns(5)
|
| 394 |
+
with col1: st.metric("MAPE", f"{mape:.1f}%",
|
| 395 |
+
help="Средняя относительная ошибка. <5% = отлично")
|
| 396 |
+
with col2: st.metric("MAE", f"{mae:.0f} зак.")
|
| 397 |
+
with col3: st.metric("RMSE", f"{rmse:.0f}")
|
| 398 |
+
with col4: st.metric("Bias", f"{bias:+.0f}",
|
| 399 |
+
delta=f"{'занижает' if bias > 0 else 'завышает'}",
|
| 400 |
+
delta_color="inverse")
|
| 401 |
+
with col5: st.metric("В интервале 10-90%", f"{in_interval}/{len(common)} дней")
|
| 402 |
+
|
| 403 |
+
st.markdown("---")
|
| 404 |
+
|
| 405 |
+
# График сравнения
|
| 406 |
+
pct_errors = []
|
| 407 |
+
for dt in fut_dates:
|
| 408 |
+
if dt in actual_daily.index:
|
| 409 |
+
act_v = actual_daily[dt]
|
| 410 |
+
fct_v = f_total.get(dt, 0)
|
| 411 |
+
err = act_v - fct_v
|
| 412 |
+
pct = err / act_v * 100 if act_v > 0 else 0
|
| 413 |
+
else:
|
| 414 |
+
pct = None
|
| 415 |
+
pct_errors.append(pct)
|
| 416 |
+
|
| 417 |
+
fig = make_subplots(
|
| 418 |
+
rows=2, cols=1,
|
| 419 |
+
row_heights=[0.62, 0.38],
|
| 420 |
+
shared_xaxes=True,
|
| 421 |
+
vertical_spacing=0.06,
|
| 422 |
+
subplot_titles=[
|
| 423 |
+
"Факт (бары) vs Прогноз (линия)",
|
| 424 |
+
"Отклонение прогноза, %",
|
| 425 |
+
],
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
# Факт по типам
|
| 429 |
+
actual_by_type = df_actual.groupby(["date","type"])["count"].sum().unstack(fill_value=0)
|
| 430 |
+
actual_by_type.index = pd.to_datetime(actual_by_type.index)
|
| 431 |
+
for dtype in res["types"]:
|
| 432 |
+
if dtype not in actual_by_type.columns: continue
|
| 433 |
+
meta = TYPE_META.get(dtype, {"short": dtype, "color": "#888"})
|
| 434 |
+
vals = [actual_by_type[dtype].get(d, 0) for d in fut_dates]
|
| 435 |
+
fig.add_trace(go.Bar(
|
| 436 |
+
x=list(fut_dates), y=vals, name=meta["short"],
|
| 437 |
+
marker_color=meta["color"], opacity=0.88,
|
| 438 |
+
legendgroup=dtype,
|
| 439 |
+
hovertemplate="%{x|%d %b}<br>%{y:,}<extra>" + meta["short"] + " (факт)</extra>",
|
| 440 |
+
), row=1, col=1)
|
| 441 |
+
|
| 442 |
+
# Прогноз — линия
|
| 443 |
+
fig.add_trace(go.Scatter(
|
| 444 |
+
x=list(fut_dates), y=f_total.values,
|
| 445 |
+
mode="lines+markers",
|
| 446 |
+
name="Прогноз Chronos-2",
|
| 447 |
+
line=dict(color="#f59e0b", width=2.5, dash="dot"),
|
| 448 |
+
marker=dict(size=5),
|
| 449 |
+
), row=1, col=1)
|
| 450 |
+
|
| 451 |
+
# Интервал
|
| 452 |
+
fig.add_trace(go.Scatter(
|
| 453 |
+
x=list(fut_dates) + list(fut_dates[::-1]),
|
| 454 |
+
y=list(hi.values) + list(lo.values[::-1]),
|
| 455 |
+
fill="toself", fillcolor="rgba(245,158,11,0.12)",
|
| 456 |
+
line=dict(color="rgba(0,0,0,0)"),
|
| 457 |
+
name="Интервал 10–90%", hoverinfo="skip",
|
| 458 |
+
), row=1, col=1)
|
| 459 |
+
|
| 460 |
+
# % ошибки
|
| 461 |
+
colors_pct = ["#ef4444" if (v is not None and v < 0) else "#22c55e"
|
| 462 |
+
for v in pct_errors]
|
| 463 |
+
texts_pct = [f"{v:+.1f}%" if v is not None else ""
|
| 464 |
+
for v in pct_errors]
|
| 465 |
+
fig.add_trace(go.Bar(
|
| 466 |
+
x=list(fut_dates),
|
| 467 |
+
y=[v if v is not None else 0 for v in pct_errors],
|
| 468 |
+
marker_color=colors_pct, opacity=0.85,
|
| 469 |
+
text=texts_pct, textposition="outside",
|
| 470 |
+
textfont=dict(size=9, color="white"),
|
| 471 |
+
name="Отклонение %",
|
| 472 |
+
showlegend=False,
|
| 473 |
+
), row=2, col=1)
|
| 474 |
+
|
| 475 |
+
# Линии ±5% и bias
|
| 476 |
+
for val, dash, color, label in [
|
| 477 |
+
(0, "solid", "#555", ""),
|
| 478 |
+
(5, "dash", "#374151", "+5%"),
|
| 479 |
+
(-5, "dash", "#374151", "-5%"),
|
| 480 |
+
]:
|
| 481 |
+
fig.add_hline(y=val, line_dash=dash, line_color=color,
|
| 482 |
+
line_width=0.8, row=2, col=1)
|
| 483 |
+
|
| 484 |
+
if common:
|
| 485 |
+
bias_pct = bias / np.mean(act) * 100
|
| 486 |
+
fig.add_hline(y=bias_pct, line_dash="dot",
|
| 487 |
+
line_color="#f59e0b", line_width=1.2,
|
| 488 |
+
annotation_text=f"Bias {bias_pct:+.1f}%",
|
| 489 |
+
annotation_font_color="#f59e0b",
|
| 490 |
+
row=2, col=1)
|
| 491 |
+
|
| 492 |
+
# Праздники
|
| 493 |
+
cal_period = build_calendar(fut_dates[0], fut_dates[-1])
|
| 494 |
+
for _, crow in cal_period[cal_period["is_holiday"]==1].iterrows():
|
| 495 |
+
for row_idx in (1, 2):
|
| 496 |
+
fig.add_vrect(
|
| 497 |
+
x0=crow["date"] - pd.Timedelta(hours=12),
|
| 498 |
+
x1=crow["date"] + pd.Timedelta(hours=12),
|
| 499 |
+
fillcolor="rgba(251,191,36,0.08)", line_width=0,
|
| 500 |
+
row=row_idx, col=1,
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
fig.update_layout(
|
| 504 |
+
barmode="stack",
|
| 505 |
+
paper_bgcolor="#0d1117", plot_bgcolor="#0d1117",
|
| 506 |
+
font_color="#e6edf3",
|
| 507 |
+
height=650,
|
| 508 |
+
legend=dict(orientation="h", y=-0.10, x=0),
|
| 509 |
+
xaxis=dict(gridcolor="#1e2330"),
|
| 510 |
+
yaxis=dict(gridcolor="#1e2330", title="Заказы"),
|
| 511 |
+
xaxis2=dict(gridcolor="#1e2330"),
|
| 512 |
+
yaxis2=dict(gridcolor="#1e2330", title="%, отклонение", zeroline=True),
|
| 513 |
+
)
|
| 514 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 515 |
+
|
| 516 |
+
# Детальная таблица
|
| 517 |
+
st.markdown("#### Детализация по дням")
|
| 518 |
+
compare_rows = []
|
| 519 |
+
for dt in fut_dates:
|
| 520 |
+
if dt not in actual_daily.index: continue
|
| 521 |
+
act_v = int(actual_daily[dt])
|
| 522 |
+
fct_v = int(f_total.get(dt, 0))
|
| 523 |
+
err = act_v - fct_v
|
| 524 |
+
pct = err / act_v * 100 if act_v > 0 else 0
|
| 525 |
+
in_iv = lo.get(dt, 0) <= act_v <= hi.get(dt, 0)
|
| 526 |
+
compare_rows.append({
|
| 527 |
+
"Дата": dt.strftime("%d %b %Y (%a)"),
|
| 528 |
+
"Факт": act_v,
|
| 529 |
+
"Прогноз": fct_v,
|
| 530 |
+
"Ошибка": err,
|
| 531 |
+
"% ошибки": round(pct, 1),
|
| 532 |
+
"В интервале": "✅" if in_iv else "❌",
|
| 533 |
+
})
|
| 534 |
+
|
| 535 |
+
df_cmp = pd.DataFrame(compare_rows)
|
| 536 |
+
|
| 537 |
+
def color_pct(val):
|
| 538 |
+
if abs(val) <= 3: return "background-color: #14532d; color: white"
|
| 539 |
+
elif abs(val) <= 7: return "background-color: #713f12; color: white"
|
| 540 |
+
else: return "background-color: #7f1d1d; color: white"
|
| 541 |
+
|
| 542 |
+
st.dataframe(
|
| 543 |
+
df_cmp.style.applymap(color_pct, subset=["% ошибки"]),
|
| 544 |
+
use_container_width=True, hide_index=True,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
# ─────────────────────────────────────────────────────────────
|
| 548 |
+
# ЭКСПОРТ
|
| 549 |
+
# ─────────────────────────────────────────────────────────────
|
| 550 |
+
|
| 551 |
+
if export_btn and "forecast_result" in st.session_state:
|
| 552 |
+
res = st.session_state["forecast_result"]
|
| 553 |
+
rows = []
|
| 554 |
+
for dt in res["fut_dates"]:
|
| 555 |
+
rows.append({
|
| 556 |
+
"date": dt.strftime("%Y-%m-%d"),
|
| 557 |
+
"forecast": int(res["forecast_total"].get(dt, 0)),
|
| 558 |
+
"low_10pct": int(res["lo"].get(dt, 0)),
|
| 559 |
+
"high_90pct": int(res["hi"].get(dt, 0)),
|
| 560 |
+
})
|
| 561 |
+
df_exp = pd.DataFrame(rows)
|
| 562 |
+
csv = df_exp.to_csv(index=False, encoding="utf-8-sig")
|
| 563 |
+
st.sidebar.download_button(
|
| 564 |
+
label="📥 Скачать CSV",
|
| 565 |
+
data=csv,
|
| 566 |
+
file_name=f"forecast_{res['fut_dates'][0].strftime('%Y%m%d')}.csv",
|
| 567 |
+
mime="text/csv",
|
| 568 |
+
)
|
app/utils/__init__.py
ADDED
|
File without changes
|
app/utils/data.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import requests
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
TYPE_META = {
|
| 9 |
+
"Доставка за 1 час": {"short": "1 час", "color": "#22c55e", "order": 0},
|
| 10 |
+
"Доставка за 2 час": {"short": "2 часа", "color": "#f59e0b", "order": 1},
|
| 11 |
+
"Доставка за 30 мин": {"short": "30 мин", "color": "#a855f7", "order": 2},
|
| 12 |
+
"Экспресс": {"short": "Экспресс", "color": "#ec4899", "order": 3},
|
| 13 |
+
"Остальное": {"short": "Остальное","color": "#f97316", "order": 4},
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_orders(file) -> pd.DataFrame:
|
| 18 |
+
"""Читает xlsx/csv, возвращает: date, type, count."""
|
| 19 |
+
if hasattr(file, "name"):
|
| 20 |
+
name = file.name
|
| 21 |
+
else:
|
| 22 |
+
name = str(file)
|
| 23 |
+
|
| 24 |
+
if name.endswith(".xlsx") or name.endswith(".xls"):
|
| 25 |
+
df = pd.read_excel(file, skiprows=2, header=0)
|
| 26 |
+
else:
|
| 27 |
+
df = pd.read_csv(file)
|
| 28 |
+
|
| 29 |
+
df.columns = ["date", "count", "type"]
|
| 30 |
+
df = df.dropna(subset=["date"]).copy()
|
| 31 |
+
df["date"] = pd.to_datetime(df["date"]).dt.normalize()
|
| 32 |
+
df["count"] = pd.to_numeric(df["count"], errors="coerce").fillna(0).astype(int)
|
| 33 |
+
df["type"] = df["type"].str.replace("до", "за", regex=False).str.strip()
|
| 34 |
+
return df
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fetch_weather(start: str, end: str) -> pd.DataFrame:
|
| 38 |
+
url = "https://archive-api.open-meteo.com/v1/archive"
|
| 39 |
+
r = requests.get(url, params={
|
| 40 |
+
"latitude": 55.7558, "longitude": 37.6176,
|
| 41 |
+
"start_date": start, "end_date": end,
|
| 42 |
+
"daily": "temperature_2m_max,precipitation_sum,snowfall_sum",
|
| 43 |
+
"timezone": "Europe/Moscow",
|
| 44 |
+
}, timeout=20)
|
| 45 |
+
r.raise_for_status()
|
| 46 |
+
d = r.json()["daily"]
|
| 47 |
+
return pd.DataFrame({
|
| 48 |
+
"date": pd.to_datetime(d["time"]),
|
| 49 |
+
"temp_max": pd.array(d["temperature_2m_max"], dtype="Float64").fillna(0),
|
| 50 |
+
"precipitation": pd.array(d["precipitation_sum"], dtype="Float64").fillna(0),
|
| 51 |
+
"snowfall": pd.array(d["snowfall_sum"], dtype="Float64").fillna(0),
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def fetch_weather_forecast(days: int = 16) -> pd.DataFrame:
|
| 56 |
+
url = "https://api.open-meteo.com/v1/forecast"
|
| 57 |
+
r = requests.get(url, params={
|
| 58 |
+
"latitude": 55.7558, "longitude": 37.6176,
|
| 59 |
+
"daily": "temperature_2m_max,precipitation_sum,snowfall_sum",
|
| 60 |
+
"forecast_days": days,
|
| 61 |
+
"timezone": "Europe/Moscow",
|
| 62 |
+
}, timeout=20)
|
| 63 |
+
r.raise_for_status()
|
| 64 |
+
d = r.json()["daily"]
|
| 65 |
+
return pd.DataFrame({
|
| 66 |
+
"date": pd.to_datetime(d["time"]),
|
| 67 |
+
"temp_max": pd.array(d["temperature_2m_max"], dtype="Float64").fillna(0),
|
| 68 |
+
"precipitation": pd.array(d["precipitation_sum"], dtype="Float64").fillna(0),
|
| 69 |
+
"snowfall": pd.array(d["snowfall_sum"], dtype="Float64").fillna(0),
|
| 70 |
+
})
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def fetch_ru_calendar(year: int) -> pd.DataFrame:
|
| 74 |
+
r = requests.get(f"https://isdayoff.ru/api/getdata?year={year}", timeout=10)
|
| 75 |
+
r.raise_for_status()
|
| 76 |
+
data_str = r.text.strip()
|
| 77 |
+
dates, holidays, shorts = [], [], []
|
| 78 |
+
date = pd.Timestamp(f"{year}-01-01")
|
| 79 |
+
for ch in data_str:
|
| 80 |
+
dates.append(date)
|
| 81 |
+
holidays.append(1 if ch == "1" else 0)
|
| 82 |
+
shorts.append(1 if ch == "2" else 0)
|
| 83 |
+
date += pd.Timedelta(days=1)
|
| 84 |
+
return pd.DataFrame({"date": dates, "is_holiday": holidays, "is_short": shorts})
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def build_calendar(start: pd.Timestamp, end: pd.Timestamp) -> pd.DataFrame:
|
| 88 |
+
years = range(start.year, end.year + 1)
|
| 89 |
+
frames = [fetch_ru_calendar(y) for y in years]
|
| 90 |
+
cal = pd.concat(frames).reset_index(drop=True)
|
| 91 |
+
dates = pd.date_range(start, end, freq="D")
|
| 92 |
+
return cal[cal["date"].isin(dates)].reset_index(drop=True)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def build_series(orders_df, dtype, weather_df, cal_df, start, end, item_id):
|
| 96 |
+
full_dates = pd.date_range(start, end, freq="D")
|
| 97 |
+
agg = orders_df[orders_df["type"] == dtype].groupby("date")["count"].sum()
|
| 98 |
+
agg = agg.reindex(full_dates, fill_value=0).reset_index()
|
| 99 |
+
agg.columns = ["date", "target"]
|
| 100 |
+
cov_cols = ["temp_max", "precipitation", "snowfall", "is_holiday", "is_short"]
|
| 101 |
+
agg = agg.merge(weather_df, on="date", how="left")
|
| 102 |
+
agg = agg.merge(cal_df[["date", "is_holiday", "is_short"]], on="date", how="left")
|
| 103 |
+
agg[cov_cols] = agg[cov_cols].fillna(0)
|
| 104 |
+
agg["item_id"] = item_id
|
| 105 |
+
agg.rename(columns={"date": "timestamp"}, inplace=True)
|
| 106 |
+
return agg
|
app/utils/forecast.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor
|
| 5 |
+
from .data import build_series, fetch_weather, fetch_weather_forecast, build_calendar
|
| 6 |
+
|
| 7 |
+
COVARIATE_COLS = ["temp_max", "precipitation", "snowfall", "is_holiday", "is_short"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def run_forecast(
|
| 11 |
+
df_history: pd.DataFrame,
|
| 12 |
+
df_prev_year,
|
| 13 |
+
forecast_days: int,
|
| 14 |
+
model_path: str = "/tmp/models/dashboard",
|
| 15 |
+
) -> dict:
|
| 16 |
+
"""
|
| 17 |
+
Запускает Chronos-2 и возвращает словарь с результатами.
|
| 18 |
+
|
| 19 |
+
df_history — текущий год (обучающие данные)
|
| 20 |
+
df_prev_year — прошлый год (опционально, для обогащения)
|
| 21 |
+
forecast_days — горизонт прогноза
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
hist_start = df_history["date"].min()
|
| 25 |
+
hist_end = df_history["date"].max()
|
| 26 |
+
fut_start = hist_end + pd.Timedelta(days=1)
|
| 27 |
+
fut_end = fut_start + pd.Timedelta(days=forecast_days - 1)
|
| 28 |
+
|
| 29 |
+
# Загружаем погоду одним запросом на весь диапазон
|
| 30 |
+
w_hist = fetch_weather(hist_start.strftime("%Y-%m-%d"), hist_end.strftime("%Y-%m-%d"))
|
| 31 |
+
cal_hist = build_calendar(hist_start, hist_end)
|
| 32 |
+
|
| 33 |
+
# Для периода прогноза: если даты в будущем — используем forecast API,
|
| 34 |
+
# иначе архив
|
| 35 |
+
today = pd.Timestamp.today().normalize()
|
| 36 |
+
if fut_end > today:
|
| 37 |
+
days_needed = (fut_end - today).days + 2
|
| 38 |
+
w_fut = fetch_weather_forecast(days=days_needed)
|
| 39 |
+
w_fut = w_fut[w_fut["date"] >= fut_start].head(forecast_days)
|
| 40 |
+
else:
|
| 41 |
+
w_fut = fetch_weather(fut_start.strftime("%Y-%m-%d"), fut_end.strftime("%Y-%m-%d"))
|
| 42 |
+
cal_fut = build_calendar(fut_start, fut_end)
|
| 43 |
+
|
| 44 |
+
# Типы доставки
|
| 45 |
+
types = sorted(df_history["type"].unique(),
|
| 46 |
+
key=lambda t: {"Доставка за 1 час": 0, "Доставка за 2 час": 1,
|
| 47 |
+
"Доставка за 30 мин": 2, "Экспресс": 3,
|
| 48 |
+
"Остальное": 4}.get(t, 9))
|
| 49 |
+
|
| 50 |
+
# Собираем обучающие серии
|
| 51 |
+
rows = []
|
| 52 |
+
for dtype in types:
|
| 53 |
+
rows.append(build_series(df_history, dtype, w_hist, cal_hist,
|
| 54 |
+
hist_start, hist_end, f"{dtype}__cur"))
|
| 55 |
+
|
| 56 |
+
if df_prev_year is not None:
|
| 57 |
+
py_start = df_prev_year["date"].min()
|
| 58 |
+
py_end = df_prev_year["date"].max()
|
| 59 |
+
w_prev = fetch_weather(py_start.strftime("%Y-%m-%d"), py_end.strftime("%Y-%m-%d"))
|
| 60 |
+
cal_prev = build_calendar(py_start, py_end)
|
| 61 |
+
prev_types = df_prev_year["type"].unique()
|
| 62 |
+
for dtype in prev_types:
|
| 63 |
+
rows.append(build_series(df_prev_year, dtype, w_prev, cal_prev,
|
| 64 |
+
py_start, py_end, f"{dtype}__prev"))
|
| 65 |
+
|
| 66 |
+
train_df = pd.concat(rows, ignore_index=True)
|
| 67 |
+
train_df["timestamp"] = pd.to_datetime(train_df["timestamp"])
|
| 68 |
+
train_data = TimeSeriesDataFrame.from_data_frame(
|
| 69 |
+
train_df, id_column="item_id", timestamp_column="timestamp"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Обучение
|
| 73 |
+
predictor = TimeSeriesPredictor(
|
| 74 |
+
prediction_length=forecast_days,
|
| 75 |
+
freq="D",
|
| 76 |
+
path=model_path,
|
| 77 |
+
known_covariates_names=COVARIATE_COLS,
|
| 78 |
+
quantile_levels=[0.1, 0.25, 0.5, 0.75, 0.9],
|
| 79 |
+
verbosity=0,
|
| 80 |
+
).fit(
|
| 81 |
+
train_data,
|
| 82 |
+
presets="chronos2",
|
| 83 |
+
skip_model_selection=True,
|
| 84 |
+
enable_ensemble=False,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Прогноз (только текущий год)
|
| 88 |
+
cur_items = [iid for iid in train_data.item_ids if iid.endswith("__cur")]
|
| 89 |
+
predict_data = train_data.loc[cur_items]
|
| 90 |
+
|
| 91 |
+
fut_dates = pd.date_range(fut_start, periods=forecast_days, freq="D")
|
| 92 |
+
fut_rows = []
|
| 93 |
+
for iid in cur_items:
|
| 94 |
+
tmp = w_fut.copy()
|
| 95 |
+
tmp = tmp.merge(cal_fut[["date", "is_holiday", "is_short"]], on="date", how="left")
|
| 96 |
+
tmp["item_id"] = iid
|
| 97 |
+
tmp.rename(columns={"date": "timestamp"}, inplace=True)
|
| 98 |
+
fut_rows.append(tmp[["timestamp", "item_id"] + COVARIATE_COLS])
|
| 99 |
+
future_cov = TimeSeriesDataFrame.from_data_frame(
|
| 100 |
+
pd.concat(fut_rows, ignore_index=True),
|
| 101 |
+
id_column="item_id", timestamp_column="timestamp"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
predictions = predictor.predict(predict_data, known_covariates=future_cov)
|
| 105 |
+
|
| 106 |
+
# Собираем результат по типам
|
| 107 |
+
forecast_by_type = {}
|
| 108 |
+
for iid in cur_items:
|
| 109 |
+
dtype = iid.replace("__cur", "")
|
| 110 |
+
pred = predictions.loc[iid].reset_index()
|
| 111 |
+
pred.columns = ["date"] + [str(c) for c in pred.columns[1:]]
|
| 112 |
+
forecast_by_type[dtype] = pred.set_index("date")
|
| 113 |
+
|
| 114 |
+
forecast_total = sum(
|
| 115 |
+
forecast_by_type[t]["mean"].reindex(fut_dates, fill_value=0)
|
| 116 |
+
for t in types if t in forecast_by_type
|
| 117 |
+
)
|
| 118 |
+
lo = sum(
|
| 119 |
+
forecast_by_type[t]["0.1"].reindex(fut_dates, fill_value=0)
|
| 120 |
+
for t in types if t in forecast_by_type
|
| 121 |
+
)
|
| 122 |
+
hi = sum(
|
| 123 |
+
forecast_by_type[t]["0.9"].reindex(fut_dates, fill_value=0)
|
| 124 |
+
for t in types if t in forecast_by_type
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
return {
|
| 128 |
+
"types": types,
|
| 129 |
+
"forecast_by_type": forecast_by_type,
|
| 130 |
+
"forecast_total": forecast_total,
|
| 131 |
+
"lo": lo,
|
| 132 |
+
"hi": hi,
|
| 133 |
+
"fut_dates": fut_dates,
|
| 134 |
+
"weather_fut": w_fut,
|
| 135 |
+
"calendar_fut": cal_fut,
|
| 136 |
+
"history": df_history,
|
| 137 |
+
"weather_hist": w_hist,
|
| 138 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
autogluon.timeseries==1.5.0
|
| 2 |
+
chronos-forecasting==2.2.2
|
| 3 |
+
streamlit==1.55.0
|
| 4 |
+
plotly==6.6.0
|
| 5 |
+
pandas==2.3.3
|
| 6 |
+
numpy==2.1.3
|
| 7 |
+
requests==2.32.5
|
| 8 |
+
openpyxl==3.1.5
|