Hamza4100's picture
Upload 20 files
9349f93 verified
Raw History Blame Contribute Delete
4.88 kB
"""
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")