import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, date
import io
# Page config
st.set_page_config(
page_title="Fitness Tracker",
page_icon="🏃♂️",
layout="wide",
initial_sidebar_state="expanded"
)
# Data file
DATA_FILE = "fitness_data.csv"
@st.cache_data
def load_data():
try:
df = pd.read_csv(DATA_FILE)
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)
return df
except FileNotFoundError:
return pd.DataFrame(columns=['date', 'activity', 'duration_min', 'calories', 'weight_kg', 'notes'])
def save_data(df):
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
df.to_csv(DATA_FILE, index=False)
# Load data
df = load_data()
# Sidebar
st.sidebar.title("🏃♂️ Fitness Tracker")
st.sidebar.info("Track your workouts and visualize progress!")
if st.sidebar.button("💾 Refresh Data"):
st.cache_data.clear()
st.rerun()
if st.sidebar.button("🗑️ Clear All Data", type="primary", help="Warning: This deletes all data!"):
if st.sidebar.checkbox("Confirm deletion"):
import os
if os.path.exists(DATA_FILE):
os.remove(DATA_FILE)
st.cache_data.clear()
st.rerun()
st.sidebar.success("Data cleared!")
# Tabs
tab1, tab2, tab3, tab4 = st.tabs(["➕ Add Workout", "📊 View Data", "📈 Visualizations", "📋 Summary & Export"])
with tab1:
st.header("Add a New Workout")
col1, col2 = st.columns(2)
with col1:
workout_date = st.date_input("Date", value=date.today(), key="add_date")
with col2:
activity = st.selectbox(
"Activity",
["Run", "Bike", "Weights", "Yoga", "Swim", "Walk", "Other"],
key="add_activity"
)
col3, col4 = st.columns(2)
with col3:
duration = st.number_input("Duration (minutes)", min_value=0.0, value=30.0, step=5.0, key="add_duration")
with col4:
calories = st.number_input("Calories Burned", min_value=0.0, value=300.0, step=10.0, key="add_calories")
col5, col6 = st.columns(2)
with col5:
weight = st.number_input("Body Weight (kg)", min_value=0.0, value=70.0, step=0.5, key="add_weight")
with col6:
notes = st.text_input("Notes", placeholder="e.g., 5km run, felt great!", key="add_notes")
if st.button("✅ Add Workout", type="primary"):
new_entry = pd.DataFrame({
'date': [pd.to_datetime(workout_date)],
'activity': [activity],
'duration_min': [duration],
'calories': [calories],
'weight_kg': [weight],
'notes': [notes]
})
global df
df = pd.concat([df, new_entry], ignore_index=True)
df = df.sort_values('date').reset_index(drop=True)
save_data(df)
st.cache_data.clear()
st.success("Workout added successfully! 🎉")
st.balloons()
st.rerun()
with tab2:
st.header("All Workouts")
if not df.empty:
st.dataframe(df, use_container_width=True, hide_index=True)
else:
st.info("👆 Add your first workout above!")
with tab3:
st.header("Visualizations")
if df.empty:
st.warning("No data yet. Add some workouts to see charts!")
else:
# Calories over time
col1, col2 = st.columns(2)
with col1:
fig_calories = px.line(df, x='date', y='calories', title='Calories Burned Over Time',
markers=True)
fig_calories.update_layout(height=400)
st.plotly_chart(fig_calories, use_container_width=True)
with col2:
# Total calories by activity
activity_totals = df.groupby('activity')['calories'].sum().reset_index()
fig_activity = px.bar(activity_totals, x='activity', y='calories',
title='Total Calories by Activity')
fig_activity.update_layout(height=400)
st.plotly_chart(fig_activity, use_container_width=True)
# Weight over time (only if data exists)
weight_data = df[df['weight_kg'] > 0]
if not weight_data.empty:
col3, col4 = st.columns(2)
with col3:
fig_weight = px.line(weight_data, x='date', y='weight_kg', title='Body Weight Over Time',
markers=True)
fig_weight.update_layout(height=400)
st.plotly_chart(fig_weight, use_container_width=True)
with col4:
# Average duration by activity
avg_duration = df.groupby('activity')['duration_min'].mean().reset_index()
fig_duration = px.bar(avg_duration, x='activity', y='duration_min',
title='Average Duration by Activity (min)')
fig_duration.update_layout(height=400)
st.plotly_chart(fig_duration, use_container_width=True)
with tab4:
st.header("Summary")
if df.empty:
st.info("No data yet.")
else:
col1, col2, col3, col4 = st.columns(4)
total_workouts = len(df)
total_calories = df['calories'].sum()
total_duration = df['duration_min'].sum()
avg_calories = df['calories'].mean()
col1.metric("Total Workouts", total_workouts)
col2.metric("Total Calories", f"{total_calories:,.0f}")
col3.metric("Total Duration", f"{total_duration:.0f} min")
col4.metric("Avg Calories/Workout", f"{avg_calories:.0f}")
st.markdown("---")
st.subheader("Export Data")
csv_buffer = io.StringIO()
df.to_csv(csv_buffer, index=False)
st.download_button(
label="📥 Download CSV",
data=csv_buffer.getvalue(),
file_name="fitness_data.csv",
mime="text/csv"
)
# Footer
st.markdown("---")
st.markdown("*Built with ❤️ using Streamlit, Pandas & Plotly*")
🚀 How to Run This App
-
Install dependencies:
pip install streamlit pandas plotly
-
Save the code to a file named fitness_tracker.py.
-
Run the app:
streamlit run fitness_tracker.py
-
Open your browser to http://localhost:8501 and start tracking!
✨ Features
- Add workouts with date, activity, duration, calories, weight, and notes.
- View raw data in a table.
- Interactive charts: Calories over time, by activity, weight progress, durations.
- Persistent storage in
fitness_data.csv (auto-saves).
- Summary metrics and CSV export.
- Clear data option (with confirmation).
- Mobile-friendly web app.
Your data stays local on your machine. Track runs, gym sessions, yoga—whatever keeps you fit! 💪 If you need customizations, let me know.