-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_statsmodels_cli.py
More file actions
567 lines (476 loc) Β· 26.6 KB
/
Copy pathexample_statsmodels_cli.py
File metadata and controls
567 lines (476 loc) Β· 26.6 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/env python3
"""
Statsmodels AIDS CLI with Colorful ASCII Visualizations for Marketing Managers
This module provides an interactive command-line interface for AIDS/QUAIDS
demand system estimation using statsmodels, with colorful ASCII charts and
marketing-friendly explanations.
Usage:
python example_statsmodels_cli.py
"""
import sys
import os
import time
import numpy as np
import pandas as pd
from typing import Dict, List, Tuple
from dataclasses import dataclass
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.layout import Layout
from rich.text import Text
from rich.align import Align
from rich import box
import warnings
warnings.filterwarnings('ignore')
# Add parent directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from example_statsmodels_aids import AIDSEstimator
# Color codes for ASCII art
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# Background colors
BG_RED = '\033[101m'
BG_GREEN = '\033[102m'
BG_YELLOW = '\033[103m'
BG_BLUE = '\033[104m'
BG_MAGENTA = '\033[105m'
BG_CYAN = '\033[106m'
class StatsmodelsCLI:
"""Interactive CLI for Statsmodels AIDS analysis with marketing focus."""
def __init__(self):
self.console = Console()
self.estimator = None
self.results = {}
def print_banner(self):
"""Print colorful banner."""
banner = f"""
{Colors.GREEN}{Colors.BOLD}
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β π AIDS/QUAIDS DEMAND SYSTEM FOR MARKETING MANAGERS π β
β β
β π Complete Product Portfolio Analysis β
β π Powered by Statsmodels Library β
β π‘ Understand how all products interact in your portfolio β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
{Colors.END}
"""
self.console.print(banner)
def print_method_explanation(self, method: str, description: str, business_value: str, real_world_example: str):
"""Print method explanation in marketing terms."""
panel = Panel(
f"[bold green]{method}[/bold green]\n\n"
f"[yellow]What it tells you:[/yellow] {description}\n\n"
f"[green]Why you care:[/green] {business_value}\n\n"
f"[blue]Real example:[/blue] {real_world_example}",
title="π What This Means for Your Business",
border_style="green",
padding=(1, 2)
)
self.console.print(panel)
def create_elasticity_matrix_chart(self, matrix: np.ndarray, products: List[str], title: str) -> str:
"""Create ASCII elasticity matrix chart."""
if matrix is None or len(products) == 0:
return f"{Colors.RED}No elasticity data available for {title}{Colors.END}"
chart = f"\n{Colors.BOLD}{Colors.GREEN}{title}{Colors.END}\n"
chart += f"{Colors.YELLOW}{'='*80}{Colors.END}\n"
# Header
header = f"{'Product':<15}"
for product in products:
header += f"{product[:8]:<12}"
chart += f"{Colors.CYAN}{header}{Colors.END}\n"
chart += f"{Colors.YELLOW}{'-'*80}{Colors.END}\n"
# Matrix rows
for i, product in enumerate(products):
row = f"{product[:12]:<15}"
for j in range(len(products)):
value = matrix[i, j]
if i == j: # Own-price elasticity
if value < -1.0:
color = Colors.RED
symbol = "π΄"
elif value < -0.5:
color = Colors.YELLOW
symbol = "π‘"
else:
color = Colors.GREEN
symbol = "π’"
else: # Cross-price elasticity
if value > 0.1:
color = Colors.GREEN
symbol = "π" # Substitutes
elif value < -0.1:
color = Colors.BLUE
symbol = "π" # Complements
else:
color = Colors.WHITE
symbol = "βͺ" # Independent
row += f"{color}{symbol} {value:>8.3f}{Colors.END} "
chart += row + "\n"
chart += f"{Colors.YELLOW}{'='*80}{Colors.END}\n"
# Business interpretation
chart += f"\n{Colors.BOLD}π How to Read This Matrix:{Colors.END}\n"
chart += f"{Colors.RED}π΄ High own-price sensitivity: Be careful raising prices{Colors.END}\n"
chart += f"{Colors.YELLOW}π‘ Moderate own-price sensitivity: You can adjust prices carefully{Colors.END}\n"
chart += f"{Colors.GREEN}π’ Low own-price sensitivity: You have pricing power{Colors.END}\n"
chart += f"{Colors.GREEN}π Substitutes: When you raise price of one, customers buy the other{Colors.END}\n"
chart += f"{Colors.BLUE}π Complements: When you raise price of one, customers buy less of both{Colors.END}\n"
chart += f"{Colors.WHITE}βͺ Independent: Products don't affect each other's sales{Colors.END}\n\n"
chart += f"{Colors.BOLD}π‘ Portfolio Strategy Tips:{Colors.END}\n"
chart += f"β’ Focus promotions on high-sensitivity products (π΄)\n"
chart += f"β’ Use substitute products (π) to capture customers from competitors\n"
chart += f"β’ Bundle complementary products (π) together for better value\n"
chart += f"β’ Independent products (βͺ) can be priced without worrying about cannibalization\n"
return chart
def create_income_effects_chart(self, results: Dict, title: str) -> str:
"""Create ASCII income effects chart."""
if not results:
return f"{Colors.RED}No income effects data available for {title}{Colors.END}"
chart = f"\n{Colors.BOLD}{Colors.GREEN}{title}{Colors.END}\n"
chart += f"{Colors.YELLOW}{'='*60}{Colors.END}\n"
# Income effects by product
if 'income_effects' in results:
income_effects = results['income_effects']
chart += f"{Colors.CYAN}Income Effects by Product:{Colors.END}\n"
for product, effect in income_effects.items():
if effect > 0.1:
color = Colors.GREEN
symbol = "π"
interpretation = "Luxury good - demand increases with income"
elif effect > 0:
color = Colors.YELLOW
symbol = "π"
interpretation = "Normal good - demand increases slightly with income"
elif effect > -0.1:
color = Colors.BLUE
symbol = "π"
interpretation = "Inferior good - demand decreases with income"
else:
color = Colors.RED
symbol = "π"
interpretation = "Strong inferior good - demand decreases significantly with income"
chart += f" {color}{symbol} {product}: {effect:>6.3f} - {interpretation}{Colors.END}\n"
# Engel curve analysis
if 'engel_curves' in results:
chart += f"\n{Colors.CYAN}Engel Curve Analysis:{Colors.END}\n"
engel_curves = results['engel_curves']
for product, curve_type in engel_curves.items():
if curve_type == 'quadratic':
color = Colors.MAGENTA
symbol = "π"
interpretation = "Non-linear relationship with income"
else:
color = Colors.CYAN
symbol = "π"
interpretation = "Linear relationship with income"
chart += f" {color}{symbol} {product}: {curve_type} - {interpretation}{Colors.END}\n"
chart += f"\n{Colors.BOLD}π‘ Business Insights:{Colors.END}\n"
chart += f"β’ Luxury goods (π): Target high-income customers with premium pricing\n"
chart += f"β’ Normal goods (π): Standard pricing strategies work well\n"
chart += f"β’ Inferior goods (π): Focus on value pricing and cost reduction\n"
chart += f"β’ Non-linear curves (π): Income effects change as customers get richer\n"
chart += f"{Colors.YELLOW}{'='*60}{Colors.END}\n"
return chart
def create_welfare_analysis_chart(self, results: Dict, title: str) -> str:
"""Create ASCII welfare analysis chart."""
if not results:
return f"{Colors.RED}No welfare analysis data available for {title}{Colors.END}"
chart = f"\n{Colors.BOLD}{Colors.GREEN}{title}{Colors.END}\n"
chart += f"{Colors.YELLOW}{'='*70}{Colors.END}\n"
# Welfare effects
if 'welfare_effects' in results:
welfare = results['welfare_effects']
chart += f"{Colors.CYAN}Consumer Welfare Impact:{Colors.END}\n"
if 'compensating_variation' in welfare:
cv = welfare['compensating_variation']
chart += f" Compensating Variation: ${cv:.2f}\n"
chart += f" (How much to pay customers to keep them as happy as before)\n"
if 'equivalent_variation' in welfare:
ev = welfare['equivalent_variation']
chart += f" Equivalent Variation: ${ev:.2f}\n"
chart += f" (How much customers would pay to avoid the price change)\n"
if 'consumer_surplus_change' in welfare:
cs = welfare['consumer_surplus_change']
chart += f" Consumer Surplus Change: ${cs:.2f}\n"
chart += f" (Net impact on customer satisfaction)\n"
# Share changes
if 'share_changes' in results:
chart += f"\n{Colors.CYAN}Market Share Changes:{Colors.END}\n"
share_changes = results['share_changes']
for product, change in share_changes.items():
if change > 0:
color = Colors.GREEN
symbol = "π"
elif change < 0:
color = Colors.RED
symbol = "π"
else:
color = Colors.WHITE
symbol = "β‘οΈ"
chart += f" {color}{symbol} {product}: {change:>+6.1f}pp{Colors.END}\n"
# Substitution effects
if 'substitution_effects' in results:
chart += f"\n{Colors.CYAN}Substitution Patterns:{Colors.END}\n"
substitution = results['substitution_effects']
for product, effect in substitution.items():
if effect > 0.1:
color = Colors.GREEN
symbol = "π"
interpretation = "Strong substitute"
elif effect > 0:
color = Colors.YELLOW
symbol = "π"
interpretation = "Weak substitute"
else:
color = Colors.BLUE
symbol = "π"
interpretation = "Complement"
chart += f" {color}{symbol} {product}: {effect:>6.3f} - {interpretation}{Colors.END}\n"
chart += f"\n{Colors.BOLD}π‘ Pricing Strategy Implications:{Colors.END}\n"
chart += f"β’ Large welfare losses: Consider smaller price increases\n"
chart += f"β’ Strong substitution: Competitors will gain market share\n"
chart += f"β’ Complementary effects: Bundle products together\n"
chart += f"β’ Monitor market share changes after price adjustments\n"
chart += f"{Colors.YELLOW}{'='*70}{Colors.END}\n"
return chart
def run_basic_aids_analysis(self):
"""Run basic AIDS analysis with visualizations."""
self.console.print("\n[bold green]π Running Basic AIDS Analysis...[/bold green]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Estimating AIDS demand system...", total=None)
try:
results = self.estimator.example_1_basic_aids()
progress.update(task, description="β
Basic AIDS analysis completed!")
# Display results
if 'elasticity_matrix' in results and 'products' in results:
matrix_chart = self.create_elasticity_matrix_chart(
results['elasticity_matrix'],
results['products'],
"π BASIC AIDS ELASTICITY MATRIX"
)
self.console.print(matrix_chart)
# Method explanation
self.print_method_explanation(
"Basic AIDS (Almost Ideal Demand System)",
"Shows you how all products in your portfolio interact with each other. It reveals which products compete, which complement each other, and how price changes affect the entire portfolio.",
"Gives you a complete picture of your product portfolio dynamics. You can see the full impact of pricing decisions across all products, not just individual ones.",
"The analysis might reveal: 'When you raise cola prices 10%, cola sales drop 12%, but water sales increase 8% (customers switch), and chips sales drop 2% (they're complements).' Now you understand the full portfolio impact."
)
self.results['basic_aids'] = results
except Exception as e:
self.console.print(f"[red]β Basic AIDS analysis failed: {e}[/red]")
def run_quaids_analysis(self):
"""Run QUAIDS analysis with visualizations."""
self.console.print("\n[bold green]π Running QUAIDS Analysis...[/bold green]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Estimating QUAIDS demand system...", total=None)
try:
results = self.estimator.example_2_quaids()
progress.update(task, description="β
QUAIDS analysis completed!")
# Display results
if 'elasticity_matrix' in results and 'products' in results:
matrix_chart = self.create_elasticity_matrix_chart(
results['elasticity_matrix'],
results['products'],
"π QUAIDS ELASTICITY MATRIX"
)
self.console.print(matrix_chart)
# Income effects
income_chart = self.create_income_effects_chart(results, "π° INCOME EFFECTS ANALYSIS")
self.console.print(income_chart)
# Method explanation
self.print_method_explanation(
"QUAIDS (Quadratic AIDS)",
"Like AIDS but captures how customer preferences change as they get richer or poorer. Some products become more attractive as income increases, others become less attractive.",
"Helps you understand how different income groups respond to your products and how to adjust your strategy as customer incomes change over time.",
"The analysis might reveal: 'High-income customers buy 20% more premium cola when their income increases 10%, but low-income customers buy 15% less when their income decreases 10%.' Now you can target different income groups differently."
)
self.results['quaids'] = results
except Exception as e:
self.console.print(f"[red]β QUAIDS analysis failed: {e}[/red]")
def run_demographic_analysis(self):
"""Run demographic analysis with visualizations."""
self.console.print("\n[bold green]π₯ Running Demographic Analysis...[/bold green]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Analyzing demographic effects...", total=None)
try:
results = self.estimator.example_4_demographics()
progress.update(task, description="β
Demographic analysis completed!")
# Display results
if 'elasticity_by_demographics' in results:
chart = f"\n{Colors.BOLD}{Colors.GREEN}π₯ DEMOGRAPHIC ELASTICITY ANALYSIS{Colors.END}\n"
chart += f"{Colors.YELLOW}{'='*60}{Colors.END}\n"
demo_elasticities = results['elasticity_by_demographics']
for demo_group, elasticities in demo_elasticities.items():
chart += f"\n{Colors.CYAN}{demo_group}:{Colors.END}\n"
for product, elasticity in elasticities.items():
if elasticity < -1.0:
color = Colors.RED
symbol = "π΄"
elif elasticity < -0.5:
color = Colors.YELLOW
symbol = "π‘"
else:
color = Colors.GREEN
symbol = "π’"
chart += f" {color}{symbol} {product}: {elasticity:>6.3f}{Colors.END}\n"
chart += f"{Colors.YELLOW}{'='*60}{Colors.END}\n"
self.console.print(chart)
# Method explanation
self.print_method_explanation(
"AIDS with Demographics",
"Shows you how different customer groups (by income, age, location) respond to price changes across your entire product portfolio.",
"Lets you create targeted pricing and marketing strategies for different customer segments. You can price differently for different demographic groups.",
"The analysis might reveal: 'High-income urban customers barely notice price increases on premium products (3% sales drop), but low-income rural customers are very sensitive (18% sales drop).' Now you can segment your pricing strategy."
)
self.results['demographics'] = results
except Exception as e:
self.console.print(f"[red]β Demographic analysis failed: {e}[/red]")
def run_welfare_analysis(self):
"""Run welfare analysis with visualizations."""
self.console.print("\n[bold green]π° Running Welfare Analysis...[/bold green]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Analyzing consumer welfare impact...", total=None)
try:
results = self.estimator.example_5_welfare()
progress.update(task, description="β
Welfare analysis completed!")
# Display results
welfare_chart = self.create_welfare_analysis_chart(results, "π° CONSUMER WELFARE ANALYSIS")
self.console.print(welfare_chart)
# Method explanation
self.print_method_explanation(
"Welfare Analysis with AIDS",
"Measures the impact of price changes on customer satisfaction and well-being. It shows how much customers lose or gain from your pricing decisions.",
"Helps you understand the customer impact of pricing decisions and balance profitability with customer satisfaction. Large welfare losses might indicate pricing that's too aggressive.",
"The analysis might reveal: 'A 10% price increase causes customers to lose $25 in satisfaction (welfare loss), but also causes 15% of customers to switch to competitors.' This helps you balance profit and customer retention."
)
self.results['welfare'] = results
except Exception as e:
self.console.print(f"[red]β Welfare analysis failed: {e}[/red]")
def create_summary_dashboard(self):
"""Create a summary dashboard of all results."""
if not self.results:
self.console.print("[red]No results to display in summary dashboard.[/red]")
return
# Create summary table
table = Table(title="π AIDS/QUAIDS ANALYSIS SUMMARY", box=box.ROUNDED)
table.add_column("Analysis", style="cyan", no_wrap=True)
table.add_column("Key Insight", style="magenta")
table.add_column("Business Impact", style="green")
insights = {
"Basic AIDS": "Complete portfolio elasticity matrix",
"QUAIDS": "Income effects and non-linear preferences",
"Demographics": "Segmented elasticity by customer groups",
"Welfare": "Consumer impact of pricing decisions"
}
impacts = {
"Basic AIDS": "Portfolio pricing optimization",
"QUAIDS": "Income-based pricing strategies",
"Demographics": "Segmented marketing and pricing",
"Welfare": "Customer satisfaction optimization"
}
for analysis in insights:
table.add_row(
analysis,
insights[analysis],
impacts[analysis]
)
self.console.print(table)
# Business recommendations
recommendations = Panel(
"[bold green]π‘ IMMEDIATE ACTION ITEMS:[/bold green]\n\n"
"[yellow]π― Portfolio Pricing:[/yellow]\n"
"β’ Use elasticity matrix to optimize all product prices together\n"
"β’ Focus promotions on high-sensitivity products\n"
"β’ Bundle complementary products for better value\n\n"
"[blue]π Customer Segmentation:[/blue]\n"
"β’ Price differently for different income groups\n"
"β’ Adjust pricing by demographic characteristics\n"
"β’ Monitor how preferences change with income\n\n"
"[magenta]π° Customer Satisfaction:[/magenta]\n"
"β’ Balance profitability with customer welfare\n"
"β’ Monitor substitution patterns after price changes\n"
"β’ Use welfare analysis to guide pricing decisions",
title="π― Your Next Steps",
border_style="green",
padding=(1, 2)
)
self.console.print(recommendations)
def run_interactive_analysis(self):
"""Run interactive analysis with user choices."""
self.print_banner()
# Initialize estimator
self.console.print("\n[bold blue]π Initializing AIDS/QUAIDS analysis...[/bold blue]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Loading data and models...", total=None)
self.estimator = AIDSEstimator()
progress.update(task, description="β
Ready for analysis!")
# Analysis menu
while True:
self.console.print("\n[bold cyan]π AIDS/QUAIDS ANALYSIS MENU[/bold cyan]")
self.console.print("1. π Basic AIDS (Portfolio Analysis)")
self.console.print("2. π QUAIDS (Income Effects)")
self.console.print("3. π₯ Demographics (Customer Segments)")
self.console.print("4. π° Welfare Analysis (Customer Impact)")
self.console.print("5. π View Summary Dashboard")
self.console.print("6. πͺ Exit")
choice = input("\n[bold yellow]Select analysis (1-6): [/bold yellow]").strip()
if choice == '1':
self.run_basic_aids_analysis()
elif choice == '2':
self.run_quaids_analysis()
elif choice == '3':
self.run_demographic_analysis()
elif choice == '4':
self.run_welfare_analysis()
elif choice == '5':
self.create_summary_dashboard()
elif choice == '6':
self.console.print("\n[bold green]π Thank you for using the AIDS/QUAIDS Analysis Tool![/bold green]")
break
else:
self.console.print("[red]β Invalid choice. Please select 1-6.[/red]")
input("\n[bold blue]Press Enter to continue...[/bold blue]")
def main():
"""Main function to run the CLI."""
try:
cli = StatsmodelsCLI()
cli.run_interactive_analysis()
except KeyboardInterrupt:
print(f"\n{Colors.YELLOW}π Analysis interrupted by user. Goodbye!{Colors.END}")
except Exception as e:
print(f"\n{Colors.RED}β Error: {e}[/red]")
if __name__ == "__main__":
main()