Spaces:
Sleeping
Sleeping
File size: 1,094 Bytes
010071f 3651f7b 010071f 3651f7b 1fadf44 3651f7b 1fadf44 010071f 1fadf44 3651f7b 1fadf44 3651f7b 1fadf44 3651f7b 010071f 1fadf44 3651f7b a9cd5f0 3651f7b 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 |
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()
|