-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard_api.py
More file actions
201 lines (162 loc) · 6.18 KB
/
dashboard_api.py
File metadata and controls
201 lines (162 loc) · 6.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python3
"""
Flask Backend API for Interactive CAC-LTV Dashboard
Serves data endpoints for real-time dashboard interactions
"""
from flask import Flask, jsonify, render_template, request
from flask_cors import CORS
import pandas as pd
import numpy as np
import json
app = Flask(__name__)
CORS(app) # Enable CORS for frontend-backend communication
# Global data storage
dashboard_data = None
def load_and_process_data():
"""Load and process CAC-LTV data for API consumption"""
global dashboard_data
# Load data
df = pd.read_csv('cac_ltv_model.csv')
# Calculate metrics
df['total_cac'] = df['marketing_spend'] + df['sales_spend']
df['arpu'] = df['monthly_subscription_fee']
df['gross_margin'] = 0.75
df['churn_rate'] = np.where(
df['churn_month'].notna(),
1 / df['churn_month'],
0.08
)
df['churn_rate_adj'] = df['churn_rate'].replace(0, 0.0001)
df['ltv'] = (df['arpu'] * df['gross_margin']) / df['churn_rate_adj']
dashboard_data = df
return df
@app.route('/')
def dashboard():
"""Serve the main dashboard HTML page"""
return render_template('dashboard.html')
@app.route('/api/summary')
def get_summary_metrics():
"""API endpoint: Get overall summary metrics"""
df = dashboard_data
summary = {
'total_customers': len(df),
'avg_ltv': round(df['ltv'].mean(), 2),
'avg_cac': round(df['total_cac'].mean(), 2),
'ltv_cac_ratio': round(df['ltv'].mean() / df['total_cac'].mean(), 2),
'retention_rate': round(((len(df) - df['churn_month'].notna().sum()) / len(df)) * 100, 1),
'total_regions': df['region'].nunique(),
'total_channels': df['acquisition_channel'].nunique()
}
return jsonify(summary)
@app.route('/api/channels')
def get_channel_metrics():
"""API endpoint: Get metrics by acquisition channel"""
df = dashboard_data
channel_metrics = df.groupby('acquisition_channel').agg({
'ltv': 'mean',
'total_cac': 'mean',
'customer_id': 'count'
}).round(2)
channel_metrics['ltv_cac_ratio'] = (channel_metrics['ltv'] / channel_metrics['total_cac']).round(2)
channel_metrics = channel_metrics.sort_values('ltv_cac_ratio', ascending=False)
result = {
'channels': channel_metrics.index.tolist(),
'ltv': channel_metrics['ltv'].tolist(),
'cac': channel_metrics['total_cac'].tolist(),
'ratios': channel_metrics['ltv_cac_ratio'].tolist(),
'customers': channel_metrics['customer_id'].tolist()
}
return jsonify(result)
@app.route('/api/regions')
def get_regional_metrics():
"""API endpoint: Get metrics by region"""
df = dashboard_data
regional_metrics = df.groupby('region').agg({
'arpu': 'mean',
'total_cac': 'mean',
'ltv': 'mean',
'customer_id': 'count'
}).round(2)
regional_metrics = regional_metrics.sort_values('arpu', ascending=False)
result = {
'regions': regional_metrics.index.tolist(),
'arpu': regional_metrics['arpu'].tolist(),
'cac': regional_metrics['total_cac'].tolist(),
'ltv': regional_metrics['ltv'].tolist(),
'customers': regional_metrics['customer_id'].tolist()
}
return jsonify(result)
@app.route('/api/cohorts')
def get_cohort_data():
"""API endpoint: Get cohort retention data"""
df = dashboard_data.copy()
# Create cohort analysis
df['signup_date'] = pd.to_datetime(df['signup_date'])
df['cohort_month'] = df['signup_date'].dt.to_period('M')
cohort_data = []
for cohort, group in df.groupby('cohort_month'):
initial_customers = len(group)
avg_churn = group['churn_rate'].mean()
retention_curve = []
for month in range(13):
retention_rate = (1 - avg_churn) ** month
retained_customers = int(initial_customers * retention_rate)
retention_curve.append(retained_customers)
cohort_data.append({
'cohort': str(cohort),
'initial_size': initial_customers,
'retention_curve': retention_curve
})
return jsonify(cohort_data)
@app.route('/api/filter')
def get_filtered_data():
"""API endpoint: Get filtered data based on user selections"""
df = dashboard_data
# Get filter parameters
selected_channels = request.args.getlist('channels')
selected_regions = request.args.getlist('regions')
# Apply filters
if selected_channels:
df = df[df['acquisition_channel'].isin(selected_channels)]
if selected_regions:
df = df[df['region'].isin(selected_regions)]
# Calculate filtered metrics
filtered_summary = {
'total_customers': len(df),
'avg_ltv': round(df['ltv'].mean(), 2) if len(df) > 0 else 0,
'avg_cac': round(df['total_cac'].mean(), 2) if len(df) > 0 else 0,
'avg_arpu': round(df['arpu'].mean(), 2) if len(df) > 0 else 0
}
return jsonify(filtered_summary)
@app.route('/api/trends')
def get_trend_data():
"""API endpoint: Get time-based trends"""
df = dashboard_data.copy()
df['signup_date'] = pd.to_datetime(df['signup_date'])
df['month_year'] = df['signup_date'].dt.to_period('M')
trends = df.groupby('month_year').agg({
'customer_id': 'count',
'ltv': 'mean',
'total_cac': 'mean'
}).round(2)
result = {
'months': [str(month) for month in trends.index],
'new_customers': trends['customer_id'].tolist(),
'avg_ltv': trends['ltv'].tolist(),
'avg_cac': trends['total_cac'].tolist()
}
return jsonify(result)
if __name__ == '__main__':
print("🚀 Starting CAC-LTV Interactive Dashboard Server...")
print("📊 Loading and processing data...")
load_and_process_data()
print("✅ Data loaded successfully!")
print("🌐 Dashboard will be available at: http://localhost:5001")
print("📡 API endpoints available:")
print(" - /api/summary (Overall metrics)")
print(" - /api/channels (Channel analysis)")
print(" - /api/regions (Regional data)")
print(" - /api/cohorts (Retention analysis)")
print(" - /api/filter (Dynamic filtering)")
print(" - /api/trends (Time trends)")
app.run(debug=True, host='0.0.0.0', port=5001)