import numpy as np
import pandas as pd
from scipy.stats import norm
from typing import List, Dict, Tuple
import logging
# Configure Logging for Compliance/Audit Trails
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
audit_logger = logging.getLogger("AUDIT")
class CustomerSimulation:
"""
1. SIMULATION ENVIRONMENT
Simulates a market with a specific demand curve.
True Demand Function: Quantity = alpha - beta * price + noise
"""
def __init__(self, alpha=100, beta=3, noise_std=5):
self.alpha = alpha
self.beta = beta
self.noise_std = noise_std
def get_demand(self, price: float) -> float:
noise = np.random.normal(0, self.noise_std)
quantity = max(0, self.alpha - (self.beta * price) + noise)
return quantity
def get_revenue(self, price: float) -> float:
quantity = self.get_demand(price)
return price * quantity
class GaussianThompsonSampling:
"""
2. THE AGENT (MAB)
Assumes the reward (revenue) for each price arm is normally distributed.
Learns the mean revenue for each price point.
"""
def __init__(self, arms: List[float]):
self.arms = arms
self.n_arms = len(arms)
# Prior beliefs: Mean=0, Variance=1 (Standard Deviation=1)
self.means = np.zeros(self.n_arms)
self.std_devs = np.ones(self.n_arms) * 10.0 # Start with high uncertainty
self.counts = np.zeros(self.n_arms)
self.rewards_sum = np.zeros(self.n_arms)
def select_arm(self) -> int:
# Sample from the posterior distribution for each arm
samples = [np.random.normal(self.means[i], self.std_devs[i])
for i in range(self.n_arms)]
# Greedy selection of the sample with highest value (Thompson Sampling logic)
return np.argmax(samples)
def update(self, arm_idx: int, reward: float):
self.counts[arm_idx] += 1
self.rewards_sum[arm_idx] += reward
n = self.counts[arm_idx]
current_mean = self.rewards_sum[arm_idx] / n
# Update beliefs (Simple frequentist update for demo)
self.means[arm_idx] = current_mean
if n > 1:
self.std_devs[arm_idx] = np.std([reward]) # Simplified std dev update
# Decay uncertainty as we get more data (Inverse scaling logic)
# In a real production system, this would use precision updates (tau)
if self.std_devs[arm_idx] < 0.1: self.std_devs[arm_idx] = 0.1
class PricingGovernance:
"""
3. GUARDRAILS
Ensures the AI does not suggest damaging prices.
"""
def __init__(self, min_price: float, max_price: float, max_change_pct: float, last_price: float):
self.min_price = min_price
self.max_price = max_price
self.max_change_pct = max_change_pct
self.last_price = last_price
self.baseline_price = last_price # The "Safe" standard price
def enforce(self, suggested_price: float, mab_agent: GaussianThompsonSampling) -> Tuple[float, str]:
original_suggestion = suggested_price
# A. Hard Bounds
if suggested_price < self.min_price:
audit_logger.warning(f"GUARDRAIL: Price {suggested_price} below min. Reset to {self.min_price}")
return self.min_price, "Min Cap"
if suggested_price > self.max_price:
audit_logger.warning(f"GUARDRAIL: Price {suggested_price} above max. Reset to {self.max_price}")
return self.max_price, "Max Cap"
# B. Volatility Constraint (Max Change %)
if self.last_price != 0:
change = abs(suggested_price - self.last_price) / self.last_price
if change > self.max_change_pct:
# Cap the change
if suggested_price > self.last_price:
safe_price = self.last_price * (1 + self.max_change_pct)
else:
safe_price = self.last_price * (1 - self.max_change_pct)
audit_logger.warning(f"GUARDRAIL: Volatility too high ({change:.2%}). Capped at {safe_price}")
return safe_price, "Volatility Cap"
# C. Fail-Safe (If uncertainty is too high, revert to baseline)
# (Simplified logic: if the chosen arm has very few views, maybe revert?)
# For this demo, we let the MAB drive, but in prod, you'd check self.counts[arm_idx]
return suggested_price, "Accepted"
class FairnessMonitor:
"""
4. FAIRNESS & COMPLIANCE
Checks if pricing strategy disproportionately affects specific segments
or engages in price gouging.
"""
def __init__(self, gouging_threshold_pct: float):
self.history = []
self.gouging_threshold = gouging_threshold_pct
def log_transaction(self, user_id: str, segment: str, price: float, base_price: float):
self.history.append({
'user': user_id,
'segment': segment,
'price': price,
'base': base_price
})
def audit_bias(self, segment_a: str, segment_b: str):
"""
Compares average prices between two demographic segments.
In a real system, this would trigger alerts if p-value < 0.05.
"""
prices_a = [h['price'] for h in self.history if h['segment'] == segment_a]
prices_b = [h['price'] for h in self.history if h['segment'] == segment_b]
if not prices_a or not prices_b:
return
avg_a = np.mean(prices_a)
avg_b = np.mean(prices_b)
diff = abs(avg_a - avg_b)
# Log for Compliance Reporting
audit_logger.info(f"COMPLIANCE AUDIT: Avg Price {segment_a}: ${avg_a:.2f} | {segment_b}: ${avg_b:.2f} | Diff: ${diff:.2f}")
if diff > (self.gouging_threshold * 0.1): # Arbitrary threshold for demo
audit_logger.warning(f"FAIRNESS ALERT: Significant price disparity detected between {segment_a} and {segment_b}")
# --- MAIN ORCHESTRATOR ---
def run_platform():
# Configuration
PRICE_ARMS = [10.00, 11.00, 12.00, 12.50, 13.00, 13.50, 14.00, 15.00]
BASE_PRICE = 12.00
SEGMENTS = ['Standard', 'Premium'] # Different user groups
# Initialize Components
env = CustomerSimulation(alpha=50, beta=2)
mab = GaussianThompsonSampling(arms=PRICE_ARMS)
guardrails = PricingGovernance(min_price=9.0, max_price=16.0, max_change_pct=0.10, last_price=BASE_PRICE)
fairness = FairnessMonitor(gouging_threshold_pct=0.20)
# Simulation Loop
print(f"{'Day':<5} | {'Segment':<10} | {'Raw Arm':<10} | {'Raw Price':<10} | {'Action':<15} | {'Final Price':<10} | {'Revenue':<10}")
print("-" * 95)
for day in range(1, 51):
# 1. Simulate incoming customer segment
current_segment = np.random.choice(SEGMENTS)
# 2. MAB Agent selects an arm (Index)
chosen_arm_idx = mab.select_arm()
raw_price = mab.arms[chosen_arm_idx]
# 3. Apply Governance Guardrails
final_price, action_taken = guardrails.enforce(raw_price, mab)
# Update Guardrails state for next day
guardrails.last_price = final_price
# 4. Environment generates reward
revenue = env.get_revenue(final_price)
# 5. Agent Learns
# Only update the MAB with the arm that was actually executed (if guardrails changed it)
# However, typically MAB updates on the arm it *pulled*, but if guardrails forced a different price,
# we usually map that price back to the closest arm or discard the learning to avoid bias.
# HERE: We update the chosen arm with the revenue obtained.
mab.update(chosen_arm_idx, revenue)
# 6. Compliance Logging
fairness.log_transaction(f"user_{day}", current_segment, final_price, BASE_PRICE)
# Print Status
print(f"{day:<5} | {current_segment:<10} | {chosen_arm_idx:<10} | ${raw_price:<9.2f} | {action_taken:<15} | ${final_price:<9.2f} | ${revenue:<9.2f}")
# Final Audit
print("\n--- COMPLIANCE AUDIT REPORT ---")
fairness.audit_bias('Standard', 'Premium')
if __name__ == "__main__":
run_platform()