import pandas as pd import streamlit as st import matplotlib.pyplot as plt from pathlib import Path st.set_page_config(page_title="SARIMA Sales Forecast", page_icon="📈", layout="wide") BASE_DIR = Path(__file__).resolve().parent FORECAST_CSV_DEFAULT = BASE_DIR / "prediction2.csv" TS_CSV_DEFAULT = BASE_DIR / "monthly_sales_ts.csv" def load_forecast_csv(path: Path) -> pd.DataFrame: df = pd.read_csv(path) # Handle index column saved by pandas (e.g., "Unnamed: 0") if df.columns[0].lower().startswith("unnamed"): df = df.rename(columns={df.columns[0]: "date"}) # If there's a date column, set it as index if "date" in df.columns: df["date"] = pd.to_datetime(df["date"]) df = df.set_index("date") # Normalize column names df.columns = [c.strip().lower() for c in df.columns] # Ensure expected columns exist required = {"forecast"} if not required.issubset(set(df.columns)): raise ValueError( "prediction2.csv must contain at least a 'forecast' column " "(and optionally 'lower_ci' and 'upper_ci')." ) return df def load_ts_csv(path: Path) -> pd.Series: df = pd.read_csv(path) if df.columns[0].lower().startswith("unnamed"): df = df.rename(columns={df.columns[0]: "date"}) if "date" not in df.columns: raise ValueError("src/monthly_sales_ts.csv should have a 'date' column.") df["date"] = pd.to_datetime(df["date"]) df = df.set_index("date") # Find a reasonable sales column sales_col = None for c in df.columns: if c.strip().lower() in ["sales", "monthly_sales", "value", "y"]: sales_col = c break if sales_col is None: sales_col = df.columns[0] # fallback return df[sales_col].astype(float) def plot_forecast(ts_hist: pd.Series | None, forecast_df: pd.DataFrame): fig = plt.figure(figsize=(12, 5)) if ts_hist is not None and len(ts_hist) > 0: plt.plot(ts_hist.index, ts_hist.values, label="Historical Sales") plt.plot(forecast_df.index, forecast_df["forecast"].values, label="Forecast") if "lower_ci" in forecast_df.columns and "upper_ci" in forecast_df.columns: plt.fill_between( forecast_df.index, forecast_df["lower_ci"].values, forecast_df["upper_ci"].values, alpha=0.25, label="Confidence Interval", ) plt.title("Monthly Sales Forecast (SARIMA)") plt.xlabel("Date") plt.ylabel("Sales") plt.legend() st.pyplot(fig) st.title("📈 Monthly Sales Forecast (SARIMA)") st.write( "This app loads your saved forecast file from `src/prediction2.csv` and visualizes " "the forecast with optional confidence intervals." ) with st.sidebar: st.header("⚙️ Settings") steps = st.slider("Forecast horizon (rows to show)", min_value=3, max_value=24, value=8, step=1) st.markdown("### 📂 Data Source (default: `src/`)") use_upload = st.checkbox("Upload CSV instead of using src/ files", value=False) uploaded_forecast = None uploaded_ts = None if use_upload: uploaded_forecast = st.file_uploader("Upload prediction2.csv", type=["csv"]) uploaded_ts = st.file_uploader("Upload monthly_sales_ts.csv (optional)", type=["csv"]) show_table = st.checkbox("Show forecast table", value=True) # --- Load forecast dataframe --- try: if use_upload and uploaded_forecast is not None: forecast_df = pd.read_csv(uploaded_forecast) if forecast_df.columns[0].lower().startswith("unnamed"): forecast_df = forecast_df.rename(columns={forecast_df.columns[0]: "date"}) if "date" in forecast_df.columns: forecast_df["date"] = pd.to_datetime(forecast_df["date"]) forecast_df = forecast_df.set_index("date") forecast_df.columns = [c.strip().lower() for c in forecast_df.columns] else: if not FORECAST_CSV_DEFAULT.exists(): st.error( "Missing file: `src/prediction2.csv`.\n\n" "Please upload it to your HuggingFace repo inside the `src/` folder." ) st.stop() forecast_df = load_forecast_csv(FORECAST_CSV_DEFAULT) except Exception as e: st.error(f"Could not load forecast CSV: {e}") st.stop() # Show only first N forecast rows forecast_df = forecast_df.iloc[:steps] # --- Load historical series (optional) --- ts_hist = None try: if use_upload and uploaded_ts is not None: ts_df = pd.read_csv(uploaded_ts) if ts_df.columns[0].lower().startswith("unnamed"): ts_df = ts_df.rename(columns={ts_df.columns[0]: "date"}) ts_df["date"] = pd.to_datetime(ts_df["date"]) ts_df = ts_df.set_index("date") # find sales col candidates = [c for c in ts_df.columns if c.strip().lower() in ["sales", "monthly_sales", "value", "y"]] sales_col = candidates[0] if candidates else ts_df.columns[0] ts_hist = ts_df[sales_col].astype(float) else: if TS_CSV_DEFAULT.exists(): ts_hist = load_ts_csv(TS_CSV_DEFAULT) except Exception: ts_hist = None # do not crash if optional file is broken # --- UI output --- if show_table: st.subheader("📄 Forecast Table") st.dataframe(forecast_df, use_container_width=True) st.subheader("📉 Forecast Plot") plot_forecast(ts_hist, forecast_df) st.download_button( "⬇️ Download forecast CSV", data=forecast_df.to_csv().encode("utf-8"), file_name="forecast_output.csv", mime="text/csv", ) st.caption("Files expected in repo: `src/prediction2.csv` (required) and `src/monthly_sales_ts.csv` (optional).")