Spaces:
Sleeping
Sleeping
File size: 1,529 Bytes
9db6dea 010071f 3651f7b 010071f 3651f7b 1fadf44 3651f7b 9db6dea 1fadf44 9db6dea 010071f 1fadf44 9db6dea 1fadf44 9db6dea 1fadf44 9db6dea 1fadf44 9db6dea 1fadf44 9db6dea a9cd5f0 9db6dea 3651f7b 9db6dea a9cd5f0 9db6dea a9cd5f0 |
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 |
# tools/forecaster.py
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import plotly.graph_objects as go
def forecast_metric_tool(file_path: str, date_col: str, value_col: str):
"""
Forecast next 3 periods for any numeric metric.
Saves PNG to /tmp via our safe write monkey-patch, returns forecast table as text.
"""
# 1) Load
df = pd.read_csv(file_path)
# 2) Parse dates
try:
df[date_col] = pd.to_datetime(df[date_col])
except Exception:
return f"β Could not parse '{date_col}' as dates."
# 3) Coerce metric to numeric, drop invalid
df[value_col] = pd.to_numeric(df[value_col], errors="coerce")
series = df.set_index(date_col)[value_col].dropna()
if series.empty:
return f"β Column '{value_col}' has no valid numeric data after coercion."
# 4) Fit ARIMA
try:
model = ARIMA(series, order=(1, 1, 1))
model_fit = model.fit()
except Exception as e:
return f"β ARIMA fitting failed: {e}"
# 5) Forecast & plot
forecast = model_fit.forecast(steps=3)
fig = go.Figure()
fig.add_scatter(x=series.index, y=series, mode="lines", name=value_col)
fig.add_scatter(x=forecast.index, y=forecast, mode="lines", name="Forecast")
fig.update_layout(title=f"{value_col} Forecast", template="plotly_dark")
fig.write_image("forecast_plot.png") # goes into /tmp thanks to our monkey-patch
# 6) Return textual table
return forecast.to_frame(name="Forecast").to_string()
|