Spaces:
Sleeping
Sleeping
File size: 1,556 Bytes
010071f a9cd5f0 010071f a9cd5f0 1fadf44 a9cd5f0 1fadf44 010071f 1fadf44 010071f 1fadf44 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 46 47 48 49 50 51 |
import pandas as pd
import plotly.graph_objects as go
from statsmodels.tsa.arima.model import ARIMA
def forecast_tool(file_path: str, date_col: str) -> str:
"""
Forecast next 3 periods of 'Sales'. Returns text summary and saves forecast_plot.png.
"""
df = pd.read_csv(file_path)
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)
# Interactive Plotly forecast with confidence interval
conf_int = model_fit.get_forecast(steps=3).conf_int()
future_index = forecast.index
fig = go.Figure()
fig.add_scatter(x=df.index, y=df["Sales"], mode="lines", name="Sales")
fig.add_scatter(x=future_index, y=forecast, mode="lines", name="Forecast")
fig.add_scatter(
x=future_index,
y=conf_int.iloc[:, 0],
mode="lines",
fill=None,
line=dict(width=0),
showlegend=False,
)
fig.add_scatter(
x=future_index,
y=conf_int.iloc[:, 1],
mode="lines",
fill="tonexty",
name="95% CI",
line=dict(width=0),
)
fig.update_layout(title="Sales Forecast", template="plotly_dark")
fig.write_image("forecast_plot.png")
return forecast.to_frame(name="Forecast").to_string()
|