petter2025 commited on
Commit
115eb63
·
verified ·
1 Parent(s): 5d54760

Update core/calculators.py

Browse files
Files changed (1) hide show
  1. core/calculators.py +297 -71
core/calculators.py CHANGED
@@ -1,87 +1,230 @@
1
  """
2
- Enhanced ROI calculators and business logic
3
  """
4
 
5
- from typing import Dict
6
- from core.data_models import IncidentScenario
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  class EnhancedROICalculator:
9
- """Investor-grade ROI calculator with sensitivity analysis"""
 
 
 
 
 
10
 
11
  def calculate_comprehensive_roi(self, monthly_incidents: int,
12
- avg_impact: float, team_size: int) -> Dict:
13
- """Calculate multi-scenario ROI analysis"""
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # Base scenario (realistic)
15
- base = self._calculate_scenario(monthly_incidents, avg_impact, team_size,
16
- savings_rate=0.82, efficiency_gain=0.85)
 
 
 
17
 
18
  # Best case (aggressive adoption)
19
- best = self._calculate_scenario(monthly_incidents, avg_impact, team_size,
20
- savings_rate=0.92, efficiency_gain=0.92)
 
 
 
21
 
22
  # Worst case (conservative)
23
- worst = self._calculate_scenario(monthly_incidents, avg_impact, team_size,
24
- savings_rate=0.72, efficiency_gain=0.78)
 
 
 
25
 
26
  # Generate recommendation
27
- recommendation = self._get_recommendation(base['roi_multiplier'])
 
 
 
28
 
29
  return {
30
  "summary": {
31
- "your_annual_impact": f"${base['annual_impact']:,.0f}",
32
- "potential_savings": f"${base['savings']:,.0f}",
33
- "enterprise_cost": f"${base['enterprise_cost']:,.0f}",
34
- "roi_multiplier": f"{base['roi_multiplier']:.1f}×",
35
- "payback_months": f"{base['payback_months']:.1f}",
36
- "annual_roi_percentage": f"{base['roi_percentage']:.0f}%"
 
 
37
  },
38
  "scenarios": {
39
  "base_case": {
40
- "roi": f"{base['roi_multiplier']:.1f}×",
41
- "payback": f"{base['payback_months']:.1f} months",
42
- "confidence": "High"
 
 
43
  },
44
  "best_case": {
45
- "roi": f"{best['roi_multiplier']:.1f}×",
46
- "payback": f"{best['payback_months']:.1f} months",
47
- "confidence": "Medium"
 
 
48
  },
49
  "worst_case": {
50
- "roi": f"{worst['roi_multiplier']:.1f}×",
51
- "payback": f"{worst['payback_months']:.1f} months",
52
- "confidence": "Medium"
 
 
53
  }
54
  },
55
- "comparison": {
56
- "industry_average": "5.2× ROI",
57
- "top_performers": "8.7× ROI",
58
- "your_position": f"Top {self._get_percentile(base['roi_multiplier'])}%"
59
- },
60
- "recommendation": recommendation
 
61
  }
62
 
63
- def _calculate_scenario(self, monthly_incidents: int, avg_impact: float,
64
- team_size: int, savings_rate: float,
65
- efficiency_gain: float) -> Dict:
66
- """Calculate specific scenario"""
67
- annual_impact = monthly_incidents * 12 * avg_impact
68
- enterprise_cost = team_size * 125000 # Conservative $125k/engineer
69
- savings = annual_impact * savings_rate * efficiency_gain
70
-
71
- roi_multiplier = savings / enterprise_cost if enterprise_cost > 0 else 0
72
- roi_percentage = (roi_multiplier - 1) * 100
73
- payback_months = (enterprise_cost / (savings / 12)) if savings > 0 else 0
74
 
