BizIntel_AI / tools /forecaster.py
mgbam's picture
Update tools/forecaster.py
1fadf44 verified
raw
history blame
1.45 kB
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
def forecast_tool(file_path: str, date_col: str | None = None) -> str:
"""
Forecast the next 3 periods of the 'Sales' column.
• If date_col is provided, use it.
• Otherwise auto‑detect the first column that can be parsed as dates.
Returns human‑readable summary and saves 'forecast_plot.png'.
"""
df = pd.read_csv(file_path)
# Auto‑detect date column if not specified
if date_col is None:
for col in df.columns:
try:
pd.to_datetime(df[col])
date_col = col
break
except Exception:
continue
if date_col is None:
return "❌ No parseable date column found."
# Parse the date column
try:
df[date_col] = pd.to_datetime(df[date_col])
except Exception:
return f"❌ Column '{date_col}' cannot be parsed as dates."
if "Sales" not in df.columns:
return "❌ CSV must contain a 'Sales' column."
df.set_index(date_col, inplace=True)
model = ARIMA(df["Sales"], order=(1, 1, 1))
model_fit = model.fit()
forecast = model_fit.forecast(steps=3)
forecast_df = pd.DataFrame(forecast, columns=["Forecast"])
forecast_df.plot(title="Sales Forecast", figsize=(10, 6))
plt.savefig("forecast_plot.png")
return forecast_df.to_string()