Checking 5 different apps to get a business overview? Here's how to pull everything into one Python script that gives you the full picture in seconds.
The Problem: Business Data Is Everywhere
Your revenue is in Stripe. Your email stats are in Mailchimp. Customer count is in your database. Traffic is in Google Analytics. You're toggling between tabs for a picture that's always incomplete.
Python can pull all of this together. One script you run in the morning that gives you everything.
A Simple Business Metrics Aggregator
from dataclasses import dataclass
from datetime import datetime, timedelta
import httpx, sqlite3, json
@dataclass
class DailyMetrics:
date: str
revenue: float
new_customers: int
active_users: int
email_opens: int
email_clicks: int
page_views: int
class MetricsAggregator:
def __init__(self):
self.db = sqlite3.connect('metrics.db')
self.setup_db()
def setup_db(self):
self.db.execute('''CREATE TABLE IF NOT EXISTS daily_metrics (
date TEXT PRIMARY KEY, revenue REAL, new_customers INTEGER,
active_users INTEGER, email_opens INTEGER, email_clicks INTEGER,
page_views INTEGER
)''')
self.db.commit()
def save(self, metrics: DailyMetrics):
self.db.execute(
'INSERT OR REPLACE INTO daily_metrics VALUES (?,?,?,?,?,?,?)',
(metrics.date, metrics.revenue, metrics.new_customers,
metrics.active_users, metrics.email_opens, metrics.email_clicks,
metrics.page_views)
)
self.db.commit()
def get_previous(self, days_ago: int = 1):
date = (datetime.now() - timedelta(days=days_ago)).strftime('%Y-%m-%d')
row = self.db.execute('SELECT * FROM daily_metrics WHERE date = ?', (date,)).fetchone()
return DailyMetrics(*row) if row else None
Pulling Revenue From Stripe
class StripeMetrics:
def __init__(self, api_key: str):
self.client = httpx.Client(auth=(api_key, ''), base_url='https://api.stripe.com/v1/')
def get_daily_revenue(self, date: datetime = None) -> float:
date = date or datetime.now()
start = int(datetime(date.year, date.month, date.day).timestamp())
charges = self.client.get('charges', params={
'created[gte]': start,
'created[lt]': start + 86400,
'limit': 100
}).json().get('data', [])
return sum(c['amount'] / 100 for c in charges if c['paid'] and not c['refunded'])
def get_new_customers(self) -> int:
start = int(datetime.now().replace(hour=0, minute=0, second=0).timestamp())
customers = self.client.get('customers', params={'created[gte]': start, 'limit': 100}).json()
return len(customers.get('data', []))
Email Stats From Mailchimp
class MailchimpMetrics:
def __init__(self, api_key: str, server_prefix: str):
self.client = httpx.Client(
auth=('anystring', api_key),
base_url=f'https://{server_prefix}.api.mailchimp.com/3.0/'
)
def get_recent_campaign_stats(self, days: int = 1) -> dict:
campaigns = self.client.get('campaigns', params={
'since_send_time': (datetime.now() - timedelta(days=days)).isoformat(),
'status': 'sent', 'count': 10
}).json().get('campaigns', [])
totals = {'opens': 0, 'clicks': 0}
for c in campaigns:
report = self.client.get(f"reports/{c['id']}").json()
totals['opens'] += report.get('opens', {}).get('unique_opens', 0)
totals['clicks'] += report.get('clicks', {}).get('unique_clicks', 0)
return totals
The Full Daily Report
def run_daily_report():
aggregator = MetricsAggregator()
stripe = StripeMetrics(api_key='sk_live_...')
mailchimp = MailchimpMetrics(api_key='...', server_prefix='us1')
today = DailyMetrics(
date=datetime.now().strftime('%Y-%m-%d'),
revenue=stripe.get_daily_revenue(),
new_customers=stripe.get_new_customers(),
active_users=0, # Add your DB query
email_opens=mailchimp.get_recent_campaign_stats().get('opens', 0),
email_clicks=mailchimp.get_recent_campaign_stats().get('clicks', 0),
page_views=0, # Add GA API call
)
yesterday = aggregator.get_previous(1)
aggregator.save(today)
report = f"""
📊 Daily Business Report — {today.date}
💰 Revenue: ${today.revenue:.2f}
{f' Yesterday: ${yesterday.revenue:.2f} ({today.revenue - yesterday.revenue:+.2f})' if yesterday else ''}
👥 New customers: {today.new_customers}
📧 Email opens: {today.email_opens} | Clicks: {today.email_clicks}
"""
print(report)
return report
if __name__ == "__main__":
run_daily_report()
Auto-Schedule It
# crontab -e
0 8 * * * /usr/bin/python3 /home/user/daily_report.py | mail -s "Daily Report $(date +%Y-%m-%d)" you@email.com
Or send to Slack:
def send_to_slack(report: str, webhook_url: str):
httpx.post(webhook_url, json={"text": report})
What You Stop Doing
- Logging into Stripe to check revenue ❌
- Opening Mailchimp for email stats ❌
- Toggling between 5 dashboards ❌
- Missing trends because you forgot to check ❌
Everything arrives at 8am in one message.
Pre-built and ready: The Python Business Automation Toolkit includes this metrics dashboard plus 11 other automation scripts for invoicing, inventory, email, and more.
Top comments (0)