File size: 1,450 Bytes
010071f
 
 
 
1fadf44
 
 
 
 
 
 
 
010071f
1fadf44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
010071f
 
1fadf44
 
 
010071f
1fadf44
 
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
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()