Daily Habit Forecasting Using Time-Series

import pandas as pd

import matplotlib.pyplot as plt

from statsmodels.tsa.holtwinters import ExponentialSmoothing


# --------------------------------------------------

# Load & Prepare Data

# --------------------------------------------------

def load_habit_data(csv_path, habit_name):

    df = pd.read_csv(csv_path)

    df["date"] = pd.to_datetime(df["date"])


    habit_df = df[df["habit"] == habit_name]

    habit_df = habit_df.sort_values("date")


    habit_df.set_index("date", inplace=True)

    ts = habit_df["completed"]


    return ts


# --------------------------------------------------

# Forecast Habit Completion

# --------------------------------------------------

def forecast_habit(ts, days=7):

    model = ExponentialSmoothing(

        ts,

        trend="add",

        seasonal=None,

        initialization_method="estimated"

    )


    fitted_model = model.fit()

    forecast = fitted_model.forecast(days)


    return fitted_model, forecast


# --------------------------------------------------

# Risk Analysis

# --------------------------------------------------

def habit_risk_score(forecast):

    avg_completion = forecast.mean()


    if avg_completion < 0.4:

        return "🚨 High Risk (likely to break)"

    elif avg_completion < 0.7:

        return "⚠️ Medium Risk"

    else:

        return "✅ Low Risk (stable habit)"


# --------------------------------------------------

# Visualization

# --------------------------------------------------

def plot_forecast(ts, forecast, habit_name):

    plt.figure(figsize=(10, 5))


    plt.plot(ts.index, ts.values, label="Past Completion", marker="o")

    plt.plot(forecast.index, forecast.values, label="Forecast", linestyle="--", marker="x")


    plt.ylim(-0.1, 1.1)

    plt.ylabel("Habit Completed (1=yes, 0=no)")

    plt.title(f"Habit Forecast: {habit_name}")

    plt.legend()

    plt.grid(True)


    plt.show()


# --------------------------------------------------

# MAIN

# --------------------------------------------------

if __name__ == "__main__":

    csv_file = input("Enter CSV file path: ").strip()

    habit = input("Enter habit name (case-sensitive): ").strip()


    ts = load_habit_data(csv_file, habit)


    model, forecast = forecast_habit(ts, days=7)


    risk = habit_risk_score(forecast)


    print("\nšŸ“Š HABIT FORECAST REPORT")

    print("------------------------")

    print(f"Habit: {habit}")

    print(f"Next 7-day average completion: {forecast.mean():.2f}")

    print(f"Risk Level: {risk}")


    plot_forecast(ts, forecast, habit)


No comments: