BizIntel_AI / tools /forecaster.py
mgbam's picture
Update tools/forecaster.py
9db6dea verified
raw
history blame
1.53 kB
# 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()