Have you ever woken up feeling like a video game character stuck at 10% health? In the world of the Quantified Self, we don't have to guess why. Between HRV (Heart Rate Variability), sleep stages, and activity levels, our wearables are screaming data at us—we just need a way to listen.
In this tutorial, we’re going to build a personalized "Energy Bar" prediction model. By performing wearable data analysis using the Oura API and Fitbit API, we will train a Scikit-learn Random Forest model to predict your cognitive load capacity and fatigue levels for the day. Whether you're a biohacker or a developer looking to optimize your deep-work sessions, this project is for you. 🚀
The Architecture 🏗️
The goal is to create a pipeline that ingests raw time-series data from multiple sources, flattens it into features, and serves a prediction via a REST API.
graph TD
A[Oura Ring API] -->|Sleep & HRV| C[Data Collector]
B[Fitbit API] -->|Steps & Activity| C
C --> D{Feature Engineer}
D -->|Rolling Averages| E[Scikit-learn Random Forest]
D -->|Circadian Delta| E
E --> F[Energy Score: 0-100]
F --> G[FastAPI Endpoint]
G --> H[Mobile/Web Dashboard]
Prerequisites 🛠️
To follow along, you'll need:
- Python 3.9+
- Tech Stack:
Scikit-learn,FastAPI,Pandas, andRequests. - API Access: Developer tokens for Oura and Fitbit (don't worry, they have great sandbox modes!).
Step 1: Fetching the Bio-Data 🛰️
First, we need to grab our metrics. We are specifically looking for HRV (Heart Rate Variability)—the gold standard for autonomic nervous system recovery—and sleep efficiency.
import requests
import pandas as pd
def fetch_oura_metrics(access_token):
# Fetching sleep and readiness data
url = "https://api.ouraring.com/v2/usercollection/daily_sleep"
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.get(url, headers=headers)
# Process JSON to DataFrame
data = response.json()['data']
df = pd.DataFrame(data)
# Focus on HRV and Sleep Score
return df[['day', 'average_hrv', 'score']]
# Repeat similar logic for Fitbit activity data (Steps, Calories)
Step 2: Feature Engineering (The "Secret Sauce") đź§Ş
Machine learning models are only as good as the features you feed them. We don't just want "today's HRV." We want the delta—how much better or worse you are doing compared to your 7-day baseline.
def engineer_features(df):
# Calculate 7-day rolling average for HRV
df['hrv_baseline'] = df['average_hrv'].rolling(window=7).mean()
# Calculate the 'Recovery Ratio'
df['recovery_ratio'] = df['average_hrv'] / df['hrv_baseline']
# Interaction feature: Sleep Score * Activity Intensity
# (High activity + Low sleep = High fatigue)
df['fatigue_index'] = df['activity_score'] / (df['sleep_score'] + 1)
return df.dropna()
Step 3: Training the "Energy Bar" Model 🤖
We use a Random Forest Regressor because health data is often non-linear and contains outliers (like that one night you stayed up till 3 AM debugging a memory leak).
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
# Features: Recovery Ratio, Sleep Score, Previous Day Activity
X = df[['recovery_ratio', 'sleep_score', 'prev_day_steps']]
y = df['actual_perceived_energy'] # Your manual labels (1-10)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
print(f"Model Accuracy: {model.score(X_test, y_test)}")
Step 4: Deploying with FastAPI ⚡
Now, let's wrap this in a FastAPI service so your phone or desktop can query your "Energy Bar" status in real-time.
from fastapi import FastAPI
app = FastAPI()
@app.get("/predict-energy")
def get_energy():
current_data = fetch_latest_wearable_metrics()
features = engineer_features(current_data)
# Predict 0-100 score
prediction = model.predict(features)
return {
"energy_score": round(prediction[0] * 10, 2),
"status": "Go Hard" if prediction > 7 else "Take it Easy",
"recommendation": "Perfect day for deep work!" if prediction > 8 else "Rest and recover."
}
The "Official" Way to Scale 🏔️
Building a local script is a great start, but if you want to take this to a production-grade level—handling multi-user OAuth2, real-time data streaming, and more complex ensemble models—you'll need more advanced patterns.
For deep dives into production-ready health-tech architectures and advanced signal processing, I highly recommend checking out the technical breakdowns at WellAlly Blog. They cover the intersection of AI and wellness in a way that’s incredibly useful for developers building in this space. 🥑
Conclusion: Take Back Your Focus 🎯
By combining Scikit-learn with wearable data, we move from "feeling tired" to "knowing why." This model allows you to schedule your most demanding tasks when your physiological "Energy Bar" is actually full.
Next Steps for you:
- Connect your own Oura/Fitbit data.
- Start labeling your "Perceived Energy" daily for two weeks to create a training set.
- Deploy the FastAPI app to a Raspberry Pi or a cloud provider.
Are you tracking your bio-data yet? Drop a comment below and let me know what your "Energy Bar" looks like today! 👇
Top comments (0)