75
- return {
76
- "annual_impact": annual_impact,
77
- "enterprise_cost": enterprise_cost,
78
- "savings": savings,
79
- "roi_multiplier": roi_multiplier,
80
- "roi_percentage": roi_percentage,
81
- "payback_months": payback_months
82
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- def _get_recommendation(self, roi_multiplier: float) -> Dict:
85
  """Get recommendation based on ROI"""
86
  if roi_multiplier >= 5.0:
87
  return {
@@ -89,15 +232,38 @@ class EnhancedROICalculator:
89
  "reason": "Exceptional ROI (>5×) with quick payback",
90
  "timeline": "30-day implementation",
91
  "expected_value": ">$1M annual savings",
92
- "priority": "High"
 
 
 
 
 
93
  }
94
- elif roi_multiplier >= 2.0:
95
  return {
96
  "action": "✅ Implement ARF Enterprise",
97
- "reason": "Strong ROI (2-5×) with operational benefits",
98
  "timeline": "60-day phased rollout",
99
  "expected_value": ">$500K annual savings",
100
- "priority": "Medium"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  }
102
  else:
103
  return {
@@ -105,18 +271,78 @@ class EnhancedROICalculator:
105
  "reason": "Validate value before Enterprise investment",
106
  "timeline": "14-day evaluation",
107
  "expected_value": "Operational insights + clear upgrade path",
108
- "priority": "Low"
 
 
 
 
 
109
  }
110
 
111
- def _get_percentile(self, roi_multiplier: float) -> str:
112
- """Calculate percentile vs industry"""
113
- if roi_multiplier >= 8.0:
114
- return "10"
115
- elif roi_multiplier >= 5.0:
116
- return "25"
117
- elif roi_multiplier >= 3.0:
118
- return "50"
119
- elif roi_multiplier >= 2.0:
120
- return "75"
121
- else:
122
- return "90"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Enhanced ROI calculators and business logic with Monte Carlo simulation
3
  """
4
 
5
+ from typing import Dict, List, Any, Tuple
6
+ import numpy as np
7
+ import logging
8
+ from dataclasses import dataclass
9
+ from enum import Enum
10
+ from config.settings import settings
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class ROIConfidence(Enum):
16
+ """Confidence levels for ROI predictions"""
17
+ HIGH = "High"
18
+ MEDIUM = "Medium"
19
+ LOW = "Low"
20
+
21
+
22
+ @dataclass
23
+ class ROIScenarioResult:
24
+ """Result of a single ROI scenario calculation"""
25
+ scenario_name: str
26
+ annual_impact: float
27
+ enterprise_cost: float
28
+ savings: float
29
+ roi_multiplier: float
30
+ roi_percentage: float
31
+ payback_months: float
32
+ confidence: ROIConfidence
33
+
34
+ def to_dict(self) -> Dict[str, Any]:
35
+ """Convert to dictionary"""
36
+ return {
37
+ "scenario_name": self.scenario_name,
38
+ "annual_impact": f"${self.annual_impact:,.0f}",
39
+ "enterprise_cost": f"${self.enterprise_cost:,.0f}",
40
+ "savings": f"${self.savings:,.0f}",
41
+ "roi_multiplier": f"{self.roi_multiplier:.1f}×",
42
+ "roi_percentage": f"{self.roi_percentage:.0f}%",
43
+ "payback_months": f"{self.payback_months:.1f}",
44
+ "confidence": self.confidence.value
45
+ }
46
+
47
 
48
  class EnhancedROICalculator:
49
+ """Investor-grade ROI calculator with Monte Carlo simulation"""
50
+
51
+ def __init__(self):
52
+ self.engineer_hourly_rate = settings.engineer_hourly_rate
53
+ self.engineer_annual_cost = settings.engineer_annual_cost
54
+ self.default_savings_rate = settings.default_savings_rate
55
 
56
  def calculate_comprehensive_roi(self, monthly_incidents: int,
57
+ avg_impact: float, team_size: int) -> Dict[str, Any]:
58
+ """
59
+ Calculate multi-scenario ROI analysis with Monte Carlo simulation
60
+
61
+ Args:
62
+ monthly_incidents: Average incidents per month
63
+ avg_impact: Average revenue impact per incident
64
+ team_size: Number of engineers
65
+
66
+ Returns:
67
+ Comprehensive ROI analysis
68
+ """
69
+ logger.info(f"Calculating ROI: incidents={monthly_incidents}, "
70
+ f"impact=${avg_impact:,}, team={team_size}")
71
+
72
  # Base scenario (realistic)
73
+ base = self._calculate_with_monte_carlo(
74
+ monthly_incidents, avg_impact, team_size,
75
+ savings_rate_mean=0.82, savings_rate_std=0.05,
76
+ efficiency_mean=0.85, efficiency_std=0.03
77
+ )
78
 
79
  # Best case (aggressive adoption)
80
+ best = self._calculate_with_monte_carlo(
81
+ monthly_incidents, avg_impact, team_size,
82
+ savings_rate_mean=0.92, savings_rate_std=0.03,
83
+ efficiency_mean=0.92, efficiency_std=0.02
84
+ )
85
 
86
  # Worst case (conservative)
87
+ worst = self._calculate_with_monte_carlo(
88
+ monthly_incidents, avg_impact, team_size,
89
+ savings_rate_mean=0.72, savings_rate_std=0.07,
90
+ efficiency_mean=0.78, efficiency_std=0.05
91
+ )
92
 
93
  # Generate recommendation
94
+ recommendation = self._get_recommendation(base.mean_roi)
95
+
96
+ # Calculate industry comparison
97
+ comparison = self._get_industry_comparison(base.mean_roi)
98
 
99
  return {
100
  "summary": {
101
+ "your_annual_impact": f"${base.mean_annual_impact:,.0f}",
102
+ "potential_savings": f"${base.mean_savings:,.0f}",
103
+ "enterprise_cost": f"${base.enterprise_cost:,.0f}",
104
+ "roi_multiplier": f"{base.mean_roi:.1f}×",
105
+ "payback_months": f"{base.mean_payback:.1f}",
106
+ "annual_roi_percentage": f"{base.mean_roi_percentage:.0f}%",
107
+ "monte_carlo_simulations": 1000,
108
+ "confidence_interval": f"{base.roi_ci[0]:.1f}× - {base.roi_ci[1]:.1f}×"
109
  },
110
  "scenarios": {
111
  "base_case": {
112
+ "roi": f"{base.mean_roi:.1f}×",
113
+ "payback": f"{base.mean_payback:.1f} months",
114
+ "confidence": base.confidence.value,
115
+ "ci_low": f"{base.roi_ci[0]:.1f}×",
116
+ "ci_high": f"{base.roi_ci[1]:.1f}×"
117
  },
118
  "best_case": {
119
+ "roi": f"{best.mean_roi:.1f}×",
120
+ "payback": f"{best.mean_payback:.1f} months",
121
+ "confidence": best.confidence.value,
122
+ "ci_low": f"{best.roi_ci[0]:.1f}×",
123
+ "ci_high": f"{best.roi_ci[1]:.1f}×"
124
  },
125
  "worst_case": {
126
+ "roi": f"{worst.mean_roi:.1f}×",
127
+ "payback": f"{worst.mean_payback:.1f} months",
128
+ "confidence": worst.confidence.value,
129
+ "ci_low": f"{worst.roi_ci[0]:.1f}×",
130
+ "ci_high": f"{worst.roi_ci[1]:.1f}×"
131
  }
132
  },
133
+ "comparison": comparison,
134
+ "recommendation": recommendation,
135
+ "monte_carlo_stats": {
136
+ "base_roi_std": f"{base.roi_std:.2f}",
137
+ "best_roi_std": f"{best.roi_std:.2f}",
138
+ "worst_roi_std": f"{worst.roi_std:.2f}"
139
+ }
140
  }
141
 
142
+ def _calculate_with_monte_carlo(self, monthly_incidents: int, avg_impact: float,
143
+ team_size: int, savings_rate_mean: float,
144
+ savings_rate_std: float, efficiency_mean: float,
145
+ efficiency_std: float) -> 'MonteCarloResult':
146
+ """
147
+ Run Monte Carlo simulation for ROI calculation
 
 
 
 
 
148
 
149
+ Returns:
150
+ MonteCarloResult with statistics
151
+ """
152
+ np.random.seed(42) # For reproducible results
153
+
154
+ n_simulations = 1000
155
+
156
+ # Generate random samples with normal distribution
157
+ savings_rates = np.random.normal(
158
+ savings_rate_mean, savings_rate_std, n_simulations
159
+ )
160
+ efficiencies = np.random.normal(
161
+ efficiency_mean, efficiency_std, n_simulations
162
+ )
163
+
164
+ # Clip to reasonable bounds
165
+ savings_rates = np.clip(savings_rates, 0.5, 0.95)
166
+ efficiencies = np.clip(efficiencies, 0.5, 0.95)
167
+
168
+ # Calculate for each simulation
169
+ annual_impacts = monthly_incidents * 12 * avg_impact
170
+ enterprise_costs = team_size * self.engineer_annual_cost
171
+
172
+ savings_list = []
173
+ roi_list = []
174
+ roi_percentage_list = []
175
+ payback_list = []
176
+
177
+ for i in range(n_simulations):
178
+ savings = annual_impacts * savings_rates[i] * efficiencies[i]
179
+ roi = savings / enterprise_costs if enterprise_costs > 0 else 0
180
+ roi_percentage = (roi - 1) * 100
181
+ payback = (enterprise_costs / (savings / 12)) if savings > 0 else 0
182
+
183
+ savings_list.append(savings)
184
+ roi_list.append(roi)
185
+ roi_percentage_list.append(roi_percentage)
186
+ payback_list.append(payback)
187
+
188
+ # Convert to numpy arrays for statistics
189
+ savings_arr = np.array(savings_list)
190
+ roi_arr = np.array(roi_list)
191
+ roi_percentage_arr = np.array(roi_percentage_list)
192
+ payback_arr = np.array(payback_list)
193
+
194
+ # Calculate statistics
195
+ mean_savings = np.mean(savings_arr)
196
+ mean_roi = np.mean(roi_arr)
197
+ mean_roi_percentage = np.mean(roi_percentage_arr)
198
+ mean_payback = np.mean(payback_arr)
199
+
200
+ roi_std = np.std(roi_arr)
201
+ roi_ci = (
202
+ np.percentile(roi_arr, 25),
203
+ np.percentile(roi_arr, 75)
204
+ )
205
+
206
+ # Determine confidence level
207
+ if roi_std / mean_roi < 0.1: # Low relative standard deviation
208
+ confidence = ROIConfidence.HIGH
209
+ elif roi_std / mean_roi < 0.2:
210
+ confidence = ROIConfidence.MEDIUM
211
+ else:
212
+ confidence = ROIConfidence.LOW
213
+
214
+ return MonteCarloResult(
215
+ mean_annual_impact=annual_impacts,
216
+ enterprise_cost=enterprise_costs,
217
+ mean_savings=mean_savings,
218
+ mean_roi=mean_roi,
219
+ mean_roi_percentage=mean_roi_percentage,
220
+ mean_payback=mean_payback,
221
+ roi_std=roi_std,
222
+ roi_ci=roi_ci,
223
+ confidence=confidence,
224
+ n_simulations=n_simulations
225
+ )
226
 
227
+ def _get_recommendation(self, roi_multiplier: float) -> Dict[str, str]:
228
  """Get recommendation based on ROI"""
229
  if roi_multiplier >= 5.0:
230
  return {
 
232
  "reason": "Exceptional ROI (>5×) with quick payback",
233
  "timeline": "30-day implementation",
234
  "expected_value": ">$1M annual savings",
235
+ "priority": "High",
236
+ "next_steps": [
237
+ "Schedule enterprise demo",
238
+ "Request custom ROI analysis",
239
+ "Start 30-day trial"
240
+ ]
241
  }
242
+ elif roi_multiplier >= 3.0:
243
  return {
244
  "action": "✅ Implement ARF Enterprise",
245
+ "reason": "Strong ROI (3-5×) with operational benefits",
246
  "timeline": "60-day phased rollout",
247
  "expected_value": ">$500K annual savings",
248
+ "priority": "Medium",
249
+ "next_steps": [
250
+ "Evaluate OSS edition",
251
+ "Run pilot with 2-3 services",
252
+ "Measure initial impact"
253
+ ]
254
+ }
255
+ elif roi_multiplier >= 2.0:
256
+ return {
257
+ "action": "📊 Evaluate ARF Enterprise",
258
+ "reason": "Positive ROI (2-3×) with learning benefits",
259
+ "timeline": "90-day evaluation",
260
+ "expected_value": ">$250K annual savings",
261
+ "priority": "Medium-Low",
262
+ "next_steps": [
263
+ "Start with OSS edition",
264
+ "Document baseline metrics",
265
+ "Identify pilot use cases"
266
+ ]
267
  }
268
  else:
269
  return {
 
271
  "reason": "Validate value before Enterprise investment",
272
  "timeline": "14-day evaluation",
273
  "expected_value": "Operational insights + clear upgrade path",
274
+ "priority": "Low",
275
+ "next_steps": [
276
+ "Install OSS edition",
277
+ "Analyze 2-3 incident scenarios",
278
+ "Document potential improvements"
279
+ ]
280
  }
281
 
282
+ def _get_percentile(self, roi_multiplier: float) -> int:
283
+ """Calculate percentile vs industry benchmarks"""
284
+ benchmarks = [
285
+ (10.0, 5), # Top 5% at 10× ROI
286
+ (8.0, 10), # Top 10% at 8× ROI
287
+ (5.0, 25), # Top 25% at 5× ROI
288
+ (3.0, 50), # Top 50% at 3× ROI
289
+ (2.0, 75), # Top 75% at 2× ROI
290
+ (1.0, 90) # Top 90% at 1× ROI
291
+ ]
292
+
293
+ for threshold, percentile in benchmarks:
294
+ if roi_multiplier >= threshold:
295
+ return percentile
296
+
297
+ return 95 # Bottom 5%
298
+
299
+ def _get_industry_comparison(self, roi_multiplier: float) -> Dict[str, str]:
300
+ """Get industry comparison metrics"""
301
+ percentile = self._get_percentile(roi_multiplier)
302
+
303
+ return {
304
+ "industry_average": "5.2× ROI",
305
+ "top_performers": "8.7× ROI",
306
+ "your_position": f"Top {percentile}%",
307
+ "benchmark_analysis": "Above industry average" if roi_multiplier >= 5.2 else "Below industry average",
308
+ "improvement_potential": f"{max(0, 8.7 - roi_multiplier):.1f}× additional ROI possible"
309
+ }
310
+
311
+ def calculate_simple_roi(self, monthly_incidents: int,
312
+ avg_impact: float, team_size: int) -> Dict[str, Any]:
313
+ """
314
+ Simple ROI calculation without Monte Carlo
315
+
316
+ For backward compatibility
317
+ """
318
+ result = self._calculate_with_monte_carlo(
319
+ monthly_incidents, avg_impact, team_size,
320
+ savings_rate_mean=self.default_savings_rate,
321
+ savings_rate_std=0.05,
322
+ efficiency_mean=0.85,
323
+ efficiency_std=0.03
324
+ )
325
+
326
+ return {
327
+ "annual_impact": result.mean_annual_impact,
328
+ "enterprise_cost": result.enterprise_cost,
329
+ "savings": result.mean_savings,
330
+ "roi_multiplier": result.mean_roi,
331
+ "roi_percentage": result.mean_roi_percentage,
332
+ "payback_months": result.mean_payback
333
+ }
334
+
335
+
336
+ @dataclass
337
+ class MonteCarloResult:
338
+ """Result of Monte Carlo simulation"""
339
+ mean_annual_impact: float
340
+ enterprise_cost: float
341
+ mean_savings: float
342
+ mean_roi: float
343
+ mean_roi_percentage: float
344
+ mean_payback: float
345
+ roi_std: float
346
+ roi_ci: Tuple[float, float]
347
+ confidence: ROIConfidence
348
+ n_simulations: int