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
| import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from datetime import datetime, timedelta import matplotlib.dates as mdates
plt.style.use('ggplot') sns.set_theme(style="whitegrid")
class AirlineRevenueSim: def __init__(self, total_seats=100, days_to_departure=60, base_price=300, demand_model='normal', price_sensitivity=-0.01, random_seed=42): """ Initialize the airline revenue management simulation. Parameters: ----------- total_seats : int Total capacity of the flight days_to_departure : int Number of days before departure to start selling base_price : float Starting price point for the ticket demand_model : str Type of demand model to use ('normal' for normally distributed demand) price_sensitivity : float How sensitive demand is to price changes (negative value) random_seed : int Seed for reproducibility """ np.random.seed(random_seed) self.total_seats = total_seats self.days_to_departure = days_to_departure self.base_price = base_price self.price_sensitivity = price_sensitivity self.timeline = pd.date_range( end=datetime.now() + timedelta(days=5), periods=days_to_departure, freq='D' ) if demand_model == 'normal': mu = 0.8 * days_to_departure sigma = days_to_departure / 4 base_demand = norm.pdf(np.arange(days_to_departure), mu, sigma) self.base_demand = base_demand / np.max(base_demand) * 30 self.remaining_seats = total_seats self.results = { 'date': [], 'price': [], 'demand': [], 'sales': [], 'revenue': [], 'remaining_seats': [] } def calculate_demand(self, price, day_index): """Calculate expected demand based on price and day.""" base_demand = self.base_demand[day_index] price_effect = np.exp(self.price_sensitivity * (price - self.base_price)) randomness = np.random.normal(1, 0.2) expected_demand = base_demand * price_effect * randomness return max(0, expected_demand) def run_static_pricing(self): """Run simulation with static pricing (control case).""" price = self.base_price for day in range(self.days_to_departure): demand = self.calculate_demand(price, day) sales = min(demand, self.remaining_seats) self.remaining_seats -= sales self.results['date'].append(self.timeline[day]) self.results['price'].append(price) self.results['demand'].append(demand) self.results['sales'].append(sales) self.results['revenue'].append(sales * price) self.results['remaining_seats'].append(self.remaining_seats) if self.remaining_seats <= 0: break return pd.DataFrame(self.results) def run_dynamic_pricing(self, load_factor_thresholds=[0.7, 0.5, 0.3], price_adjustments=[1.0, 1.3, 1.6, 2.0]): """ Run simulation with dynamic pricing based on load factor. Parameters: ----------- load_factor_thresholds : list Load factor levels at which to adjust prices price_adjustments : list Price multipliers to apply at each threshold (should be one more than thresholds) """ for day in range(self.days_to_departure): days_remaining = self.days_to_departure - day - 1 load_factor = 1 - (self.remaining_seats / self.total_seats) target_load_factor = (day + 1) / self.days_to_departure if days_remaining > 0: price_multiplier = 1.0 if load_factor > target_load_factor: for i, threshold in enumerate(load_factor_thresholds): if load_factor > threshold: price_multiplier = price_adjustments[i] break else: price_multiplier = price_adjustments[-1] time_factor = 1 + (0.5 * (1 - days_remaining / self.days_to_departure)) price = self.base_price * price_multiplier * time_factor else: if load_factor > 0.9: price = self.base_price * 2.2 else: price = self.base_price * 0.9 demand = self.calculate_demand(price, day) sales = min(demand, self.remaining_seats) self.remaining_seats -= sales self.results['date'].append(self.timeline[day]) self.results['price'].append(price) self.results['demand'].append(demand) self.results['sales'].append(sales) self.results['revenue'].append(sales * price) self.results['remaining_seats'].append(self.remaining_seats) if self.remaining_seats <= 0: break return pd.DataFrame(self.results)
np.random.seed(42)
static_sim = AirlineRevenueSim(total_seats=150, days_to_departure=60, base_price=300) static_results = static_sim.run_static_pricing()
np.random.seed(42) dynamic_sim = AirlineRevenueSim(total_seats=150, days_to_departure=60, base_price=300) dynamic_results = dynamic_sim.run_dynamic_pricing()
fig, axs = plt.subplots(2, 2, figsize=(16, 12))
axs[0, 0].plot(static_results['date'], static_results['price'], label='Static Pricing') axs[0, 0].plot(dynamic_results['date'], dynamic_results['price'], label='Dynamic Pricing') axs[0, 0].set_title('Ticket Price Over Time', fontsize=14) axs[0, 0].set_xlabel('Date') axs[0, 0].set_ylabel('Price ($)') axs[0, 0].legend() axs[0, 0].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
axs[0, 1].plot(static_results['date'], static_results['remaining_seats'], label='Static Pricing') axs[0, 1].plot(dynamic_results['date'], dynamic_results['remaining_seats'], label='Dynamic Pricing') axs[0, 1].set_title('Remaining Seats Over Time', fontsize=14) axs[0, 1].set_xlabel('Date') axs[0, 1].set_ylabel('Seats') axs[0, 1].legend() axs[0, 1].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
axs[1, 0].bar(np.arange(len(static_results)) - 0.2, static_results['sales'], width=0.4, label='Static Pricing') axs[1, 0].bar(np.arange(len(dynamic_results)) + 0.2, dynamic_results['sales'], width=0.4, label='Dynamic Pricing') axs[1, 0].set_title('Daily Ticket Sales', fontsize=14) axs[1, 0].set_xlabel('Days Before Departure') axs[1, 0].set_ylabel('Number of Tickets Sold') axs[1, 0].set_xticks(np.arange(0, len(static_results), 5)) axs[1, 0].set_xticklabels([f"{60-i}" for i in range(0, len(static_results), 5)]) axs[1, 0].legend()
static_cumulative = static_results['revenue'].cumsum() dynamic_cumulative = dynamic_results['revenue'].cumsum()
axs[1, 1].plot(static_results['date'], static_cumulative, label='Static Pricing') axs[1, 1].plot(dynamic_results['date'], dynamic_cumulative, label='Dynamic Pricing') axs[1, 1].set_title('Cumulative Revenue', fontsize=14) axs[1, 1].set_xlabel('Date') axs[1, 1].set_ylabel('Revenue ($)') axs[1, 1].legend() axs[1, 1].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.tight_layout() plt.show()
print("Static Pricing Summary:") print(f"Total Revenue: ${static_results['revenue'].sum():.2f}") print(f"Average Ticket Price: ${static_results['price'].mean():.2f}") print(f"Tickets Sold: {static_results['sales'].sum():.0f}") print(f"Remaining Seats: {static_results['remaining_seats'].iloc[-1]:.0f}") print(f"Load Factor: {100 * (1 - static_results['remaining_seats'].iloc[-1] / 150):.1f}%")
print("\nDynamic Pricing Summary:") print(f"Total Revenue: ${dynamic_results['revenue'].sum():.2f}") print(f"Average Ticket Price: ${dynamic_results['price'].mean():.2f}") print(f"Tickets Sold: {dynamic_results['sales'].sum():.0f}") print(f"Remaining Seats: {dynamic_results['remaining_seats'].iloc[-1]:.0f}") print(f"Load Factor: {100 * (1 - dynamic_results['remaining_seats'].iloc[-1] / 150):.1f}%") print(f"Revenue Improvement: {100 * (dynamic_results['revenue'].sum() / static_results['revenue'].sum() - 1):.1f}%")
def optimize_prices(sim, remaining_days, remaining_seats): """ Find optimal price for each day to maximize expected revenue using a simple grid search approach. """ prices = np.linspace(sim.base_price * 0.5, sim.base_price * 3, 50) optimal_prices = [] for day in range(remaining_days): day_index = sim.days_to_departure - remaining_days + day expected_revenues = [] for price in prices: expected_demand = sim.calculate_demand(price, day_index) expected_sales = min(expected_demand, remaining_seats) expected_revenue = expected_sales * price expected_revenues.append(expected_revenue) optimal_price = prices[np.argmax(expected_revenues)] optimal_prices.append(optimal_price) expected_demand = sim.calculate_demand(optimal_price, day_index) expected_sales = min(expected_demand, remaining_seats) remaining_seats -= expected_sales if remaining_seats <= 0: break return optimal_prices
np.random.seed(42) optim_sim = AirlineRevenueSim(total_seats=150, days_to_departure=60, base_price=300)
optimal_prices = optimize_prices(optim_sim, optim_sim.days_to_departure, optim_sim.total_seats)
optim_results = { 'date': [], 'price': [], 'demand': [], 'sales': [], 'revenue': [], 'remaining_seats': [] }
remaining_seats = optim_sim.total_seats
for day in range(len(optimal_prices)): price = optimal_prices[day] demand = optim_sim.calculate_demand(price, day) sales = min(demand, remaining_seats) remaining_seats -= sales optim_results['date'].append(optim_sim.timeline[day]) optim_results['price'].append(price) optim_results['demand'].append(demand) optim_results['sales'].append(sales) optim_results['revenue'].append(sales * price) optim_results['remaining_seats'].append(remaining_seats) if remaining_seats <= 0: break
optim_results = pd.DataFrame(optim_results)
fig, axs = plt.subplots(2, 2, figsize=(16, 12))
axs[0, 0].plot(static_results['date'], static_results['price'], label='Static Pricing') axs[0, 0].plot(dynamic_results['date'], dynamic_results['price'], label='Rule-Based Dynamic') axs[0, 0].plot(optim_results['date'], optim_results['price'], label='Optimization-Based') axs[0, 0].set_title('Ticket Price Over Time', fontsize=14) axs[0, 0].set_xlabel('Date') axs[0, 0].set_ylabel('Price ($)') axs[0, 0].legend() axs[0, 0].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
axs[0, 1].plot(static_results['date'], static_results['remaining_seats'], label='Static Pricing') axs[0, 1].plot(dynamic_results['date'], dynamic_results['remaining_seats'], label='Rule-Based Dynamic') axs[0, 1].plot(optim_results['date'], optim_results['remaining_seats'], label='Optimization-Based') axs[0, 1].set_title('Remaining Seats Over Time', fontsize=14) axs[0, 1].set_xlabel('Date') axs[0, 1].set_ylabel('Seats') axs[0, 1].legend() axs[0, 1].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
days_to_show = min(len(static_results), len(dynamic_results), len(optim_results)) axs[1, 0].plot(range(days_to_show), static_results['sales'][:days_to_show], label='Static Pricing') axs[1, 0].plot(range(days_to_show), dynamic_results['sales'][:days_to_show], label='Rule-Based Dynamic') axs[1, 0].plot(range(days_to_show), optim_results['sales'][:days_to_show], label='Optimization-Based') axs[1, 0].set_title('Daily Ticket Sales', fontsize=14) axs[1, 0].set_xlabel('Days Before Departure') axs[1, 0].set_ylabel('Number of Tickets Sold') axs[1, 0].set_xticks(np.arange(0, days_to_show, 5)) axs[1, 0].set_xticklabels([f"{60-i}" for i in range(0, days_to_show, 5)]) axs[1, 0].legend()
static_cumulative = static_results['revenue'].cumsum() dynamic_cumulative = dynamic_results['revenue'].cumsum() optim_cumulative = optim_results['revenue'].cumsum()
axs[1, 1].plot(static_results['date'][:days_to_show], static_cumulative[:days_to_show], label='Static Pricing') axs[1, 1].plot(dynamic_results['date'][:days_to_show], dynamic_cumulative[:days_to_show], label='Rule-Based Dynamic') axs[1, 1].plot(optim_results['date'][:days_to_show], optim_cumulative[:days_to_show], label='Optimization-Based') axs[1, 1].set_title('Cumulative Revenue', fontsize=14) axs[1, 1].set_xlabel('Date') axs[1, 1].set_ylabel('Revenue ($)') axs[1, 1].legend() axs[1, 1].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.tight_layout() plt.show()
print("Static Pricing Summary:") print(f"Total Revenue: ${static_results['revenue'].sum():.2f}") print(f"Average Ticket Price: ${static_results['price'].mean():.2f}") print(f"Tickets Sold: {static_results['sales'].sum():.0f}") print(f"Load Factor: {100 * (1 - static_results['remaining_seats'].iloc[-1] / 150):.1f}%")
print("\nRule-Based Dynamic Pricing Summary:") print(f"Total Revenue: ${dynamic_results['revenue'].sum():.2f}") print(f"Average Ticket Price: ${dynamic_results['price'].mean():.2f}") print(f"Tickets Sold: {dynamic_results['sales'].sum():.0f}") print(f"Load Factor: {100 * (1 - dynamic_results['remaining_seats'].iloc[-1] / 150):.1f}%") print(f"Revenue Improvement: {100 * (dynamic_results['revenue'].sum() / static_results['revenue'].sum() - 1):.1f}%")
print("\nOptimization-Based Pricing Summary:") print(f"Total Revenue: ${optim_results['revenue'].sum():.2f}") print(f"Average Ticket Price: ${optim_results['price'].mean():.2f}") print(f"Tickets Sold: {optim_results['sales'].sum():.0f}") print(f"Load Factor: {100 * (1 - optim_results['remaining_seats'].iloc[-1] / 150):.1f}%") print(f"Revenue Improvement: {100 * (optim_results['revenue'].sum() / static_results['revenue'].sum() - 1):.1f}%")
|