import pandas as pd import numpy as np from datetime import datetime, timedelta import os np.random.seed(42) DATA_DIR = os.path.join(os.path.dirname(__file__), 'data', 'synthetic') os.makedirs(DATA_DIR, exist_ok=True) START_DATE = '2024-01-01' END_DATE = '2025-12-31' BRANDS = ['Alpha', 'Beta', 'Gamma'] REGIONS = ['North', 'South', 'East', 'West'] CHANNELS = { 'TV': {'sub': ['National TV', 'Regional TV'], 'base_spend': 50000, 'cpm': 12, 'ctr': 0.008, 'conv_rate': 0.03}, 'Digital Display': {'sub': ['Google Display', 'Programmatic'], 'base_spend': 30000, 'cpm': 5, 'ctr': 0.012, 'conv_rate': 0.04}, 'Paid Search': {'sub': ['Google Search', 'Bing Search'], 'base_spend': 25000, 'cpm': 15, 'ctr': 0.045, 'conv_rate': 0.08}, 'Social Media': {'sub': ['Facebook', 'Instagram', 'LinkedIn'], 'base_spend': 20000, 'cpm': 7, 'ctr': 0.025, 'conv_rate': 0.05}, 'Radio': {'sub': ['National Radio', 'Local Radio'], 'base_spend': 10000, 'cpm': 4, 'ctr': 0.005, 'conv_rate': 0.02}, 'Print': {'sub': ['Newspaper', 'Magazine'], 'base_spend': 8000, 'cpm': 8, 'ctr': 0.003, 'conv_rate': 0.015}, } CAMPAIGN_OBJECTIVES = ['Awareness', 'Consideration', 'Conversion'] def seasonality_factor(date): day_of_year = date.timetuple().tm_yday return 1 + 0.3 * np.sin(2 * np.pi * (day_of_year - 60) / 365) def generate_media_data(): weeks = pd.date_range(START_DATE, END_DATE, freq='W-MON') rows = [] # ---- Step 1: Create a pool of ads with defined lifetimes ---- # Each ad runs for a specific duration across multiple weeks ad_pool = [] ad_counter = 0 for brand in BRANDS: for channel, cfg in CHANNELS.items(): for sub in cfg['sub']: for objective in CAMPAIGN_OBJECTIVES: # Create 3-6 ads per combination, each with a different lifespan n_ads = np.random.randint(3, 7) for _ in range(n_ads): ad_format = np.random.choice(['Image', 'Video', 'Carousel', 'Text']) # Ad launch: random week within the date range launch_week_idx = np.random.randint(0, max(1, len(weeks) - 4)) # Ad duration: 3-26 weeks (some ads run long, some short) duration_weeks = np.random.choice( [3, 4, 5, 6, 8, 10, 12, 16, 20, 26], p=[0.05, 0.08, 0.10, 0.12, 0.15, 0.15, 0.12, 0.10, 0.08, 0.05] ) end_week_idx = min(launch_week_idx + duration_weeks, len(weeks) - 1) quarter = f"Q{(weeks[launch_week_idx].month - 1) // 3 + 1}" campaign_name = f"{channel}_{quarter}_{weeks[launch_week_idx].year}_{objective}_{brand}" # Base spend varies significantly between ads spend_multiplier = np.random.uniform(0.3, 2.5) # Fatigue rate: how quickly CTR/conv rate decay over time fatigue_rate = np.random.uniform(0.005, 0.03) ad_pool.append({ 'ad_id': f"AD-{ad_counter:05d}", 'ad_format': ad_format, 'channel': channel, 'sub_channel': sub, 'campaign_name': campaign_name, 'campaign_objective': objective, 'brand': brand, 'media_type': 'Paid', 'launch_idx': launch_week_idx, 'end_idx': end_week_idx, 'spend_mult': spend_multiplier, 'fatigue_rate': fatigue_rate, 'base_ctr': cfg['ctr'], 'base_conv': cfg['conv_rate'], 'base_spend': cfg['base_spend'], 'cpm': cfg['cpm'], 'n_subs': len(cfg['sub']), }) ad_counter += 1 # ---- Step 2: Generate weekly rows for each active ad ---- brand_mult = {'Alpha': 1.2, 'Beta': 0.9, 'Gamma': 0.7} for ad in ad_pool: for week_idx in range(ad['launch_idx'], ad['end_idx'] + 1): week = weeks[week_idx] sf = seasonality_factor(week) weeks_active = week_idx - ad['launch_idx'] # Fatigue: CTR and conv rate decay over ad lifetime fatigue_factor = max(0.3, 1.0 - ad['fatigue_rate'] * weeks_active) # Some randomness in weekly performance noise = np.random.uniform(0.75, 1.25) bm = brand_mult[ad['brand']] spend = max(200, ad['base_spend'] * bm * sf * ad['spend_mult'] * noise / ad['n_subs'] / 4) impressions = int(spend / ad['cpm'] * 1000 * np.random.uniform(0.8, 1.2)) # CTR decays with fatigue effective_ctr = ad['base_ctr'] * fatigue_factor * np.random.uniform(0.7, 1.3) clicks = max(0, int(impressions * effective_ctr)) # Conv rate also decays effective_conv = ad['base_conv'] * fatigue_factor * np.random.uniform(0.6, 1.4) conversions = max(0, int(clicks * effective_conv)) leads = max(0, int(clicks * effective_conv * 1.5 * np.random.uniform(0.7, 1.3))) region = np.random.choice(REGIONS) rows.append({ 'date': week.strftime('%Y-%m-%d'), 'channel': ad['channel'], 'sub_channel': ad['sub_channel'], 'campaign_name': ad['campaign_name'], 'campaign_objective': ad['campaign_objective'], 'ad_id': ad['ad_id'], 'ad_format': ad['ad_format'], 'spend': round(spend, 2), 'impressions': impressions, 'clicks': clicks, 'conversions': conversions, 'leads': leads, 'region': region, 'brand': ad['brand'], 'media_type': ad['media_type'], }) df = pd.DataFrame(rows) df = df.sort_values('date').reset_index(drop=True) df.to_csv(os.path.join(DATA_DIR, 'media_data.csv'), index=False) print(f"Media data: {len(df)} rows, {len(ad_pool)} unique ads") return df def generate_sales_data(media_df): weeks = pd.date_range(START_DATE, END_DATE, freq='W-MON') base_revenue = {'Alpha': 120000, 'Beta': 80000, 'Gamma': 50000} base_price = {'Alpha': 49.99, 'Beta': 34.99, 'Gamma': 24.99} rows = [] media_spend_by_week = media_df.groupby(['date', 'brand'])['spend'].sum().reset_index() media_spend_dict = {} for _, r in media_spend_by_week.iterrows(): media_spend_dict[(r['date'], r['brand'])] = r['spend'] prev_spend = {b: 0 for b in BRANDS} for week in weeks: sf = seasonality_factor(week) week_str = week.strftime('%Y-%m-%d') for brand in BRANDS: current_spend = media_spend_dict.get((week_str, brand), 0) adstock_spend = 0.4 * current_spend + 0.6 * prev_spend[brand] prev_spend[brand] = current_spend media_effect = adstock_spend * 0.8 for region in REGIONS: region_mult = {'North': 1.1, 'South': 1.0, 'East': 0.9, 'West': 0.95}[region] revenue = base_revenue[brand] * region_mult * sf / 4 + media_effect / 4 * np.random.uniform(0.8, 1.2) revenue = max(5000, revenue * np.random.uniform(0.85, 1.15)) price = base_price[brand] * np.random.uniform(0.95, 1.05) units = int(revenue / price) new_customers = int(units * np.random.uniform(0.05, 0.15)) sales_channel = np.random.choice(['Online', 'Offline'], p=[0.45, 0.55]) rows.append({ 'date': week_str, 'product': f"{brand} Product", 'brand': brand, 'region': region, 'channel': sales_channel, 'units_sold': units, 'revenue': round(revenue, 2), 'price': round(price, 2), 'new_customers': new_customers, }) df = pd.DataFrame(rows) df.to_csv(os.path.join(DATA_DIR, 'sales_data.csv'), index=False) print(f"Sales data: {len(df)} rows") return df def generate_consumer_promo_data(): promo_types = ['Coupon', 'Discount %', 'BOGO', 'Cashback', 'Free Sample', 'Bundle Deal'] mechanics = ['On-pack', 'In-store', 'Digital coupon', 'App-based', 'Mail-in'] rows = [] promo_counter = 0 start = pd.Timestamp(START_DATE) end = pd.Timestamp(END_DATE) current = start while current < end: n_promos = np.random.randint(1, 4) for _ in range(n_promos): brand = np.random.choice(BRANDS) promo_type = np.random.choice(promo_types) duration_weeks = np.random.randint(1, 5) promo_start = current + timedelta(days=np.random.randint(0, 14)) promo_end = promo_start + timedelta(weeks=duration_weeks) if promo_end > end: promo_end = end depth = np.random.uniform(5, 45) if promo_type in ['Discount %', 'Coupon'] else np.random.uniform(10, 30) promo_spend = np.random.uniform(5000, 50000) total_distributed = np.random.randint(5000, 50000) redemption_rate = { 'Coupon': 0.12, 'Discount %': 0.35, 'BOGO': 0.25, 'Cashback': 0.15, 'Free Sample': 0.30, 'Bundle Deal': 0.20 }[promo_type] * np.random.uniform(0.7, 1.3) units_redeemed = int(total_distributed * redemption_rate) promo_counter += 1 for week_start in pd.date_range(promo_start, promo_end, freq='W-MON'): region = np.random.choice(REGIONS) rows.append({ 'date': week_start.strftime('%Y-%m-%d'), 'promo_id': f"CP-{promo_counter:04d}", 'promo_name': f"{promo_type}_{brand}_{promo_start.strftime('%b%y')}", 'promo_type': promo_type, 'promo_mechanic': np.random.choice(mechanics), 'product': f"{brand} Product", 'promo_depth': round(depth, 1), 'promo_spend': round(promo_spend / max(1, duration_weeks), 2), 'units_redeemed': int(units_redeemed / max(1, duration_weeks)), 'total_units_distributed': int(total_distributed / max(1, duration_weeks)), 'start_date': promo_start.strftime('%Y-%m-%d'), 'end_date': promo_end.strftime('%Y-%m-%d'), 'region': region, 'brand': brand, }) current += timedelta(weeks=2) df = pd.DataFrame(rows) df.to_csv(os.path.join(DATA_DIR, 'consumer_promo_data.csv'), index=False) print(f"Consumer promo data: {len(df)} rows") return df def generate_trade_promo_data(): promo_types = ['Off-invoice discount', 'Bill-back', 'Scan-down', 'Display allowance', 'Volume rebate', 'Co-op advertising'] retailers = ['MegaMart', 'ValueStore', 'PrimeRetail', 'ShopPlus', 'FreshMarket'] compliance_opts = ['Compliant', 'Partially Compliant', 'Non-compliant'] compliance_probs = [0.65, 0.25, 0.10] rows = [] event_counter = 0 start = pd.Timestamp(START_DATE) end = pd.Timestamp(END_DATE) current = start while current < end: n_events = np.random.randint(1, 4) for _ in range(n_events): brand = np.random.choice(BRANDS) retailer = np.random.choice(retailers) promo_type = np.random.choice(promo_types) duration_weeks = np.random.randint(1, 6) event_start = current + timedelta(days=np.random.randint(0, 14)) event_end = event_start + timedelta(weeks=duration_weeks) if event_end > end: event_end = end planned_spend = np.random.uniform(10000, 80000) actual_spend = planned_spend * np.random.uniform(0.8, 1.2) baseline_volume = np.random.uniform(1000, 5000) lift_pct = np.random.uniform(0.05, 0.50) actual_volume = baseline_volume * (1 + lift_pct) compliance = np.random.choice(compliance_opts, p=compliance_probs) event_counter += 1 for week_start in pd.date_range(event_start, event_end, freq='W-MON'): region = np.random.choice(REGIONS) rows.append({ 'date': week_start.strftime('%Y-%m-%d'), 'event_id': f"TP-{event_counter:04d}", 'promo_type': promo_type, 'retailer': retailer, 'product': f"{brand} Product", 'planned_spend': round(planned_spend / max(1, duration_weeks), 2), 'actual_spend': round(actual_spend / max(1, duration_weeks), 2), 'baseline_volume': round(baseline_volume / max(1, duration_weeks), 1), 'actual_volume': round(actual_volume / max(1, duration_weeks), 1), 'compliance_status': compliance, 'start_date': event_start.strftime('%Y-%m-%d'), 'end_date': event_end.strftime('%Y-%m-%d'), 'region': region, 'brand': brand, }) current += timedelta(weeks=3) df = pd.DataFrame(rows) df.to_csv(os.path.join(DATA_DIR, 'trade_promo_data.csv'), index=False) print(f"Trade promo data: {len(df)} rows") return df def generate_external_factors(): dates = pd.date_range(START_DATE, END_DATE, freq='D') holidays = { 'New Year': [(1, 1)], 'Presidents Day': [(2, 17), (2, 16)], 'Memorial Day': [(5, 27), (5, 26)], 'Independence Day': [(7, 4)], 'Labor Day': [(9, 2), (9, 1)], 'Thanksgiving': [(11, 28), (11, 27)], 'Black Friday': [(11, 29), (11, 28)], 'Christmas': [(12, 25)], 'Cyber Monday': [(12, 2), (12, 1)], } rows = [] econ_index = 1.0 comp_index = 1.0 for date in dates: day_of_year = date.timetuple().tm_yday temp = 55 + 25 * np.sin(2 * np.pi * (day_of_year - 80) / 365) + np.random.normal(0, 5) precip = max(0, np.random.exponential(0.15)) holiday_flag = False holiday_name = '' for hname, hdays in holidays.items(): for m, d in hdays: if date.month == m and date.day == d: holiday_flag = True holiday_name = hname econ_index += np.random.normal(0, 0.002) econ_index = np.clip(econ_index, 0.90, 1.10) comp_index += np.random.normal(0, 0.003) comp_index = np.clip(comp_index, 0.85, 1.15) event_flag = date.month == 2 and date.day == 12 # Super Bowl Sunday placeholder event_name = 'Super Bowl' if event_flag else '' rows.append({ 'date': date.strftime('%Y-%m-%d'), 'temperature': round(temp, 1), 'precipitation': round(precip, 2), 'holiday_flag': holiday_flag, 'holiday_name': holiday_name, 'economic_index': round(econ_index, 4), 'competitor_price_index': round(comp_index, 4), 'event_flag': event_flag, 'event_name': event_name, }) df = pd.DataFrame(rows) df.to_csv(os.path.join(DATA_DIR, 'external_factors_data.csv'), index=False) print(f"External factors data: {len(df)} rows") return df if __name__ == '__main__': print("Generating synthetic data...") media_df = generate_media_data() sales_df = generate_sales_data(media_df) cp_df = generate_consumer_promo_data() tp_df = generate_trade_promo_data() ef_df = generate_external_factors() print(f"\nAll data generated in {DATA_DIR}") print(f"Total rows: {len(media_df) + len(sales_df) + len(cp_df) + len(tp_df) + len(ef_df)}")