File size: 4,876 Bytes
9349f93 | 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 | """
Generate sample sales data for the Sales Forecasting Dashboard.
Produces:
- sample_data/sample_sales.csv (~1095+ rows with realistic patterns)
- sample_data/sample_data_alt.csv (50 rows, alternate column names)
"""
import csv
import math
import random
import os
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def date_range(start_str, end_str):
"""Return list of (year, month, day) tuples from start to end inclusive."""
from datetime import date, timedelta
start = date.fromisoformat(start_str)
end = date.fromisoformat(end_str)
days = []
cur = start
while cur <= end:
days.append(cur)
cur += timedelta(days=1)
return days
# ---------------------------------------------------------------------------
# 1. sample_sales.csv
# ---------------------------------------------------------------------------
random.seed(42)
PRODUCTS = ["Widget A", "Widget B", "Widget C"]
CATEGORIES = {"Widget A": "Electronics", "Widget B": "Electronics", "Widget C": "Accessories"}
REGIONS = ["North", "South", "East", "West"]
days = date_range("2021-01-01", "2023-12-31")
rows = []
for i, day in enumerate(days):
for j, product in enumerate(PRODUCTS):
# --- deterministic trend (gradual upward) --------------------------
total_days = len(days) * len(PRODUCTS)
idx = i * len(PRODUCTS) + j
trend = 500 + 300 * (idx / total_days)
# --- monthly seasonality -------------------------------------------
# peak Nov (11) & Dec (12), trough Jan (1) & Feb (2)
month_factors = {
1: 0.75, 2: 0.78, 3: 0.88, 4: 0.92, 5: 0.95,
6: 0.98, 7: 1.00, 8: 1.02, 9: 1.05, 10: 1.10,
11: 1.30, 12: 1.45
}
seasonality = month_factors[day.month]
# --- weekend effect ------------------------------------------------
# weekday(): 0=Mon … 6=Sun
weekend_factor = 0.80 if day.weekday() >= 5 else 1.0
# --- product-level multiplier -------------------------------------
prod_mult = {"Widget A": 1.0, "Widget B": 1.3, "Widget C": 0.6}[product]
# --- realistic noise ----------------------------------------------
noise = random.gauss(0, 30)
sales = round(trend * seasonality * weekend_factor * prod_mult + noise, 2)
sales = max(sales, 0) # no negative sales
# --- region (rotate deterministically, with slight shuffle) --------
region = REGIONS[(i + j) % 4]
rows.append({
"date": day.isoformat(),
"product": product,
"category": CATEGORIES[product],
"region": region,
"sales": sales,
})
# --- introduce ~2% missing values (set sales to empty) --------------------
total_rows = len(rows)
missing_indices = random.sample(range(total_rows), k=int(total_rows * 0.02))
for idx in missing_indices:
rows[idx]["sales"] = ""
# --- introduce ~10 duplicate rows -----------------------------------------
dup_sources = random.sample(range(total_rows), k=10)
duplicates = [dict(rows[idx]) for idx in dup_sources]
rows.extend(duplicates)
# shuffle so duplicates aren't all at the end
random.shuffle(rows)
out_path = os.path.join(os.path.dirname(__file__), "sample_sales.csv")
fieldnames = ["date", "product", "category", "region", "sales"]
with open(out_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
print(f"[sample_sales.csv] rows written : {len(rows)}")
print(f" path : {out_path}")
print(f" size : {os.path.getsize(out_path):,} bytes")
# ---------------------------------------------------------------------------
# 2. sample_data_alt.csv (50 rows, alternate column names)
# ---------------------------------------------------------------------------
from datetime import date, timedelta
alt_start = date(2024, 1, 1)
alt_rows = []
base_rev = 1_000.0
for k in range(50):
day = alt_start + timedelta(days=k)
trend = base_rev + 20 * k
noise = random.gauss(0, 50)
revenue = round(max(trend + noise, 0), 2)
alt_rows.append({"transaction_date": day.isoformat(), "revenue": revenue})
alt_path = os.path.join(os.path.dirname(__file__), "sample_data_alt.csv")
with open(alt_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["transaction_date", "revenue"])
writer.writeheader()
writer.writerows(alt_rows)
print(f"\n[sample_data_alt.csv] rows written : {len(alt_rows)}")
print(f" path : {alt_path}")
print(f" size : {os.path.getsize(alt_path):,} bytes")
|