BizIntel_AI / tools /forecaster.py
mgbam's picture
Update tools/forecaster.py
3651f7b verified
raw
history blame
1.09 kB
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 and returns forecast DataFrame as text.
"""
df = pd.read_csv(file_path)
try:
df[date_col] = pd.to_datetime(df[date_col])
except Exception:
return f"❌ '{date_col}' not parseable as dates."
if value_col not in df.columns:
return f"❌ '{value_col}' column missing."
df.set_index(date_col, inplace=True)
model = ARIMA(df[value_col], order=(1, 1, 1))
model_fit = model.fit()
forecast = model_fit.forecast(steps=3)
# Plot
fig = go.Figure()
fig.add_scatter(x=df.index, y=df[value_col], 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")
return forecast.to_frame(name="Forecast").to_string()