Back to Courses

Complete AI Mastery Course

Published

A comprehensive 10-module journey from AI foundations to advanced agentic systems and entrepreneurship. Master prompt engineering, automation, coding with AI, and build a future-proof career.

Progress

0%

Pricing & Access

Students pay this to access the course. Leave "Paid course" off for free/enrolled-only access.

CPD Accreditation

Required for CPD — what a learner can do after the course. One outcome per line.

CPD hours (auto-computed)

0 CPD Hours

CPD status

Not submitted

Submitting sends this course for CPD verification. Once approved and the fee is paid, the CPD logo appears on this course's certificates.

Interactive15 min

Project 3: Automating a Personal Habit Tracker

Automate a personal habit tracker end to end, covering data collection and storage, Pandas-based analysis, optional predictive modeling, and automation via scripts or tools like IFTTT and Zapier.

{"contentFormat":"slides.v1","completion":{"requireAllSlides":true,"requireQuiz":true},"slides":[{"kind":"title","eyebrow":"Module 8: Portfolio Projects","title":"Project 3: Automating a Personal Habit Tracker","body":"Build an end-to-end AI-powered habit tracker that collects data, analyzes patterns, predicts adherence, and automates logging. By the end of this project, you'll have a working system you can use daily.","outcomes":["Design a data collection pipeline for personal habits","Analyze habit data with Pandas and visualize trends","Train a logistic regression model to predict habit completion","Automate data logging and reminders with Python scripts"],"narration":"Welcome to Project 3: Automating a Personal Habit Tracker. In this capstone, you'll apply everything you've learned to build a practical tool that tracks your habits, uncovers patterns, and even predicts your future adherence. Let's get started."},{"kind":"content","heading":"Project Overview & Architecture","body":"Your habit tracker will consist of four components:\n\n1. Data Collection: Log habits manually or via automated triggers (e.g., location, time).\n2. Data Storage: Use a local SQLite database for privacy and portability.\n3. Analysis & Visualization: Compute streaks, completion rates, and trends using Pandas and Matplotlib.\n4. Predictive Model: Train a logistic regression model (scikit-learn) to forecast daily habit completion.\n\nTech Stack (2026 best practices):\n- Python 3.11+\n- Pandas, Matplotlib, scikit-learn\n- SQLite3 (built-in)\n- Schedule library for automation\n\nAll data stays on your machine — no cloud dependencies required.","callout":{"variant":"note","title":"Privacy First","text":"Habit data is personal. By storing everything locally in SQLite, you avoid sending sensitive information to third parties. If you later want to sync across devices, consider encrypted cloud storage like Cryptomator."},"narration":"Let's outline the architecture. You'll collect data, store it in a local SQLite database, analyze it with Pandas, and optionally build a logistic regression model to predict your habit completion. All code runs on your machine, keeping your data private."},{"kind":"content","heading":"Step 1: Define Habits & Data Schema","body":"Choose 2-3 specific, measurable habits. Examples:\n- Exercise: 30 minutes of cardio\n- Reading: 20 pages of a book\n- Meditation: 10 minutes\n\nDatabase Schema (SQLite):\n

sql\nCREATE TABLE habits (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    habit_name TEXT NOT NULL,\n    date TEXT NOT NULL,\n    completed INTEGER NOT NULL,  -- 1 or 0\n    notes TEXT,\n    timestamp TEXT DEFAULT CURRENT_TIMESTAMP\n);\n
\n\nWhy SQLite?\n- Zero configuration, file-based, no server needed.\n- Easy to query and backup.\n- Works across Windows, macOS, Linux.\n\nGlobal Example:\n- Kenya: Track water consumption (liters) for health.\n- India: Track daily yoga practice duration.\n- Brazil: Track Portuguese vocabulary study sessions.","callout":{"variant":"exercise","title":"Your Turn","text":"Write down 3 habits you want to track. For each, define a clear completion criterion (e.g., 'ran 5 km' not 'exercise'). Then create the SQLite table using the schema above."},"narration":"Start by defining your habits and setting up the database. Use the SQL schema provided to create a table that stores each habit entry. Remember to keep your criteria measurable."},{"kind":"content","heading":"Step 2: Data Collection & Logging Script","body":"Write a Python script to log habit completions. Use sqlite3 and datetime.\n\n
python\nimport sqlite3\nfrom datetime import date\n\ndef log_habit(habit_name, completed, notes=\"\"):\n    conn = sqlite3.connect('habits.db')\n    c = conn.cursor()\n    c.execute('''INSERT INTO habits (habit_name, date, completed, notes)\n                 VALUES (?, ?, ?, ?)''',\n              (habit_name, date.today().isoformat(), int(completed), notes))\n    conn.commit()\n    conn.close()\n    print(f\"Logged: {habit_name} - {'Done' if completed else 'Missed'}\")\n\n# Example usage\nlog_habit(\"Exercise\", True, \"Morning run 5km\")\nlog_habit(\"Reading\", False)\n
\n\nAutomation Tip: Use the schedule library to run this script daily at a set time.\n
python\nimport schedule\nimport time\n\ndef morning_reminder():\n    print(\"Time to log your habits!\")\n    # You can integrate with a notification system here\n\nschedule.every().day.at(\"20:00\").do(morning_reminder)\n\nwhile True:\n    schedule.run_pending()\n    time.sleep(60)\n
\n\nSecurity: Never hardcode sensitive data. Use environment variables if needed.","callout":{"variant":"tip","title":"Automate Logging","text":"You can extend the script to automatically log habits from external sources: e.g., if you use a fitness watch, export data and parse it. For simplicity, start with manual logging via command line."},"narration":"Now write the logging function. It inserts a new row into the database each time you complete or miss a habit. You can also set up a daily reminder using the schedule library."},{"kind":"content","heading":"Step 3: Analyze Habit Patterns with Pandas","body":"Load your data and compute key metrics.\n\n
python\nimport pandas as pd\nimport sqlite3\n\nconn = sqlite3.connect('habits.db')\ndf = pd.read_sql_query(\"SELECT  FROM habits\", conn)\nconn.close()\n\n# Completion rate per habit\ncompletion_rate = df.groupby('habit_name')['completed'].mean()\nprint(\"Completion Rates:\")\nprint(completion_rate)\n\n# Streak calculation (consecutive days of completion)\ndef compute_streak(series):\n    # series is boolean, sorted by date\n    streak = 0\n    for val in series:\n        if val:\n            streak += 1\n        else:\n            break\n    return streak\n\nfor habit in df['habit_name'].unique():\n    habit_data = df[df['habit_name'] == habit].sort_values('date')\n    streak = compute_streak(habit_data['completed'].values)\n    print(f\"{habit}: current streak = {streak} days\")\n
\n\nVisualization:\n
python\nimport matplotlib.pyplot as plt\n\n# Monthly completion rate\nmonthly = df.copy()\nmonthly['month'] = pd.to_datetime(monthly['date']).dt.to_period('M')\nmonthly_rate = monthly.groupby(['habit_name', 'month'])['completed'].mean().unstack(0)\nmonthly_rate.plot(kind='bar')\nplt.title('Monthly Habit Completion Rates')\nplt.ylabel('Rate')\nplt.tight_layout()\nplt.show()\n
\n\nInsight: Look for patterns — are you more likely to exercise on weekdays? Do you read more on weekends?","callout":{"variant":"insight","title":"Pattern Discovery","text":"Use the analysis to adjust your schedule. For example, if you notice low exercise completion on Fridays, try shifting your workout to Thursday."},"narration":"With data collected, use Pandas to calculate completion rates and streaks. Visualize monthly trends to spot patterns. This analysis helps you understand your behavior and make informed adjustments."},{"kind":"content","heading":"Step 4: Predictive Modeling with Logistic Regression","body":"Predict whether you'll complete a habit tomorrow based on features like day of week, past completion, and recent streak.\n\nFeature Engineering:\n
python\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n\n# Prepare data for one habit, e.g., 'Exercise'\ndf_habit = df[df['habit_name'] == 'Exercise'].copy()\ndf_habit['date'] = pd.to_datetime(df_habit['date'])\ndf_habit['day_of_week'] = df_habit['date'].dt.dayofweek  # Monday=0\ndf_habit['prev_completed'] = df_habit['completed'].shift(1).fillna(0).astype(int)\ndf_habit['streak'] = df_habit['completed'].groupby((df_habit['completed'] != df_habit['completed'].shift()).cumsum()).cumsum()\ndf_habit['streak'] = df_habit['streak'].shift(1).fillna(0).astype(int)\n\n# Drop rows with NaN (first row)\ndf_habit = df_habit.dropna()\n\nX = df_habit[['day_of_week', 'prev_completed', 'streak']]\ny = df_habit['completed']\n\n# Train/test split (temporal order)\nsplit = int(0.8  len(df_habit))\nX_train, X_test = X.iloc[:split], X.iloc[split:]\ny_train, y_test = y.iloc[:split], y.iloc[split:]\n\nmodel = LogisticRegression()\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\naccuracy = accuracy_score(y_test, predictions)\nprint(f\"Model accuracy: {accuracy:.2f}\")\n\n# Predict tomorrow\ntomorrow = pd.DataFrame({\n    'day_of_week': [pd.Timestamp.today().weekday()],\n    'prev_completed': [df_habit['completed'].iloc[-1]],\n    'streak': [compute_streak(df_habit['completed'].values)]\n})\nprob = model.predict_proba(tomorrow)[0][1]\nprint(f\"Probability of completing tomorrow: {prob:.2%}\")\n
\n\nInterpretation: The model uses day of week, yesterday's completion, and current streak to estimate your likelihood. A probability >0.5 suggests you're likely to complete.","callout":{"variant":"warning","title":"Data Requirements","text":"Logistic regression needs at least a few weeks of data to be meaningful. Start tracking now and revisit the model after 30 days. Also, ensure your classes are balanced (both completed and missed days)."},"narration":"Now let's build a predictive model. Using logistic regression, we'll forecast your habit completion based on day of week, previous day's completion, and streak length. This gives you a personalized probability for tomorrow."},{"kind":"content","heading":"Step 5: Automation & Integration","body":"Fully automate your habit tracker with scheduled scripts and optional integrations.\n\nDaily Logging Reminder:\n
python\nimport schedule\nimport time\n\ndef log_habit_prompt():\n    # This could send a desktop notification or SMS\n    print(\"Reminder: Log your habits for today!\")\n    # Or use notify-py for cross-platform notifications\n\nschedule.every().day.at(\"21:00\").do(log_habit_prompt)\n\nwhile True:\n    schedule.run_pending()\n    time.sleep(60)\n
\n\nAuto-log from External Sources (Example: Apple Health Export):\nIf you export Apple Health data as XML, parse it with xml.etree.ElementTree and insert steps or workouts into your habits table.\n\nDashboard Generation:\nCreate a weekly summary script that emails you a PDF report.\n
python\n# Pseudocode\nimport smtplib\n# Generate plot and save as PDF\n# Send email via SMTP (use environment variables for credentials)\n
\n\nCross-Platform Notifications:\nUse plyer library for desktop notifications.\n
python\nfrom plyer import notification\nnotification.notify(title=\"Habit Tracker\", message=\"Time to log your habits!\", timeout=10)\n
","callout":{"variant":"tip","title":"Start Simple","text":"Don't over-automate initially. Get comfortable with manual logging and analysis first, then add one automation at a time."},"narration":"Automate reminders and data collection. Use the schedule library for daily prompts, and optionally integrate with health apps or send weekly reports. Remember to start simple and gradually add complexity."},{"kind":"content","heading":"What Good Looks Like: Checklist","body":"Before considering your project complete, verify the following:\n\n| Criteria | Description |\n|----------|-------------|\n| Data Storage | SQLite database with at least 30 days of data for 2+ habits |\n| Logging Script | Python function to log habit completion with date, habit name, and completion status |\n| Analysis | Pandas script that computes completion rates and streaks per habit |\n| Visualization | At least one chart (e.g., monthly completion bar chart) |\n| Predictive Model | Logistic regression model trained on your data, with accuracy reported |\n| Automation | Scheduled reminder or auto-logging (even simple print statement counts) |\n| Privacy | All data stored locally; no external API calls unless user explicitly opts in |\n| Documentation | README explaining how to run the scripts and interpret results |\n\nStretch Goals:\n- Deploy a simple web dashboard using Streamlit.\n- Add more features to the model (e.g., weather, sleep hours).\n- Share anonymized data for a group challenge (with consent).","callout":{"variant":"insight","title":"Real-World Impact","text":"A user in Nigeria used a similar tracker to improve medication adherence by 40% over 3 months. The key was the predictive model alerting them on low-probability days."},"narration":"Here's a checklist to evaluate your project. Ensure you have a working database, logging, analysis, visualization, and a predictive model. Aim for at least 30 days of data. Then consider stretch goals like a web dashboard."},{"kind":"quiz","heading":"Knowledge Check","questions":[{"question":"Which database is recommended for storing habit data locally in this project?","options":["MySQL","PostgreSQL","SQLite","MongoDB"],"questionId":"cmrf73kcj0031pd271q11j1v2"},{"question":"What is the purpose of the 'streak' feature in the logistic regression model?","options":["To measure the total number of habits tracked","To capture the number of consecutive days the habit was completed prior to the current day","To calculate the average completion time","To identify the most popular habit"],"questionId":"cmrf73kcj0032pd270a2ej1ey"},{"question":"Why is it important to store habit data locally rather than on a cloud server?","options":["Cloud servers are slower","To protect personal privacy and avoid sharing sensitive data","Local storage is cheaper","Cloud services are not available globally"],"questionId":"cmrf73kcj0033pd27kqr4ey9y"}],"narration":"Let's test your understanding with a quick quiz. Answer these three questions to reinforce key concepts from the project.","quizId":"qz_cmk7lnk37003jg4p80jtad99s"},{"kind":"summary","heading":"Project Recap & Next Steps","takeaways":["You built a complete habit tracker with data collection, analysis, and prediction.","SQLite provides a private, portable storage solution for personal data.","Pandas enables powerful pattern analysis, including streaks and completion rates.","Logistic regression can predict habit adherence using day-of-week, previous completion, and streak.","Automation via schedule library reduces manual effort and keeps you consistent.","Always prioritize data privacy — keep sensitive data local unless necessary."],"narration":"Congratulations! You've built an end-to-end personal habit tracker. You now have a tool that not only logs your habits but also analyzes patterns and predicts future behavior. Keep iterating — add new features, refine your model, and most importantly, use it to improve your daily life."}]}