{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Business statistics and decision methods\n",
    "\n",
    "Gareth Grant — 54 worked examples\n",
    "\n",
    "Each example is illustrative and self-contained. Run the code, inspect the recorded output, and then change the inputs. The examples cover statistics plus adjacent operations and financial decision methods. A numerical result is meaningful only with suitable measurement, sampling, model assumptions and a clear decision context.\n",
    "\n",
    "## Run this notebook\n",
    "\n",
    "Use Python 3.11 or newer in Jupyter or VS Code. Install the packages listed in requirements.txt: NumPy, SciPy and scikit-learn. No dataset downloads, API keys or paid services are needed. Every example defines its own illustrative data.\n",
    "\n",
    "The accompanying HTML handbook contains the full explanations, formula glossaries, assumptions, pitfalls and strategy playbooks. The website supplies 50 live browser explorations; multiple regression, clustering, PCA and measurement-system analysis use the richer fitted Python workflows here.\n"
   ],
   "id": "business-cell-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Descriptive statistics: centre, spread and shape\n",
    "\n",
    "**Business question:** What does normal performance look like, and how inconsistent is it?\n",
    "\n",
    "Descriptive statistics turn individual records into an understandable picture of current performance. They are the starting point for a business dashboard, a process investigation and the choice of a more advanced model.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Mean = Σxᵢ/n; sample variance s² = Σ(xᵢ − x̄)²/(n − 1); IQR = Q3 − Q1\n",
    "\n",
    "- **xᵢ**: One observed value, such as minutes for one completed job.\n",
    "- **n**: Number of observations; use the actual denominator for the stated unit.\n",
    "- **s**: Sample standard deviation, using n − 1 when estimating a population spread.\n",
    "- **Q1, Q3**: 25th and 75th percentiles; record the quantile convention used.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative Durban repair desk: eight completed jobs took different numbers of minutes. The manager wants to understand the typical job and the work consumed by long jobs.\n",
    "\n",
    "- Minutes: 18, 20, 22, 20, 25, 21, 19, 55.\n",
    "- All eight are valid completed jobs measured using the same start and stop definition.\n",
    "\n",
    "1. Add the job times: 200 minutes. Divide by 8 to obtain a mean of 25.00 minutes.\n",
    "2. Sort the data: 18, 19, 20, 20, 21, 22, 25, 55. The two middle values are 20 and 21, giving a median of 20.50 minutes.\n",
    "3. The sum of squared deviations from 25 is 1,060. Divide by 7 to obtain sample variance 151.4286; take the square root to obtain 12.3056 minutes.\n",
    "4. Using linear-interpolated quartiles, Q1 = 19.75 and Q3 = 22.75, so IQR = 3.00 minutes.\n",
    "\n",
    "**Result:** Mean 25.00 min; median 20.50 min; sample standard deviation 12.31 min; IQR 3.00 min.\n",
    "\n",
    "The middle of this small sample is relatively compact, while one long job raises the mean and total workload. Use the mean for the observed workload calculation and investigate the long job before choosing a customer promise.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Measurements have consistent units and operational meaning.\n",
    "- Each row is counted once at the intended level of analysis.\n",
    "- The collected period is relevant to the decision being discussed.\n",
    "- A sample standard deviation estimates variability; it is not a confidence interval or a guaranteed operating range.\n",
    "\n",
    "**Decision rule to adapt:** Select the summary that matches the decision, then check whether its conclusion survives subgroup and time-based inspection.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: measures of location](https://www.itl.nist.gov/div898/handbook/eda/section3/eda351.htm)\n",
    "- [NIST: skewness and kurtosis](https://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm)\n"
   ],
   "id": "business-cell-001"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "descriptive-statistics"
   },
   "execution_count": 1,
   "source": [
    "import numpy as np\n",
    "minutes = np.array([18, 20, 22, 20, 25, 21, 19, 55])\n",
    "q1, q3 = np.quantile(minutes, [0.25, 0.75])\n",
    "print(f'Jobs: {len(minutes)}')\n",
    "print(f'Mean: {minutes.mean():.2f} min')\n",
    "print(f'Median: {np.median(minutes):.2f} min')\n",
    "print(f'Sample SD: {minutes.std(ddof=1):.2f} min')\n",
    "print(f'IQR: {q3-q1:.2f} min')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Jobs: 8\n",
      "Mean: 25.00 min\n",
      "Median: 20.50 min\n",
      "Sample SD: 12.31 min\n",
      "IQR: 3.00 min\n"
     ]
    }
   ],
   "id": "business-cell-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Data quality, missing values and outliers\n",
    "\n",
    "**Business question:** Is the apparent business problem real, or did the records create it?\n",
    "\n",
    "Data cleaning establishes whether records are usable for a specific decision. An unusual observation is a prompt to investigate, not permission to remove inconvenient evidence.\n",
    "\n",
    "### Formula\n",
    "\n",
    "IQR = Q3 − Q1; lower flag = Q1 − 1.5 × IQR; upper flag = Q3 + 1.5 × IQR\n",
    "\n",
    "- **Q1, Q3**: 25th and 75th percentiles using a documented interpolation rule.\n",
    "- **IQR**: Spread of the middle half of measured values.\n",
    "- **flag**: A candidate for review, not an automatic rejection or correction.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative service desk: ten recorded job durations include a 60-minute repair. The analyst screens the data and then asks whether that long repair is an error or an operational event.\n",
    "\n",
    "- Minutes: 10, 11, 11, 12, 12, 13, 13, 14, 15, 60.\n",
    "- Quartiles use NumPy’s default linear interpolation.\n",
    "\n",
    "1. Calculate Q1 = 11.25 and Q3 = 13.75 minutes. The IQR is 2.50 minutes.\n",
    "2. Compute the lower fence: 11.25 − 1.5 × 2.50 = 7.50 minutes. The upper fence is 13.75 + 3.75 = 17.50 minutes.\n",
    "3. Only 60 minutes lies outside the fences. The mean of all ten jobs is 171/10 = 17.10 minutes.\n",
    "4. For a sensitivity comparison only, the other nine average 111/9 = 12.33 minutes. The difference shows why the record matters; it does not justify deleting it.\n",
    "\n",
    "**Result:** One flagged duration, 60 minutes. Inclusive mean 17.10 min; sensitivity mean excluding that record 12.33 min.\n",
    "\n",
    "If the 60-minute job was a genuine failure, it belongs in a measure of the customer’s overall experience. If source evidence proves that seconds were entered as minutes, correct the unit and retain an audit trail.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The cleaning rules reflect the actual process and intended unit of analysis.\n",
    "- A duplicate key is interpreted in context: legitimate repeat visits are not duplicate customers.\n",
    "- Outlier fences are screening rules and can flag genuine observations in skewed distributions.\n",
    "- Any imputation or exclusion is disclosed and supported by a reason relevant to the decision.\n",
    "\n",
    "**Decision rule to adapt:** Change a value only when evidence or the pre-defined analysis population supports the change; otherwise retain it and analyse its influence.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: detection of outliers](https://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm)\n"
   ],
   "id": "business-cell-003"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "data-quality-outliers"
   },
   "execution_count": 2,
   "source": [
    "import numpy as np\n",
    "minutes = np.array([10, 11, 11, 12, 12, 13, 13, 14, 15, 60])\n",
    "q1, q3 = np.quantile(minutes, [0.25, 0.75])\n",
    "iqr = q3 - q1\n",
    "flagged = (minutes < q1-1.5*iqr) | (minutes > q3+1.5*iqr)\n",
    "print(f'Flagging fences: {q1-1.5*iqr:.2f}, {q3+1.5*iqr:.2f} min')\n",
    "print('Review these values:', minutes[flagged].tolist())\n",
    "print(f'Inclusive mean: {minutes.mean():.2f} min')\n",
    "print(f'Sensitivity mean only: {minutes[~flagged].mean():.2f} min')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Flagging fences: 7.50, 17.50 min\n",
      "Review these values: [60]\n",
      "Inclusive mean: 17.10 min\n",
      "Sensitivity mean only: 12.33 min\n"
     ]
    }
   ],
   "id": "business-cell-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Sampling, surveys and representative measurement\n",
    "\n",
    "**Business question:** Whose experience does the sample represent?\n",
    "\n",
    "A sampling plan connects the records you can collect to the population you want to understand. Selection, coverage, response and weighting matter before the sample size is considered.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Stratified estimate p̂ = Σ Wₕ p̂ₕ; Wₕ = Nₕ/N; basic expansion weight wₕ = Nₕ/nₕ\n",
    "\n",
    "- **h**: A population stratum, such as a branch.\n",
    "- **Nₕ, nₕ**: Population and sampled counts in that stratum.\n",
    "- **Wₕ**: Share of the target population belonging to the stratum.\n",
    "- **p̂ₕ**: Observed outcome proportion within that stratum.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative two-branch repair company: branch A serves 600 of 1,000 eligible customers and B serves 400. Fifty customers are randomly sampled from each branch and all respond.\n",
    "\n",
    "- Branch A: 40 satisfied respondents out of 50.\n",
    "- Branch B: 25 satisfied respondents out of 50.\n",
    "- Population shares: A = 0.60; B = 0.40.\n",
    "\n",
    "1. Calculate the within-branch satisfaction rates: A = 40/50 = 80%; B = 25/50 = 50%.\n",
    "2. An unweighted pooled calculation gives 65/100 = 65%, but it assigns each branch a 50% share.\n",
    "3. Use population shares: 0.60 × 0.80 + 0.40 × 0.50 = 0.68.\n",
    "4. Equivalently, use expansion weights 600/50 = 12 and 400/50 = 8: (40 × 12 + 25 × 8)/1,000 = 68%.\n",
    "\n",
    "**Result:** The design-weighted satisfaction estimate is 68%, compared with an unweighted 65%.\n",
    "\n",
    "The weighted estimate restores the known branch population mix under the stated selection and full-response assumptions. It does not prove that nonrespondents would have answered similarly if response were incomplete.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Population counts and stratum membership are accurate for the reporting period.\n",
    "- Selection within each example stratum is genuinely random and without substitution by convenience.\n",
    "- The numerical example assumes full response; non-response requires a separate assessment.\n",
    "- The outcome question has the same meaning across branches and customer groups.\n",
    "\n",
    "**Decision rule to adapt:** Use population conclusions only when the selection, coverage and response story support them; report subgroup and design limitations alongside the estimate.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [Statistics Canada: probability sampling](https://www150.statcan.gc.ca/n1/edu/power-pouvoir/ch13/prob/5214899-eng.htm)\n"
   ],
   "id": "business-cell-005"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "sampling-surveys"
   },
   "execution_count": 3,
   "source": [
    "population_a, population_b = 600, 400\n",
    "satisfied_a, sampled_a = 40, 50\n",
    "satisfied_b, sampled_b = 25, 50\n",
    "rate_a = satisfied_a / sampled_a\n",
    "rate_b = satisfied_b / sampled_b\n",
    "weighted = (population_a*rate_a + population_b*rate_b)/(population_a+population_b)\n",
    "unweighted = (satisfied_a+satisfied_b)/(sampled_a+sampled_b)\n",
    "print(f'Branch A: {rate_a:.1%}; branch B: {rate_b:.1%}')\n",
    "print(f'Population-weighted rate: {weighted:.1%}')\n",
    "print(f'Unweighted sample rate: {unweighted:.1%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Branch A: 80.0%; branch B: 50.0%\n",
      "Population-weighted rate: 68.0%\n",
      "Unweighted sample rate: 65.0%\n"
     ]
    }
   ],
   "id": "business-cell-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Probability, expected value and decision trees\n",
    "\n",
    "**Business question:** Which option has the better expected contribution when outcomes are uncertain?\n",
    "\n",
    "Expected value combines the financial result of each possible outcome with its probability. It gives a consistent comparison of uncertain choices while leaving room to consider downside risk, cash limits and the value of more information.\n",
    "\n",
    "### Formula\n",
    "\n",
    "E[V] = Σ pᵢvᵢ; incremental expected value = E[V with change] − E[V without change]\n",
    "\n",
    "- **pᵢ**: Probability of outcome i; mutually exclusive scenario probabilities sum to one.\n",
    "- **vᵢ**: Financial result for that outcome, on a consistent cost and time basis.\n",
    "- **E[V]**: Modelled long-run average value, not a guarantee for one decision.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative Ballito service firm considers spending R8,000 on a booking improvement. The firm compares incremental contribution over the same three-month period, before financing and tax.\n",
    "\n",
    "- Strong uptake: probability 0.30, incremental contribution before intervention cost R30,000.\n",
    "- Moderate uptake: probability 0.50, contribution R12,000.\n",
    "- Weak uptake: probability 0.20, contribution R0.\n",
    "- Intervention cost R8,000, incurred in every scenario.\n",
    "\n",
    "1. Calculate the net scenario results: R22,000, R4,000 and −R8,000.\n",
    "2. Weight each net result: 0.30 × 22,000 = R6,600; 0.50 × 4,000 = R2,000; 0.20 × (−8,000) = −R1,600.\n",
    "3. Add the weighted results: R6,600 + R2,000 − R1,600 = R7,000.\n",
    "4. The model assigns 20% probability to an R8,000 loss, so confirm that the business can tolerate that outcome.\n",
    "\n",
    "**Result:** Modelled incremental expected contribution is R7,000, with an R8,000 downside in the weak-uptake scenario.\n",
    "\n",
    "The intervention has a positive expectation under these assumptions. Approval still depends on affordability, alternatives and whether the scenario probabilities have enough support to guide a commitment.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- All material scenarios and relevant incremental cash or contribution items are represented.\n",
    "- Probabilities describe the same future horizon and business conditions.\n",
    "- Values use consistent treatment of fixed, sunk and variable costs.\n",
    "- Risk preferences and funding limits are assessed separately from the average value.\n",
    "\n",
    "**Decision rule to adapt:** Prefer a feasible option with a better incremental expectation only after checking downside constraints and sensitivity to defensible assumptions.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy: expected value by probability-weighted summation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_discrete.expect.html)\n"
   ],
   "id": "business-cell-007"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "probability-expected-value"
   },
   "execution_count": 4,
   "source": [
    "probabilities = [0.30, 0.50, 0.20]\n",
    "contributions = [30000, 12000, 0]\n",
    "intervention_cost = 8000\n",
    "net_results = [value-intervention_cost for value in contributions]\n",
    "expected = sum(p*value for p, value in zip(probabilities, net_results))\n",
    "print('Net scenario contributions:', net_results)\n",
    "print(f'Expected incremental contribution: R {expected:,.2f}')\n",
    "print(f'Worst modelled result: R {min(net_results):,.2f}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Net scenario contributions: [22000, 4000, -8000]\n",
      "Expected incremental contribution: R 7,000.00\n",
      "Worst modelled result: R -8,000.00\n"
     ]
    }
   ],
   "id": "business-cell-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Bayes’ theorem and the base-rate problem\n",
    "\n",
    "**Business question:** When an alert fires, how likely is the underlying business problem?\n",
    "\n",
    "Bayes’ theorem combines a starting prevalence with the reliability of new evidence. It prevents a common error: treating the probability of an alert given a problem as the probability of a problem given an alert.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(D | A) = [P(A | D)P(D)] / [P(A | D)P(D) + P(A | not D)P(not D)]\n",
    "\n",
    "- **D**: Underlying problem, such as a genuinely defective item.\n",
    "- **A**: Observed alert or positive screening result.\n",
    "- **P(D)**: Base-rate probability before seeing the alert.\n",
    "- **P(A | D), P(A | not D)**: Sensitivity and false-positive rate measured under relevant conditions.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative KwaZulu-Natal warehouse considers an automated visual flag as a trigger for manual inspection, not as a final rejection decision.\n",
    "\n",
    "- Expected defect prevalence 2%.\n",
    "- Sensitivity 90%; false-positive rate 5%.\n",
    "- Operating volume: 10,000 items.\n",
    "\n",
    "1. Of 10,000 items, expect 200 defective and 9,800 good items under the prevalence assumption.\n",
    "2. The flag finds 0.90 × 200 = 180 defective items and also flags 0.05 × 9,800 = 490 good items.\n",
    "3. Total flagged items = 180 + 490 = 670. The fraction genuinely defective is 180/670 = 0.2686567.\n",
    "4. Twenty defective items are missed: 200 − 180 = 20. Manual inspection must be sized for about 670 alerts, not just the 180 true alerts.\n",
    "\n",
    "**Result:** A flagged item has a modelled 26.87% probability of being defective. The 90% sensitivity is a different probability.\n",
    "\n",
    "The alert can still be useful for a relatively inexpensive manual check. It would be a poor basis for assuming that almost every flagged item should be scrapped without confirmation.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The two underlying states in this example are mutually exclusive and exhaustive.\n",
    "- Validation rates and prevalence are relevant to the operation where the system will be used.\n",
    "- The alert definition stays the same when the probabilities are applied.\n",
    "- Estimation uncertainty and changes in product mix are checked rather than treating supplied rates as exact facts.\n",
    "\n",
    "**Decision rule to adapt:** Act on the posterior probability together with error costs and verification options; re-estimate it when prevalence or operating conditions change.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Bayes formula, prior and posterior models](https://www.itl.nist.gov/div898/handbook/apr/section2/apr1a.htm)\n"
   ],
   "id": "business-cell-009"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "bayes-theorem"
   },
   "execution_count": 5,
   "source": [
    "items = 10000\n",
    "prevalence = 0.02\n",
    "sensitivity = 0.90\n",
    "false_positive_rate = 0.05\n",
    "true_alerts = items*prevalence*sensitivity\n",
    "false_alerts = items*(1-prevalence)*false_positive_rate\n",
    "posterior = true_alerts/(true_alerts+false_alerts)\n",
    "print(f'True alerts: {true_alerts:.0f}; false alerts: {false_alerts:.0f}')\n",
    "print(f'Expected alerts to review: {true_alerts+false_alerts:.0f}')\n",
    "print(f'P(defect given alert): {posterior:.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True alerts: 180; false alerts: 490\n",
      "Expected alerts to review: 670\n",
      "P(defect given alert): 26.87%\n"
     ]
    }
   ],
   "id": "business-cell-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Binomial distribution: successes in a fixed number of trials\n",
    "\n",
    "**Business question:** How variable can the number of defects or conversions be in a fixed batch?\n",
    "\n",
    "The binomial distribution models a count of yes/no outcomes across a specified number of comparable trials. It connects an assumed event rate to the chances of individual batch results.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(X = k) = C(n,k)pᵏ(1 − p)ⁿ⁻ᵏ; E[X] = np; Var(X) = np(1 − p)\n",
    "\n",
    "- **n**: Fixed number of trials.\n",
    "- **p**: Probability of the counted outcome on each trial.\n",
    "- **k**: Whole-number successes from 0 to n.\n",
    "- **C(n,k)**: Number of ways k successes can be placed among n trials.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative packaging operation inspects batches of 100 items. Historical evidence motivates a scenario with a stable 2% defect probability per item. The supervisor asks how often a batch needs space for more than three reworks.\n",
    "\n",
    "- n = 100 items per batch.\n",
    "- p = 0.02 defect probability, treated as known for this planning example.\n",
    "- Threshold: more than 3 defects, meaning 4 or more.\n",
    "\n",
    "1. Calculate the expected defect count: 100 × 0.02 = 2 defects.\n",
    "2. Calculate the variance: 100 × 0.02 × 0.98 = 1.96; the standard deviation is 1.40 defects.\n",
    "3. Exactly two defects has probability C(100,2) × 0.02² × 0.98⁹⁸ = 0.2734139.\n",
    "4. For more than three defects, sum k = 4 through 100, or use the survival probability P(X > 3) = 0.1410384.\n",
    "\n",
    "**Result:** Mean 2 defects per batch; probability of exactly 2 is 27.34%; probability of more than 3 is 14.10%.\n",
    "\n",
    "A stable average of two defects does not mean that three rework places cover almost every batch. This scenario predicts that the threshold is exceeded in roughly 14% of comparable batches.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The number of trials n is fixed rather than stopping after a target number of successes.\n",
    "- Every trial has the same event probability in the stated scenario.\n",
    "- Outcomes are independent, conditional on the model and its parameters.\n",
    "- Sampling without replacement is approximated only when depletion is negligible; otherwise use a finite-population model.\n",
    "\n",
    "**Decision rule to adapt:** Choose a count threshold that meets the stated coverage objective under a validated trial model, then monitor whether observed batches behave similarly.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: binomial distribution](https://www.itl.nist.gov/div898/handbook/eda/section3/eda366i.htm)\n"
   ],
   "id": "business-cell-011"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "binomial-distribution"
   },
   "execution_count": 6,
   "source": [
    "from scipy.stats import binom\n",
    "n, p = 100, 0.02\n",
    "print(f'Expected defects: {n*p:.2f}')\n",
    "print(f'Count standard deviation: {(n*p*(1-p))**0.5:.2f}')\n",
    "print(f'Exactly two defects: {binom.pmf(2,n,p):.2%}')\n",
    "print(f'More than three defects: {binom.sf(3,n,p):.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Expected defects: 2.00\n",
      "Count standard deviation: 1.40\n",
      "Exactly two defects: 27.34%\n",
      "More than three defects: 14.10%\n"
     ]
    }
   ],
   "id": "business-cell-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Poisson distribution: random event counts\n",
    "\n",
    "**Business question:** How often could random demand exceed the capacity planned for a time window?\n",
    "\n",
    "A Poisson model translates an average event rate into a distribution of whole-number counts. It is useful for random arrivals or incidents when the rate and independence assumptions fit the operation.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(X = k) = exp(−λ) λ^k/k!; λ = event rate × exposure; P(overflow) = P(X > C)\n",
    "\n",
    "- **λ**: Expected number of events in the exact window being analysed.\n",
    "- **k**: A non-negative whole-number count.\n",
    "- **C**: Nominal event-handling capacity over that same window.\n",
    "- **event rate**: Expected events per chosen exposure unit, estimated for comparable conditions.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative packing team receives 48 orders per hour. Each station has nominal capacity for four orders per 15-minute window. The manager compares four and five stations, assuming zero opening backlog.\n",
    "\n",
    "- Hourly order rate = 48; window = 0.25 hours.\n",
    "- Capacity per station = 4 orders per window.\n",
    "- Coverage objective = at least 95% of arrival-count windows.\n",
    "\n",
    "1. Convert the rate to the window mean: λ = 48 × 0.25 = 12 orders.\n",
    "2. Four stations provide capacity C = 4 × 4 = 16. Calculate P(X > 16) = 0.1012910.\n",
    "3. Five stations provide C = 20. Calculate P(X > 20) = 0.0115977.\n",
    "4. Window coverage changes from 1 − 0.1012910 = 89.87% to 1 − 0.0115977 = 98.84%. Five is the smallest whole-station count meeting this target with four orders per station.\n",
    "\n",
    "**Result:** Four stations: 10.13% overflow risk. Five stations: 1.16% overflow risk under the stated count model.\n",
    "\n",
    "Adding one station changes count coverage substantially, but this is not an individual-order on-time completion guarantee. Check whether the same conclusion holds with measured service times and carried work.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Events occur independently under an approximately constant rate within the modelled exposure.\n",
    "- The event and exposure definitions are the same in estimation and planning.\n",
    "- The illustrative capacity comparison starts with no unfinished work.\n",
    "- The supplied rate is treated as known; parameter uncertainty is a separate issue.\n",
    "\n",
    "**Decision rule to adapt:** Select the smallest feasible capacity meeting the stated count-coverage objective only after checking the arrival model and the separate service constraints.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Poisson distribution](https://www.itl.nist.gov/div898/handbook/eda/section3/eda366j.htm)\n"
   ],
   "id": "business-cell-013"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "poisson-distribution"
   },
   "execution_count": 7,
   "source": [
    "from scipy.stats import poisson\n",
    "mean_orders = 48*0.25\n",
    "for stations in [4, 5]:\n",
    "    capacity = stations*4\n",
    "    overflow = poisson.sf(capacity, mean_orders)\n",
    "    print(f'{stations} stations: capacity {capacity}, overflow {overflow:.2%}, coverage {1-overflow:.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "4 stations: capacity 16, overflow 10.13%, coverage 89.87%\n",
      "5 stations: capacity 20, overflow 1.16%, coverage 98.84%\n"
     ]
    }
   ],
   "id": "business-cell-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Normal distribution: measurement variation\n",
    "\n",
    "**Business question:** How much output falls outside a requirement when measurements vary around a centre?\n",
    "\n",
    "A normal distribution describes a symmetric continuous spread using a mean and standard deviation. When that shape is appropriate, it converts measurement limits into expected proportions and costs.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Z = (X − μ)/σ; P(reject) = Φ((LSL − μ)/σ) + 1 − Φ((USL − μ)/σ)\n",
    "\n",
    "- **μ**: Mean of the modelled continuous measurement.\n",
    "- **σ**: Positive standard deviation in the same measurement units.\n",
    "- **LSL, USL**: Product specification limits, determined by the requirement.\n",
    "- **Φ**: Standard normal cumulative distribution function.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative bottling line accepts volumes from 490 to 510 ml. Suppose a stable process has mean 502 ml and standard deviation 4 ml. Ten thousand bottles are produced in the period.\n",
    "\n",
    "- Mean μ = 502 ml; standard deviation σ = 4 ml.\n",
    "- Acceptable interval 490–510 ml.\n",
    "- 10,000 bottles; R3 contribution loss or rework cost per rejected bottle in this simplified example.\n",
    "\n",
    "1. Standardise the lower limit: (490 − 502)/4 = −3. The lower-tail probability is 0.0013499.\n",
    "2. Standardise the upper limit: (510 − 502)/4 = 2. The upper-tail probability is 0.0227501.\n",
    "3. Add the tails: 0.0013499 + 0.0227501 = 0.0241000, or 2.4100%.\n",
    "4. Expected rejects = 10,000 × 0.0241000 = 241.00 bottles. Expected period reject cost = 241.00 × R3 ≈ R723.00.\n",
    "\n",
    "**Result:** Modelled acceptance 97.59%; expected rejects about 241 per 10,000; expected reject cost about R723.\n",
    "\n",
    "The upper tail dominates because the process mean is closer to the upper limit. Check centring and variation separately, and include intervention costs before deciding which adjustment is economically worthwhile.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The distribution is approximately normal for the measurement and operating regime being analysed.\n",
    "- The process parameters are reasonably stable over the decision period.\n",
    "- Measurement error is understood and small enough for the intended quality decision.\n",
    "- The example treats both tails as rejects with the same cost; real underfill and giveaway economics may differ.\n",
    "\n",
    "**Decision rule to adapt:** Use the tail calculation only for a defensible distribution and compare actual intervention cost with the reduction in expected quality losses.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: normal distribution](https://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm)\n"
   ],
   "id": "business-cell-015"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "normal-distribution"
   },
   "execution_count": 8,
   "source": [
    "from scipy.stats import norm\n",
    "mean, sd = 502, 4\n",
    "lower, upper = 490, 510\n",
    "reject_probability = norm.cdf(lower,mean,sd)+norm.sf(upper,mean,sd)\n",
    "expected_rejects = 10000*reject_probability\n",
    "print(f'Reject probability: {reject_probability:.4%}')\n",
    "print(f'Expected rejects: {expected_rejects:.2f}')\n",
    "print(f'Expected reject cost: R {expected_rejects*3:.2f}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Reject probability: 2.4100%\n",
      "Expected rejects: 241.00\n",
      "Expected reject cost: R 723.00\n"
     ]
    }
   ],
   "id": "business-cell-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. Exponential distribution: time until a random event\n",
    "\n",
    "**Business question:** How long might we wait for the next event when the event rate is constant?\n",
    "\n",
    "The exponential distribution models a non-negative waiting time with a constant event rate. It is a useful building block for random-arrival and some reliability models, provided the constant-hazard assumption is reasonable.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(T > t) = exp(−λt); E[T] = 1/λ; t_q = −ln(1 − q)/λ\n",
    "\n",
    "- **T**: Non-negative time until the event.\n",
    "- **λ**: Constant event rate per time unit.\n",
    "- **t**: Waiting-time threshold in the matching time unit.\n",
    "- **q**: Desired cumulative probability, such as 0.95 for a 95th percentile.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative technical support desk receives unscheduled requests during a quiet, stable period. The scenario assumes a mean of twenty minutes between arrivals. The manager asks how unusual a thirty-minute gap would be.\n",
    "\n",
    "- Mean inter-arrival time = 20 minutes, so λ = 1/20 = 0.05 per minute.\n",
    "- Threshold t = 30 minutes.\n",
    "- Percentile of interest q = 0.95.\n",
    "\n",
    "1. Calculate P(T > 30) = exp(−0.05 × 30) = exp(−1.5) = 0.2231302.\n",
    "2. The chance of an arrival within thirty minutes is 1 − 0.2231302 = 0.7768698.\n",
    "3. Calculate the 95th percentile: −ln(0.05)/0.05 = 59.9146 minutes.\n",
    "4. Under memorylessness, after ten minutes without an arrival, the modelled mean additional wait is still twenty minutes.\n",
    "\n",
    "**Result:** A gap longer than thirty minutes has probability 22.31%; the modelled 95th percentile is 59.91 minutes.\n",
    "\n",
    "A thirty-minute quiet period is not especially rare under this scenario. Staffing decisions still need the volume and service work over the whole period rather than assuming that each current gap predicts the next one.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The model uses a constant event rate within the period being analysed.\n",
    "- The associated random-event mechanism has no duration-dependent hazard.\n",
    "- Times are non-negative and measured consistently, with any censoring recorded.\n",
    "- The numerical parameter is treated as known; uncertainty in its estimate is not included in the example.\n",
    "\n",
    "**Decision rule to adapt:** Use an exponential model when a constant-rate, memoryless mechanism is defensible; choose service or maintenance actions using costs and the complete operating context.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: exponential distribution](https://www.itl.nist.gov/div898/handbook/eda/section3/eda3667.htm)\n"
   ],
   "id": "business-cell-017"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "exponential-distribution"
   },
   "execution_count": 9,
   "source": [
    "from scipy.stats import expon\n",
    "mean_gap = 20\n",
    "probability_long_gap = expon.sf(30,scale=mean_gap)\n",
    "percentile_95 = expon.ppf(0.95,scale=mean_gap)\n",
    "print(f'Gap longer than 30 min: {probability_long_gap:.2%}')\n",
    "print(f'Arrival within 30 min: {1-probability_long_gap:.2%}')\n",
    "print(f'95th percentile gap: {percentile_95:.2f} min')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Gap longer than 30 min: 22.31%\n",
      "Arrival within 30 min: 77.69%\n",
      "95th percentile gap: 59.91 min\n"
     ]
    }
   ],
   "id": "business-cell-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10. Geometric distribution: trials until the first success\n",
    "\n",
    "**Business question:** How many attempts might be needed before the first successful outcome?\n",
    "\n",
    "The geometric distribution models the trial number on which the first success occurs. It is useful for a repeated, comparable yes/no process where the success probability stays constant.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(K = k) = (1 − p)ᵏ⁻¹p; P(K ≤ m) = 1 − (1 − p)ᵐ; E[K] = 1/p\n",
    "\n",
    "- **K**: Trial number of the first success, taking values 1, 2, 3 and so on.\n",
    "- **p**: Constant success probability on an independent attempt.\n",
    "- **m**: A whole-number attempt budget.\n",
    "- **cost per attempt**: Comparable incremental cost incurred on every attempt.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative outreach team considers a scenario with a 20% qualified conversion probability per independent lead. Each attempted contact costs R40. The supervisor wants both the average cost and a finite-attempt coverage probability.\n",
    "\n",
    "- Success probability p = 0.20.\n",
    "- Attempt budget m = 8 contacts.\n",
    "- Incremental cost per attempt = R40.\n",
    "\n",
    "1. Expected attempts until the first success = 1/0.20 = 5.\n",
    "2. Expected contact cost until first success = 5 × R40 = R200, assuming every attempt has the same cost and the process can continue.\n",
    "3. Chance of no success in eight attempts = 0.80⁸ = 0.1677722. Therefore P(K ≤ 8) = 0.8322278.\n",
    "4. Chance that the first success still has not occurred after ten attempts is 0.80¹⁰ = 0.1073742.\n",
    "\n",
    "**Result:** Expected attempts 5 and expected contact cost R200; probability of a first success within eight attempts 83.22%.\n",
    "\n",
    "An eight-contact budget exceeds the expected five contacts but still leaves a 16.78% chance of no success in this simplified scenario. A finite campaign needs both a probability target and a stopping or escalation policy.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Attempts are independent and have the same success probability.\n",
    "- The first success is the stopping event; a multi-success target needs a different distribution.\n",
    "- Each attempt is classified as success or failure using the same rule.\n",
    "- Expected unbounded-attempt cost assumes constant per-attempt cost and continued attempts; a capped campaign has a different cost calculation.\n",
    "\n",
    "**Decision rule to adapt:** Choose an attempt policy using both the chance of success within the budget and the cost of continued attempts, then validate the constant-probability assumption.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy: geometric distribution and its trial-count convention](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.geom.html)\n"
   ],
   "id": "business-cell-019"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "geometric-distribution"
   },
   "execution_count": 10,
   "source": [
    "from scipy.stats import geom\n",
    "p = 0.20\n",
    "mean_attempts = geom.mean(p)\n",
    "print(f'Expected attempts: {mean_attempts:.2f}')\n",
    "print(f'Expected cost until success: R {mean_attempts*40:.2f}')\n",
    "print(f'First success within eight attempts: {geom.cdf(8,p):.2%}')\n",
    "print(f'No success after ten attempts: {geom.sf(10,p):.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Expected attempts: 5.00\n",
      "Expected cost until success: R 200.00\n",
      "First success within eight attempts: 83.22%\n",
      "No success after ten attempts: 10.74%\n"
     ]
    }
   ],
   "id": "business-cell-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 11. Negative binomial: repeated-success targets and overdispersed counts\n",
    "\n",
    "**Business question:** How variable is the effort needed to achieve several successes?\n",
    "\n",
    "A negative-binomial distribution can model failures before a target number of successes. A related parameterisation also describes count data whose variance exceeds its mean. State which interpretation is being used before calculating.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(F = f) = C(f+r−1,f)pʳ(1−p)ᶠ; E[F] = r(1−p)/p; total attempts = F+r\n",
    "\n",
    "- **r**: Required successes in the repeated-trial example; a positive dispersion/shape parameter in the count parameterisation.\n",
    "- **p**: Success probability in the repeated-trial interpretation.\n",
    "- **F**: Non-negative failures before the rth success, not total attempts.\n",
    "- **μ**: Mean count when using the alternative variance μ + μ²/r form.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative sales desk wants five conversions. The planning scenario assumes independent contacts with a 25% conversion probability. The manager asks whether a twenty-contact allocation is enough to reach the target.\n",
    "\n",
    "- Target r = 5 successes; p = 0.25 per contact.\n",
    "- Total contact budget = 20.\n",
    "- Every contact has one success/failure outcome in this simplified scenario.\n",
    "\n",
    "1. Expected failures = 5 × 0.75/0.25 = 15. Expected total contacts = 15 + 5 = 20.\n",
    "2. Variance of failures = 5 × 0.75/0.25² = 60. Adding five fixed successes does not change the variance of total attempts.\n",
    "3. Achieving the fifth success by contact twenty requires no more than 20 − 5 = 15 failures before that success.\n",
    "4. Calculate P(F ≤ 15) using nbinom with r = 5 and p = 0.25: 0.5851585.\n",
    "\n",
    "**Result:** The expected total is twenty contacts, but the chance of reaching five conversions by then is only 58.52%.\n",
    "\n",
    "The mean effort is not a high-coverage quota. A manager who needs a much higher chance of meeting the conversion target must compare larger contact budgets or a different feasible process.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The worked trial example uses independent contacts with constant p.\n",
    "- The success target is fixed and the variable counts failures until it is reached.\n",
    "- Fixed-window uses need comparable exposure or a model that adjusts for exposure.\n",
    "- Parameter uncertainty and future changes in the conversion process are not included in the numerical example.\n",
    "\n",
    "**Decision rule to adapt:** Use a threshold probability for the correctly defined count and select an operationally defensible parameterisation; test the fit against held-out periods or contacts.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy: negative-binomial definitions and mean/dispersion parameterisation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.nbinom.html)\n"
   ],
   "id": "business-cell-021"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "negative-binomial"
   },
   "execution_count": 11,
   "source": [
    "from scipy.stats import nbinom\n",
    "r, p = 5, 0.25\n",
    "contact_budget = 20\n",
    "failure_budget = contact_budget-r\n",
    "print(f'Expected total contacts: {nbinom.mean(r,p)+r:.2f}')\n",
    "print(f'Contact-count variance: {nbinom.var(r,p):.2f}')\n",
    "print(f'Five successes by contact 20: {nbinom.cdf(failure_budget,r,p):.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Expected total contacts: 20.00\n",
      "Contact-count variance: 60.00\n",
      "Five successes by contact 20: 58.52%\n"
     ]
    }
   ],
   "id": "business-cell-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 12. Hypergeometric distribution: sampling a finite lot\n",
    "\n",
    "**Business question:** What is the chance a sample finds a defect when items are drawn without replacement?\n",
    "\n",
    "The hypergeometric distribution models successes in a sample from a finite population with a stated composition. It accounts for the fact that each sampled item changes what remains in the lot.\n",
    "\n",
    "### Formula\n",
    "\n",
    "P(X = k) = C(K,k)C(N−K,n−k)/C(N,n); E[X] = nK/N\n",
    "\n",
    "- **N**: Total number of items in the finite lot.\n",
    "- **K**: Number with the counted property under the specified lot scenario.\n",
    "- **n**: Sample size drawn randomly without replacement.\n",
    "- **X**: Counted-property items found in the sample.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative warehouse compares a ten-item inspection with a lot of one hundred items. For this scenario calculation, suppose exactly eight items are defective. The aim is to understand detection probability, not to claim that eight is known in a live lot.\n",
    "\n",
    "- Lot size N = 100; scenario defects K = 8.\n",
    "- Random sample n = 10 without replacement.\n",
    "- Detection means observing at least one defective item.\n",
    "\n",
    "1. The expected number of defects in the sample is 10 × 8/100 = 0.8.\n",
    "2. The probability of no defects is C(8,0) × C(92,10)/C(100,10) = 0.4165533.\n",
    "3. Detection probability is P(X ≥ 1) = 1 − 0.4165533 = 0.5834467.\n",
    "4. Therefore, even a lot with eight defects can pass a zero-defects-observed sample with probability about 41.66% under this plan.\n",
    "\n",
    "**Result:** The ten-item sample detects at least one defect with probability 58.34%; it finds none with probability 41.66%.\n",
    "\n",
    "This sample is a limited detector for the stated lot composition. Increasing the sample, changing the acceptance threshold or adding process evidence may be needed if the consequence of accepting such a lot is unacceptable.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The lot is finite, with a fixed composition during sampling.\n",
    "- Sampling is genuinely random without replacement, not a convenient selection of accessible items.\n",
    "- Classification is accurate or inspection errors are modelled separately.\n",
    "- The example’s K = 8 is a scenario input; it is not inferred from a ten-item sample.\n",
    "\n",
    "**Decision rule to adapt:** Choose an acceptance-sampling plan using its performance across relevant lot compositions and the business consequences of each decision error.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy: hypergeometric distribution and finite sampling](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.hypergeom.html)\n"
   ],
   "id": "business-cell-023"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "hypergeometric-distribution"
   },
   "execution_count": 12,
   "source": [
    "from scipy.stats import hypergeom\n",
    "lot_size, defects, sample_size = 100, 8, 10\n",
    "no_defects_found = hypergeom.pmf(0,lot_size,defects,sample_size)\n",
    "detected = hypergeom.sf(0,lot_size,defects,sample_size)\n",
    "print(f'Expected sample defects: {sample_size*defects/lot_size:.2f}')\n",
    "print(f'No defects observed: {no_defects_found:.2%}')\n",
    "print(f'At least one defect observed: {detected:.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Expected sample defects: 0.80\n",
      "No defects observed: 41.66%\n",
      "At least one defect observed: 58.34%\n"
     ]
    }
   ],
   "id": "business-cell-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 13. Lognormal distribution: positive, right-skewed values\n",
    "\n",
    "**Business question:** How should we plan for positive costs or durations with occasional large outcomes?\n",
    "\n",
    "A lognormal model is useful when the logarithm of a positive measurement is approximately normal. Its mean, median and upper percentiles can differ substantially, making it relevant to budgets and tail exposure.\n",
    "\n",
    "### Formula\n",
    "\n",
    "ln(X) ~ Normal(μ,σ²); median(X) = exp(μ); E[X] = exp(μ+σ²/2); q-th percentile = exp(μ+σz_q)\n",
    "\n",
    "- **X**: A strictly positive value measured in a consistent unit.\n",
    "- **μ, σ**: Mean and positive standard deviation of the natural-log values.\n",
    "- **z_q**: Standard normal percentile at cumulative probability q.\n",
    "- **exp**: Exponentiation with base e; the inverse of the natural logarithm.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative repair company models per-job material costs with a lognormal scenario. The median is R1,000 and the standard deviation of the natural-log costs is 0.60.\n",
    "\n",
    "- μ = ln(1,000); σ = 0.60 on the log scale.\n",
    "- High-cost threshold = R2,000.\n",
    "- Single-job percentile of interest = 95%.\n",
    "\n",
    "1. The median is exp(ln(1,000)) = R1,000.\n",
    "2. Calculate the mean: exp(ln(1,000) + 0.60²/2) = 1,000 × exp(0.18) = R1,197.22.\n",
    "3. Use z_0.95 = 1.6448536: the 95th percentile is 1,000 × exp(0.60 × 1.6448536) = R2,682.94.\n",
    "4. The standardised log threshold for R2,000 is ln(2,000/1,000)/0.60 = 1.1552453. Its upper-tail probability is 12.3995%.\n",
    "\n",
    "**Result:** Median R1,000; expected single-job cost R1,197.22; 95th percentile R2,682.94; probability above R2,000 about 12.40%.\n",
    "\n",
    "Using the median as the expected cost would understate this model’s average material requirement. The upper percentile helps frame contingency discussions, but it does not determine a whole-month budget by itself.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Values are strictly positive; a genuine zero outcome needs a separate treatment or mixture model.\n",
    "- Natural-log values are approximately normal within the modelled regime.\n",
    "- Costs use a consistent currency basis, including any relevant inflation or price-period adjustment.\n",
    "- The example treats the parameters as known and does not quantify their estimation uncertainty.\n",
    "\n",
    "**Decision rule to adapt:** Use the lognormal model when positive data and log-scale diagnostics support it; choose budget protection using the appropriate aggregate-risk model.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: lognormal distribution and parameterisations](https://www.itl.nist.gov/div898/handbook/eda/section3/eda3669.htm)\n"
   ],
   "id": "business-cell-025"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "lognormal-distribution"
   },
   "execution_count": 13,
   "source": [
    "from math import log, exp\n",
    "from scipy.stats import lognorm\n",
    "mu, sigma = log(1000), 0.60\n",
    "scale = exp(mu)\n",
    "print(f'Median cost: R {scale:.2f}')\n",
    "print(f'Mean cost: R {lognorm.mean(sigma,scale=scale):.2f}')\n",
    "print(f'95th percentile: R {lognorm.ppf(0.95,sigma,scale=scale):.2f}')\n",
    "print(f'Cost above R2000: {lognorm.sf(2000,sigma,scale=scale):.2%}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Median cost: R 1000.00\n",
      "Mean cost: R 1197.22\n",
      "95th percentile: R 2682.94\n",
      "Cost above R2000: 12.40%\n"
     ]
    }
   ],
   "id": "business-cell-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14. Weibull distribution: reliability and changing failure risk\n",
    "\n",
    "**Business question:** Does an asset’s failure risk change as it ages?\n",
    "\n",
    "A Weibull lifetime model separates scale from hazard shape. It can describe decreasing, constant or increasing failure hazard and support reliability discussions when failure and censoring records are suitable.\n",
    "\n",
    "### Formula\n",
    "\n",
    "S(t) = exp(−(t/η)^β); F(t) = 1 − S(t); P(fail by t+u | survive to t) = 1 − S(t+u)/S(t)\n",
    "\n",
    "- **t**: Operating age from the defined starting point.\n",
    "- **η**: Positive scale or characteristic-life parameter in the same age units.\n",
    "- **β**: Positive shape parameter controlling how hazard changes with age.\n",
    "- **S(t), F(t)**: Survival probability and cumulative failure probability.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative pump component has a fitted planning scenario with shape 2 and scale 1,000 operating hours. The manager compares survival at 600 hours and the next 200 hours for a surviving component.\n",
    "\n",
    "- β = 2; η = 1,000 operating hours.\n",
    "- Current age t = 600 hours; additional horizon u = 200 hours.\n",
    "- B10 means the age by which 10% of modelled units fail.\n",
    "\n",
    "1. Survival to 600 hours is exp(−(600/1,000)²) = exp(−0.36) = 0.6976763.\n",
    "2. Cumulative failure by 600 hours is 1 − 0.6976763 = 30.2324%.\n",
    "3. For a component surviving to 600, next-200-hour risk is 1 − exp(−(0.80² − 0.60²)) = 24.4216%.\n",
    "4. B10 = 1,000 × sqrt(−ln(0.90)) = 324.59 hours. The mean is η × Gamma(1+1/β) = 886.23 hours, not 1,000.\n",
    "\n",
    "**Result:** Survival at 600 h 69.77%; conditional failure risk over the next 200 h 24.42%; B10 324.59 h.\n",
    "\n",
    "The increasing-hazard scenario gives an older surviving component a different risk from a new one. B10 describes a lifetime percentile; it is not automatically the cost-optimal replacement age.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The modelled units share a relevant lifetime mechanism or explicitly modelled covariates.\n",
    "- The age origin and operating exposure are measured consistently.\n",
    "- Censoring is handled appropriately rather than dropping units that have not failed.\n",
    "- The stated two-parameter Weibull shape is suitable; repairs and recurrent events may need a different process model.\n",
    "\n",
    "**Decision rule to adapt:** Use a lifetime curve that accounts for censoring and operating context, then choose policy through reliability-and-cost comparison rather than a percentile alone.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Weibull distribution](https://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm)\n"
   ],
   "id": "business-cell-027"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "weibull-distribution"
   },
   "execution_count": 14,
   "source": [
    "from scipy.stats import weibull_min\n",
    "shape, scale = 2, 1000\n",
    "s600 = weibull_min.sf(600,shape,scale=scale)\n",
    "s800 = weibull_min.sf(800,shape,scale=scale)\n",
    "print(f'Survival to 600 h: {s600:.2%}')\n",
    "print(f'Next 200 h risk, given survival to 600: {1-s800/s600:.2%}')\n",
    "print(f'B10 life: {weibull_min.ppf(0.10,shape,scale=scale):.2f} h')\n",
    "print(f'Mean lifetime: {weibull_min.mean(shape,scale=scale):.2f} h')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Survival to 600 h: 69.77%\n",
      "Next 200 h risk, given survival to 600: 24.42%\n",
      "B10 life: 324.59 h\n",
      "Mean lifetime: 886.23 h\n"
     ]
    }
   ],
   "id": "business-cell-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 15. Confidence interval for a population mean\n",
    "\n",
    "**Business question:** How precisely have we estimated the average, rather than just measured this sample?\n",
    "\n",
    "A confidence interval expresses sampling uncertainty around an estimated population mean. When the population standard deviation is unknown, a t interval uses the sample spread and sample size under appropriate sampling assumptions.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Two-sided interval = x̄ ± t_(1−α/2,n−1) × s/sqrt(n)\n",
    "\n",
    "- **x̄**: Sample mean of the measured outcome.\n",
    "- **s**: Sample standard deviation, calculated with n−1 in the variance denominator.\n",
    "- **n**: Number of independent observations.\n",
    "- **α**: One minus the confidence level; 0.05 for a 95% two-sided interval.\n",
    "- **t_(1−α/2,n−1)**: Student t percentile using n−1 degrees of freedom.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative repair operation collects 25 randomly selected, independent jobs from a stable and approximately normal job-time population. The sample mean is 42 minutes with sample standard deviation 10 minutes.\n",
    "\n",
    "- n = 25; sample mean = 42 minutes; sample SD = 10 minutes.\n",
    "- Two-sided confidence level = 95%.\n",
    "- A manager is considering an average-time objective of 45 minutes.\n",
    "\n",
    "1. Calculate the standard error: 10/sqrt(25) = 2 minutes.\n",
    "2. Degrees of freedom = 25 − 1 = 24. The 97.5th t percentile is 2.0638986.\n",
    "3. Margin = 2.0638986 × 2 = 4.1277971 minutes.\n",
    "4. Lower endpoint = 42 − 4.1277971 = 37.8722. Upper endpoint = 42 + 4.1277971 = 46.1278 minutes.\n",
    "\n",
    "**Result:** The 95% two-sided t confidence interval for the population mean is approximately 37.87–46.13 minutes.\n",
    "\n",
    "The observed mean is below 45 minutes, but this interval still includes population means above 45. It does not support a claim that 95% of individual repairs finish within 46.13 minutes.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The observations represent the target population rather than a convenient selected subset.\n",
    "- The basic formula assumes independent observations; repeated customers or clustered shifts need adjustment.\n",
    "- Exact t coverage requires normal observations, with appropriate large-sample robustness assessed rather than presumed.\n",
    "- The population standard deviation is unknown and the sample SD is an appropriate estimate of its spread.\n",
    "\n",
    "**Decision rule to adapt:** Define the practical threshold and the intended interval before analysing; if the plausible means change the action, improve the evidence or use a cautious staged decision.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: confidence limits for the mean](https://www.itl.nist.gov/div898/handbook/eda/section3/eda352.htm)\n"
   ],
   "id": "business-cell-029"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "confidence-mean"
   },
   "execution_count": 15,
   "source": [
    "from math import sqrt\n",
    "from scipy.stats import t\n",
    "n, mean, sample_sd = 25, 42, 10\n",
    "standard_error = sample_sd/sqrt(n)\n",
    "critical = t.ppf(0.975,n-1)\n",
    "margin = critical*standard_error\n",
    "print(f'Standard error: {standard_error:.2f} min')\n",
    "print(f'95% t interval for mean: {mean-margin:.2f} to {mean+margin:.2f} min')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Standard error: 2.00 min\n",
      "95% t interval for mean: 37.87 to 46.13 min\n"
     ]
    }
   ],
   "id": "business-cell-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 16. Confidence interval for a proportion: Wilson interval\n",
    "\n",
    "**Business question:** How uncertain is the defect, conversion or satisfaction rate estimated from a sample?\n",
    "\n",
    "A proportion confidence interval expresses uncertainty about a binary outcome rate. The Wilson interval is a score-based method that remains within 0–1 and is preferable to the simplest symmetric normal interval in many practical small-rate settings.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Wilson centre = (p̂ + z²/(2n))/(1+z²/n); half-width = z sqrt(p̂(1−p̂)/n + z²/(4n²))/(1+z²/n)\n",
    "\n",
    "- **p̂ = x/n**: Observed success proportion and its numerator/denominator.\n",
    "- **n**: Eligible independent trials in the basic binomial model.\n",
    "- **z**: Standard normal critical value; about 1.96 for a 95% two-sided interval.\n",
    "- **bounds**: Adjusted centre minus and plus the Wilson half-width.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative packaging inspection finds eight defective units among 200 randomly sampled units from a stable process. The manager asks whether the observed 4% rate establishes a defect probability below 5%.\n",
    "\n",
    "- x = 8 defective units; n = 200 inspected units.\n",
    "- Observed rate p̂ = 8/200 = 0.04.\n",
    "- 95% two-sided Wilson confidence interval.\n",
    "\n",
    "1. Use z = 1.95996398, so the denominator adjustment is 1 + z²/200 = 1.0192073.\n",
    "2. Adjusted centre = (0.04 + z²/400)/1.0192073 ≈ 0.0486689.\n",
    "3. Compute the Wilson half-width using the stated formula, approximately 0.0282632.\n",
    "4. Endpoints are 0.0204056 and 0.0769321, or 2.04% and 7.69%.\n",
    "\n",
    "**Result:** Observed defect rate 4.00%; 95% Wilson interval approximately 2.04%–7.69%.\n",
    "\n",
    "The sample is compatible with defect probabilities above 5%, so the observed 4% alone is not sufficient evidence for the proposed claim. A different planned one-sided requirement would need its corresponding analysis.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The basic Wilson calculation uses independent Bernoulli observations with a common p.\n",
    "- The sample is relevant to the rate being claimed and outcome labels are accurate.\n",
    "- The confidence level and whether the interval is one- or two-sided are chosen before inspecting the result.\n",
    "- Parameter uncertainty is addressed by the interval, but selection bias and misclassification are separate concerns.\n",
    "\n",
    "**Decision rule to adapt:** Use the pre-specified rate threshold and confidence bound, and separate an inconclusive result from evidence that the process meets or fails the requirement.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Wilson confidence intervals for proportions](https://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm)\n",
    "- [SciPy: binomtest and proportion confidence intervals](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binomtest.html)\n"
   ],
   "id": "business-cell-031"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "confidence-proportion"
   },
   "execution_count": 16,
   "source": [
    "from scipy.stats import binomtest\n",
    "defects, inspected = 8, 200\n",
    "interval = binomtest(defects,inspected).proportion_ci(confidence_level=0.95,method='wilson')\n",
    "print(f'Observed defect rate: {defects/inspected:.2%}')\n",
    "print(f'95% Wilson interval: {interval.low:.2%} to {interval.high:.2%}')\n",
    "print('Includes rates above 5%:', interval.high > 0.05)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Observed defect rate: 4.00%\n",
      "95% Wilson interval: 2.04% to 7.69%\n",
      "Includes rates above 5%: True\n"
     ]
    }
   ],
   "id": "business-cell-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 17. Sample size, precision and statistical power\n",
    "\n",
    "**Business question:** How much useful data should we plan before an experiment or survey?\n",
    "\n",
    "Sample size follows the decision and the uncertainty it must resolve. Planning an estimate to a margin of error is different from powering a test to detect a specified effect.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Two-group normal approximation: n per group ≈ 2(z_(1−α/2)+z_(power))²σ²/Δ²; proportion estimation: n ≈ z²p(1−p)/e²\n",
    "\n",
    "- **Δ**: Smallest difference in means worth detecting, in original outcome units.\n",
    "- **σ**: Assumed common outcome standard deviation, ideally informed by relevant prior data.\n",
    "- **α, power**: False-positive rate under the null and target detection probability at the specified alternative.\n",
    "- **e**: Desired absolute half-width for a proportion estimate; 0.05 means five percentage points.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative service company plans a randomised two-group trial. A five-minute mean improvement matters economically, and prior comparable work suggests a ten-minute standard deviation. A separate survey needs roughly five-percentage-point precision.\n",
    "\n",
    "- Trial: Δ = 5 minutes, σ = 10 minutes, two-sided α = 0.05, power = 0.80, equal groups.\n",
    "- Normal-approximation planning calculation with common variance.\n",
    "- Survey: 95% confidence, p = 0.5 and e = 0.05; simple independent sampling with no finite-population correction.\n",
    "\n",
    "1. Use z_0.975 = 1.959964 and z_0.80 = 0.841621.\n",
    "2. Trial n per group ≈ 2 × (1.959964 + 0.841621)² × 10²/5² = 62.791; round upward to 63 usable observations per group.\n",
    "3. If only 80% of invited trial participants provide a usable outcome, 63/0.80 = 78.75 suggests inviting at least 79 per group, without guaranteeing completion.\n",
    "4. Survey n ≈ 1.959964² × 0.5 × 0.5/0.05² = 384.146; round upward to 385 usable responses.\n",
    "\n",
    "**Result:** Approximate trial plan: 63 usable observations per group. Separate survey precision plan: 385 responses.\n",
    "\n",
    "The two sample sizes answer different questions. The trial figure is a starting approximation; a final t-based, cluster-adjusted or binary-outcome design may need a different size.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The worked trial approximation assumes equal independent groups and a common known or planning standard deviation.\n",
    "- The alternative effect Δ is specified in advance and measured in the same units as σ.\n",
    "- The survey formula assumes simple independent sampling; large sampling fractions and complex designs need adjustment.\n",
    "- A response-rate inflation is an expectation, not a promise of an achieved usable sample.\n",
    "\n",
    "**Decision rule to adapt:** Choose a feasible design that can resolve the minimum useful effect or estimation precision; if it cannot, change the plan before treating the study as decisive.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: sample sizes required for mean comparisons and precision](https://www.itl.nist.gov/div898/handbook/prc/section2/prc222.htm)\n",
    "- [NIST: selecting sample sizes](https://www.itl.nist.gov/div898/handbook/ppc/section3/ppc333.htm)\n"
   ],
   "id": "business-cell-033"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "sample-size-power"
   },
   "execution_count": 17,
   "source": [
    "from math import ceil\n",
    "from scipy.stats import norm\n",
    "alpha, power = 0.05, 0.80\n",
    "sd, useful_difference = 10, 5\n",
    "z_alpha = norm.ppf(1-alpha/2)\n",
    "z_power = norm.ppf(power)\n",
    "per_group = ceil(2*(z_alpha+z_power)**2*sd**2/useful_difference**2)\n",
    "survey_size = ceil(z_alpha**2*0.5*0.5/0.05**2)\n",
    "print(f'Approximate usable trial observations per group: {per_group}')\n",
    "print(f'Invitations per group at 80% completion: {ceil(per_group/0.80)}')\n",
    "print(f'Survey responses for +/-5 percentage points: {survey_size}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Approximate usable trial observations per group: 63\n",
      "Invitations per group at 80% completion: 79\n",
      "Survey responses for +/-5 percentage points: 385\n"
     ]
    }
   ],
   "id": "business-cell-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 18. Bayesian updating: beta-binomial learning about a rate\n",
    "\n",
    "**Business question:** How should prior knowledge and a new small sample combine when estimating a business rate?\n",
    "\n",
    "Beta-binomial updating represents uncertainty about an unknown binary-outcome probability. A disclosed beta prior is updated with new successes and failures to produce a posterior distribution for the rate.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Prior p ~ Beta(a,b); posterior p | x,n ~ Beta(a+x,b+n−x); posterior mean = (a+x)/(a+b+n)\n",
    "\n",
    "- **a,b**: Positive prior shape parameters; their relevance and strength must be justified.\n",
    "- **x,n**: New successes and eligible trials, counted once and using the same outcome definition.\n",
    "- **p**: Unknown underlying success probability.\n",
    "- **credible interval**: An interval containing a stated posterior probability under the chosen model.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative service firm begins a new booking channel with a modest Beta(2,8) prior on conversion. It then observes ten conversions among thirty comparable enquiries. The business threshold under discussion is a 25% conversion rate.\n",
    "\n",
    "- Prior Beta(2,8), with prior mean 2/10 = 20%.\n",
    "- New observations: x = 10 conversions; n = 30 enquiries.\n",
    "- Posterior interval: equal-tailed 95%; practical threshold p > 0.25.\n",
    "\n",
    "1. Update the success parameter: a + x = 2 + 10 = 12. Update the other parameter: b + n − x = 8 + 30 − 10 = 28.\n",
    "2. The posterior is Beta(12,28), with mean 12/(12+28) = 30.00%. The observed rate alone is 10/30 = 33.33%.\n",
    "3. The 2.5th and 97.5th posterior percentiles are approximately 0.1701959 and 0.4487363.\n",
    "4. The posterior probability that p exceeds 0.25 is 0.7468608. A future ten-enquiry count has posterior predictive mean 10 × 0.30 = 3 conversions.\n",
    "\n",
    "**Result:** Posterior mean 30.00%; 95% credible interval about 17.02%–44.87%; posterior probability above 25% about 74.69%.\n",
    "\n",
    "The new data raise the rate estimate, but substantial uncertainty remains. A 74.69% model-based probability is a decision input, not a universally sufficient reason to expand the channel.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The likelihood uses conditionally independent Bernoulli trials sharing a relevant p.\n",
    "- Prior and new data address the same rate or any differences are explicitly modelled.\n",
    "- Prior parameters are fixed before the new evidence is used, with their strength disclosed.\n",
    "- The posterior probability is conditional on the model and does not remove sampling bias or misclassification.\n",
    "\n",
    "**Decision rule to adapt:** Select an action using a pre-agreed practical threshold or expected loss, and show whether the decision survives defensible alternative priors.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Bayesian updating and conjugate beta priors](https://www.itl.nist.gov/div898/handbook/apr/section2/apr1a.htm)\n",
    "- [SciPy: beta distribution](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html)\n",
    "- [SciPy: beta-binomial predictive distribution](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.betabinom.html)\n"
   ],
   "id": "business-cell-035"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "bayesian-updating"
   },
   "execution_count": 18,
   "source": [
    "from scipy.stats import beta, betabinom\n",
    "a, b = 2, 8\n",
    "successes, trials = 10, 30\n",
    "post_a, post_b = a+successes, b+trials-successes\n",
    "low, high = beta.ppf([0.025,0.975],post_a,post_b)\n",
    "print(f'Posterior mean rate: {beta.mean(post_a,post_b):.2%}')\n",
    "print(f'95% credible interval: {low:.2%} to {high:.2%}')\n",
    "print(f'P(rate above 25%): {beta.sf(0.25,post_a,post_b):.2%}')\n",
    "print(f'Predictive mean successes in 10 trials: {betabinom.mean(10,post_a,post_b):.2f}')"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Posterior mean rate: 30.00%\n",
      "95% credible interval: 17.02% to 44.87%\n",
      "P(rate above 25%): 74.69%\n",
      "Predictive mean successes in 10 trials: 3.00\n"
     ]
    }
   ],
   "id": "business-cell-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 19. Welch’s independent-samples t-test\n",
    "\n",
    "**Business question:** Do two independent suppliers, teams or processes have different average performance?\n",
    "\n",
    "Welch’s t-test compares two population means while allowing different sample sizes and variances. It turns an observed average difference into an estimate with uncertainty, helping a business distinguish a plausible operational improvement from ordinary sampling variation.\n",
    "\n",
    "### Formula\n",
    "\n",
    "difference = mean_A − mean_B; SE = √(s_A²/n_A + s_B²/n_B); t = difference/SE; CI = difference ± t_(0.975,ν) × SE\n",
    "\n",
    "- **mean_A, mean_B**: Sample averages in the original business units.\n",
    "- **s_A, s_B**: Sample standard deviations, calculated with n−1 in the denominator.\n",
    "- **n_A, n_B**: Numbers of independent observations.\n",
    "- **ν**: Welch–Satterthwaite approximate degrees of freedom.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative South African repair business comparing turnaround time from two independent spare-parts suppliers.\n",
    "\n",
    "- Supplier A: n=30, mean=18 minutes, sample SD=4 minutes.\n",
    "- Supplier B: n=25, mean=22 minutes, sample SD=7 minutes.\n",
    "- Predefined two-sided test and 95% confidence interval.\n",
    "\n",
    "1. Difference A−B = 18−22 = −4 minutes.\n",
    "2. Variance of the difference = 16/30 + 49/25 = 2.49333; SE = 1.57903 minutes.\n",
    "3. Welch degrees of freedom ≈36.596; t≈−2.533, with p≈0.015724.\n",
    "4. The 95% interval is approximately −7.201 to −0.799 minutes.\n",
    "\n",
    "**Result:** A’s sample suggests a lower mean turnaround, with an estimated reduction of 4 minutes relative to B.\n",
    "\n",
    "The interval supports a mean reduction under the model, but individual A jobs may still take longer than individual B jobs. Across 1,000 comparable jobs, four minutes represents 66.7 job-hours less elapsed turnaround. It represents released staff capacity only if those minutes are active staff work or demonstrably release a constrained resource; it is not an automatic payroll saving.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Orders within and between groups are independent; repeated jobs from the same customer or day may require clustered analysis.\n",
    "- The data represent the suppliers and conditions about which the decision will be made.\n",
    "- Means are meaningful for the outcome; extreme skew or influential errors need investigation.\n",
    "- The t approximation is adequate for the sample sizes and distributions; small severe-tailed samples can be unreliable.\n",
    "\n",
    "**Decision rule to adapt:** Choose a supplier on total value only after the estimated difference and its uncertainty meet a pre-agreed practical requirement. A small p-value alone is not a purchasing rule.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · independent samples and Welch’s test](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html)\n"
   ],
   "id": "business-cell-037"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "welch-t-test"
   },
   "execution_count": 19,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "mean_a, sd_a, n_a = 18, 4, 30\n",
    "mean_b, sd_b, n_b = 22, 7, 25\n",
    "test = stats.ttest_ind_from_stats(mean_a, sd_a, n_a, mean_b, sd_b, n_b, equal_var=False)\n",
    "v_a, v_b = sd_a**2 / n_a, sd_b**2 / n_b\n",
    "se = np.sqrt(v_a + v_b)\n",
    "df = (v_a + v_b)**2 / (v_a**2 / (n_a-1) + v_b**2 / (n_b-1))\n",
    "margin = stats.t.ppf(0.975, df) * se\n",
    "print(\"Difference A-B (minutes):\", round(mean_a-mean_b, 3))\n",
    "print(\"Welch t, df, p:\", round(test.statistic, 3), round(df, 3), round(test.pvalue, 6))\n",
    "print(\"95% CI:\", round(mean_a-mean_b-margin, 3), round(mean_a-mean_b+margin, 3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Difference A-B (minutes): -4\n",
      "Welch t, df, p: -2.533 36.596 0.015724\n",
      "95% CI: -7.201 -0.799\n"
     ]
    }
   ],
   "id": "business-cell-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 20. Paired t-test and before–after change\n",
    "\n",
    "**Business question:** Did the same machines, people or jobs improve after a change?\n",
    "\n",
    "A paired t-test analyses the difference within each matched unit. By comparing like with like, it can remove stable differences between units and estimate an average change more precisely than treating the before and after values as unrelated samples.\n",
    "\n",
    "### Formula\n",
    "\n",
    "d_i = before_i − after_i; mean reduction = mean(d); SE = s_d/√n; t = mean(d)/SE; df = n−1\n",
    "\n",
    "- **d_i**: The reduction within matched unit i.\n",
    "- **s_d**: Sample standard deviation of the paired reductions.\n",
    "- **n**: Number of complete independent pairs.\n",
    "- **df**: Degrees of freedom for the t distribution.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative timed task completed by eight technicians before and after a revised work instruction.\n",
    "\n",
    "- Before minutes: 30, 28, 35, 32, 31, 29, 34, 33.\n",
    "- After minutes, in the same technician order: 27, 27, 31, 30, 28, 27, 30, 31.\n",
    "- Positive differences mean faster completion after the change.\n",
    "\n",
    "1. Within-person reductions are 3, 1, 4, 2, 3, 2, 4 and 2 minutes.\n",
    "2. Their average is 21/8 = 2.625 minutes; their sample SD is approximately 1.06066.\n",
    "3. SE = 1.06066/√8 = 0.375; t = 2.625/0.375 = 7 with 7 degrees of freedom.\n",
    "4. The two-sided p-value is about 0.000212 and the 95% interval is 1.738–3.512 minutes.\n",
    "\n",
    "**Result:** The observed sample supports a positive average time reduction for the matched task.\n",
    "\n",
    "A shorter average time is valuable only if first-pass quality, safety and workload remain acceptable. The small illustrative sample and uncontrolled timing cannot isolate the work instruction from practice or other changes.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The matching is meaningful and correctly aligned; row order alone is not evidence of a pair.\n",
    "- Differences from separate pairs are independent; repeated observations from one technician require additional modelling.\n",
    "- For small samples, differences should be reasonably compatible with a normal distribution without extreme influential values.\n",
    "- The measurement method and comparison conditions are sufficiently consistent for the change to be interpretable.\n",
    "\n",
    "**Decision rule to adapt:** Predefine the minimum useful reduction and acceptable quality outcomes. Confirm that the interval and the study design support the decision, then validate in ordinary work.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · related-samples t-test](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_rel.html)\n"
   ],
   "id": "business-cell-039"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "paired-t-test"
   },
   "execution_count": 20,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "before = np.array([30,28,35,32,31,29,34,33])\n",
    "after = np.array([27,27,31,30,28,27,30,31])\n",
    "difference = before - after\n",
    "test = stats.ttest_rel(before, after)\n",
    "mean = difference.mean()\n",
    "se = difference.std(ddof=1) / np.sqrt(len(difference))\n",
    "margin = stats.t.ppf(0.975, len(difference)-1) * se\n",
    "print(\"Mean reduction (minutes):\", round(mean, 3))\n",
    "print(\"t and p:\", round(test.statistic, 3), round(test.pvalue, 6))\n",
    "print(\"95% CI:\", round(mean-margin, 3), round(mean+margin, 3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Mean reduction (minutes): 2.625\n",
      "t and p: 7.0 0.000212\n",
      "95% CI: 1.738 3.512\n"
     ]
    }
   ],
   "id": "business-cell-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 21. A/B testing for conversion rates\n",
    "\n",
    "**Business question:** Does a changed offer or customer journey improve conversion enough to justify rollout?\n",
    "\n",
    "A fixed-horizon A/B test compares two independently assigned experiences using a predefined outcome. Conversion counts can estimate an absolute rate difference, its uncertainty and an economic consequence, while random allocation helps separate the experience from differences in the visitors receiving it.\n",
    "\n",
    "### Formula\n",
    "\n",
    "difference = p_B−p_A; pooled p = (x_A+x_B)/(n_A+n_B); z = difference/√[pooled p(1−pooled p)(1/n_A+1/n_B)]\n",
    "\n",
    "- **x_A, x_B**: Success counts from independently assigned units.\n",
    "- **n_A, n_B**: Eligible units with the defined outcome window.\n",
    "- **p_A, p_B**: Observed success proportions in each arm.\n",
    "- **difference**: Absolute rate change; multiply by 100 for percentage points.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative online retailer testing a clearer checkout on independent eligible visitors.\n",
    "\n",
    "- Control A: 80 purchases from 1,000 visitors, or 8%.\n",
    "- Variant B: 110 purchases from 1,000 visitors, or 11%.\n",
    "- Contribution per extra purchase is assumed R120 before any new intervention cost.\n",
    "\n",
    "1. Absolute difference = 0.11−0.08 = 0.03, or 3 percentage points; relative lift is 37.5%.\n",
    "2. The pooled null conversion estimate is 190/2,000 = 0.095.\n",
    "3. The two-sided large-sample z test gives z≈2.288 and p≈0.022149.\n",
    "4. A separate unpooled normal interval for the difference is approximately 0.433–5.567 percentage points.\n",
    "\n",
    "**Result:** At the observed difference, 1,000 comparable visitors would produce 30 extra purchases and R3,600 in extra contribution before new costs.\n",
    "\n",
    "The lower and upper interval endpoints imply materially different business cases. This calculation assumes a well-run randomised test; it does not promise that the observed lift will persist after rollout.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The two arms contain independent Bernoulli units with no material cross-arm contamination.\n",
    "- Randomisation and measurement are implemented correctly, including the intended exposure denominator.\n",
    "- Counts are sufficiently large for the normal approximation; sparse outcomes require another method.\n",
    "- The fixed horizon and analysis plan are respected, including adjustment for multiple variants or outcomes.\n",
    "\n",
    "**Decision rule to adapt:** Roll out when the practical effect, uncertainty, implementation cost and guardrails jointly meet the pre-agreed decision standard; investigate surprising assignment or tracking problems first.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [statsmodels · two-sample proportion z-test](https://www.statsmodels.org/stable/generated/statsmodels.stats.proportion.proportions_ztest.html)\n"
   ],
   "id": "business-cell-041"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "ab-testing"
   },
   "execution_count": 21,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "a_success, a_n = 80, 1000\n",
    "b_success, b_n = 110, 1000\n",
    "a_rate, b_rate = a_success/a_n, b_success/b_n\n",
    "difference = b_rate - a_rate\n",
    "pooled = (a_success+b_success)/(a_n+b_n)\n",
    "test_se = np.sqrt(pooled*(1-pooled)*(1/a_n+1/b_n))\n",
    "z = difference/test_se\n",
    "p = 2*stats.norm.sf(abs(z))\n",
    "interval_se = np.sqrt(a_rate*(1-a_rate)/a_n + b_rate*(1-b_rate)/b_n)\n",
    "low, high = difference-1.96*interval_se, difference+1.96*interval_se\n",
    "print(\"Lift (percentage points):\", round(100*difference, 3))\n",
    "print(\"Two-sided z and p:\", round(z, 3), round(p, 6))\n",
    "print(\"Approximate 95% CI (points):\", round(100*low, 3), round(100*high, 3))\n",
    "print(\"Illustrative extra contribution / 1000 visitors (R):\", round(1000*difference*120, 2))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Lift (percentage points): 3.0\n",
      "Two-sided z and p: 2.288 0.022149\n",
      "Approximate 95% CI (points): 0.433 5.567\n",
      "Illustrative extra contribution / 1000 visitors (R): 3600.0\n"
     ]
    }
   ],
   "id": "business-cell-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 22. Chi-square tests for categorical relationships\n",
    "\n",
    "**Business question:** Are complaint, return or purchasing categories related to channel, location or customer group?\n",
    "\n",
    "A chi-square independence test compares observed category counts with the counts expected if two categorical variables were unrelated. It is useful for finding a pattern worth investigating, with the strength and operational meaning assessed separately from the p-value.\n",
    "\n",
    "### Formula\n",
    "\n",
    "E_ij = row_total_i × column_total_j / N; χ² = Σ[(O_ij−E_ij)²/E_ij]; V = √[χ²/(N × min(r−1,c−1))]\n",
    "\n",
    "- **O_ij**: Observed count in row i and column j.\n",
    "- **E_ij**: Expected count under independence.\n",
    "- **N**: Total independent observations.\n",
    "- **r, c**: Number of rows and columns.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative retailer comparing 30-day returns for online and in-store purchases.\n",
    "\n",
    "- Online: 30 returned and 270 not returned, total 300.\n",
    "- In-store: 10 returned and 190 not returned, total 200.\n",
    "- Use Pearson’s chi-square test without the optional 2×2 continuity correction.\n",
    "\n",
    "1. The overall return rate is 40/500 = 8%.\n",
    "2. Expected online counts are 24 and 276; expected in-store counts are 16 and 184.\n",
    "3. Adding the four contributions gives χ²≈4.076 with 1 degree of freedom and p≈0.043494.\n",
    "4. Cramer’s V = √(4.076/500) ≈0.090; observed return rates are 10% and 5%.\n",
    "\n",
    "**Result:** The sample contains evidence of an association between channel and return outcome under the test assumptions.\n",
    "\n",
    "The association is not proof that online selling causes returns. Product mix, customer selection or fulfilment differences could explain it. The return-rate difference and avoidable cost are more decision-relevant than the significance label alone.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Observations are independent; repeated purchases from one customer may require customer-level or clustered analysis.\n",
    "- Categories are consistently recorded, mutually exclusive and collectively suitable for the business question.\n",
    "- Expected cell counts are adequate for the chosen chi-square approximation.\n",
    "- The observed sample represents the comparison population; different sampling designs need appropriate adjustment.\n",
    "\n",
    "**Decision rule to adapt:** Investigate a meaningful categorical association when the recording quality and test approximation are sound, but base corrective action on confirmed causes and business impact.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · chi-square contingency analysis](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.contingency.chi2_contingency.html)\n"
   ],
   "id": "business-cell-043"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "chi-square"
   },
   "execution_count": 22,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "observed = np.array([[30,270],[10,190]])\n",
    "test = stats.chi2_contingency(observed, correction=False)\n",
    "v = np.sqrt(test.statistic / observed.sum())\n",
    "print(\"Expected counts:\", test.expected_freq.tolist())\n",
    "print(\"Chi-square, df, p:\", round(test.statistic, 3), test.dof, round(test.pvalue, 6))\n",
    "print(\"Cramer's V:\", round(v, 3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Expected counts: [[24.0, 276.0], [16.0, 184.0]]\n",
      "Chi-square, df, p: 4.076 1 0.043494\n",
      "Cramer's V: 0.09\n"
     ]
    }
   ],
   "id": "business-cell-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 23. One-way ANOVA for several group means\n",
    "\n",
    "**Business question:** Do several production lines, branches or treatments have the same average outcome?\n",
    "\n",
    "One-way analysis of variance compares several group means in one overall test. It separates between-group differences from within-group variation, helping a business decide whether a factor deserves further investigation while controlling the initial comparison more coherently than many unplanned t-tests.\n",
    "\n",
    "### Formula\n",
    "\n",
    "SS_between = Σ n_g(mean_g−grand_mean)²; SS_within = ΣΣ(y_ig−mean_g)²; F = [SS_between/(k−1)]/[SS_within/(N−k)]\n",
    "\n",
    "- **k**: Number of groups.\n",
    "- **N**: Total number of observations.\n",
    "- **n_g**: Number of observations in group g.\n",
    "- **η²**: SS_between divided by total SS; a sample effect-size summary.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative accepted units per hour measured on three independent packing lines under comparable work.\n",
    "\n",
    "- A: 48, 50, 49, 51, 52 units/hour.\n",
    "- B: 55, 54, 56, 53, 57 units/hour.\n",
    "- C: 50, 52, 51, 49, 53 units/hour.\n",
    "\n",
    "1. Group means are 50, 55 and 51; the grand mean is 52.\n",
    "2. Between-group SS = 5×[(50−52)²+(55−52)²+(51−52)²] = 70.\n",
    "3. Within-group SS = 10+10+10 = 30; df are 2 and 12.\n",
    "4. F = (70/2)/(30/12) = 14; p≈0.000729 and η² = 70/100 = 0.70.\n",
    "\n",
    "**Result:** The illustrative data provide evidence that not all three population means are equal under the ordinary ANOVA assumptions.\n",
    "\n",
    "The test does not establish that B differs from both other lines or that buying B’s equipment would reproduce the result. Operator, product and scheduling differences need to be controlled before making that investment.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Groups contain independent observations; serial hours from one shift can violate this assumption.\n",
    "- For the ordinary test, errors have a common variance across groups.\n",
    "- Within-group errors are sufficiently compatible with normality for the sample sizes, particularly when samples are small.\n",
    "- The design separates the intended factor from important confounding variables or clearly acknowledges those limitations.\n",
    "\n",
    "**Decision rule to adapt:** Use the overall test to decide whether further planned comparison is warranted, then require a practical improvement and a credible design before changing the business.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · ordinary and Welch one-way ANOVA](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f_oneway.html)\n"
   ],
   "id": "business-cell-045"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "anova"
   },
   "execution_count": 23,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "groups = [np.array([48,50,49,51,52]), np.array([55,54,56,53,57]), np.array([50,52,51,49,53])]\n",
    "test = stats.f_oneway(*groups)\n",
    "grand_mean = np.concatenate(groups).mean()\n",
    "between = sum(len(g)*(g.mean()-grand_mean)**2 for g in groups)\n",
    "within = sum(((g-g.mean())**2).sum() for g in groups)\n",
    "eta_squared = between/(between+within)\n",
    "print(\"Group means:\", [round(float(g.mean()), 2) for g in groups])\n",
    "print(\"Between and within SS:\", round(between, 3), round(within, 3))\n",
    "print(\"F and p:\", round(test.statistic, 3), round(test.pvalue, 6))\n",
    "print(\"Eta-squared:\", round(eta_squared, 3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Group means: [50.0, 55.0, 51.0]\n",
      "Between and within SS: 70.0 30.0\n",
      "F and p: 14.0 0.000729\n",
      "Eta-squared: 0.7\n"
     ]
    }
   ],
   "id": "business-cell-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 24. Rank-based comparisons and Mann–Whitney U\n",
    "\n",
    "**Business question:** Do two independent groups show a distributional difference when raw-value assumptions are difficult?\n",
    "\n",
    "Rank-based tests compare the ordering of observations rather than assuming that the original measurements follow a normal distribution. Mann–Whitney U is a common independent-group method; its interpretation must match the question and the assumptions, especially when group shapes or spreads differ.\n",
    "\n",
    "### Formula\n",
    "\n",
    "U_A = R_A − n_A(n_A+1)/2; pairwise superiority estimate = U_A/(n_A n_B)\n",
    "\n",
    "- **R_A**: Sum of pooled ranks for group A, using average ranks for ties.\n",
    "- **n_A, n_B**: Independent observations in the two groups.\n",
    "- **U_A**: A-over-B pairwise wins, with ties counted as half.\n",
    "- **superiority**: Estimated P(A>B) + 0.5P(A=B), not a causal probability.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative delivery-day samples from two independent spare-parts suppliers.\n",
    "\n",
    "- Supplier A: 4, 5, 6, 7, 8, 9 days.\n",
    "- Supplier B: 6, 7, 8, 9, 10, 11 days.\n",
    "- Use a two-sided asymptotic test with tie correction and the default continuity correction.\n",
    "\n",
    "1. The sample medians are 6.5 and 8.5 days, but these medians are descriptive summaries rather than the complete test definition.\n",
    "2. Pooling and ranking gives U_A = 8 out of 6×6 = 36 pairwise comparisons.\n",
    "3. The superiority estimate is 8/36 ≈0.222, including half-ties; A observations tend to be smaller in this sample.\n",
    "4. The tie-corrected normal approximation gives p≈0.125530.\n",
    "\n",
    "**Result:** At a preselected 5% level, these small samples do not provide strong evidence against the equal-distributions null.\n",
    "\n",
    "This does not show the suppliers are equivalent. The observed tendency may still matter operationally, and the sample is small. A purchasing decision needs uncertainty, tail delays, price and a larger representative comparison.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Observations within and between groups are independent.\n",
    "- The ordering of the measured outcome is meaningful and consistently recorded.\n",
    "- The test method correctly handles ties and the sample sizes.\n",
    "- A median or pure location-shift interpretation needs additional equal-shape assumptions beyond the basic rank comparison.\n",
    "\n",
    "**Decision rule to adapt:** Match the rank-based hypothesis to the decision, report the actual distributional pattern, and require a practical and adequately supported difference before acting.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · Mann–Whitney U and interpretation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mannwhitneyu.html)\n"
   ],
   "id": "business-cell-047"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "nonparametric-tests"
   },
   "execution_count": 24,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "a = np.array([4,5,6,7,8,9])\n",
    "b = np.array([6,7,8,9,10,11])\n",
    "test = stats.mannwhitneyu(a, b, alternative=\"two-sided\", method=\"asymptotic\")\n",
    "superiority = test.statistic/(len(a)*len(b))\n",
    "print(\"Median days A/B:\", np.median(a), np.median(b))\n",
    "print(\"U and tie-corrected approximate p:\", round(test.statistic, 3), round(test.pvalue, 6))\n",
    "print(\"P(A exceeds B), counting ties half:\", round(superiority, 3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Median days A/B: 6.5 8.5\n",
      "U and tie-corrected approximate p: 8.0 0.12553\n",
      "P(A exceeds B), counting ties half: 0.222\n"
     ]
    }
   ],
   "id": "business-cell-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 25. Bootstrap uncertainty from resampling\n",
    "\n",
    "**Business question:** How uncertain is a median, cost estimate or other statistic when a simple textbook interval is awkward?\n",
    "\n",
    "The bootstrap approximates how a statistic might vary across repeated samples by repeatedly resampling the observed data. It can support practical uncertainty analysis for statistics such as medians, but it inherits the limits of the original sample and the sampling design.\n",
    "\n",
    "### Formula\n",
    "\n",
    "For b=1,…,B: sample n rows with replacement and calculate θ*_b; percentile interval = [quantile_0.025(θ*), quantile_0.975(θ*)]\n",
    "\n",
    "- **n**: Number of original observational units.\n",
    "- **B**: Number of bootstrap resamples.\n",
    "- **θ**: Statistic of interest, such as a median.\n",
    "- **θ*_b**: The statistic calculated from bootstrap resample b.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative service invoices used to describe a typical completed job rather than forecast total revenue.\n",
    "\n",
    "- Eight invoice values: R180, R220, R250, R270, R300, R340, R420 and R700.\n",
    "- Target statistic: the sample median.\n",
    "- Use 10,000 ordinary resamples, percentile endpoints and NumPy random seed 42.\n",
    "\n",
    "1. Sort the original observations; the middle values are 270 and 300, giving median R285.\n",
    "2. Draw eight values with replacement for each resample and calculate its median.\n",
    "3. Repeat 10,000 times and sort or quantile the resulting medians.\n",
    "4. With the stated seed and implementation, the 2.5th and 97.5th percentiles are approximately R220 and R420.\n",
    "\n",
    "**Result:** The illustrative percentile bootstrap interval is R220–R420 around a sample median of R285.\n",
    "\n",
    "The wide interval reflects limited information in eight invoices. It is not an interval covering 95% of individual future invoices, nor a guarantee of exact 95% coverage for the population median.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The observed data reasonably represent the population or process of interest.\n",
    "- The resampling design preserves relevant pairing, clustering or time dependence.\n",
    "- The statistic and sample contain enough information for the bootstrap approximation to be useful.\n",
    "- Any cleaning and selection rules are defensible and documented rather than chosen to tighten the interval.\n",
    "\n",
    "**Decision rule to adapt:** Use bootstrap uncertainty as an input to a decision only when the sampling design and method are credible; widen the evidence base when the interval spans materially different actions.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · bootstrap procedures and interval methods](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bootstrap.html)\n"
   ],
   "id": "business-cell-049"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "bootstrap"
   },
   "execution_count": 25,
   "source": [
    "import numpy as np\n",
    "rng = np.random.default_rng(42)\n",
    "invoices = np.array([180,220,250,270,300,340,420,700])\n",
    "medians = []\n",
    "for repeat in range(10000):\n",
    "    sample = rng.choice(invoices, size=len(invoices), replace=True)\n",
    "    medians.append(np.median(sample))\n",
    "low, high = np.quantile(medians, [0.025, 0.975])\n",
    "print(\"Sample median (R):\", round(np.median(invoices), 2))\n",
    "print(\"Percentile bootstrap 95% CI (R):\", round(low, 2), round(high, 2))\n",
    "print(\"Resamples:\", len(medians))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Sample median (R): 285.0\n",
      "Percentile bootstrap 95% CI (R): 220.0 420.0\n",
      "Resamples: 10000\n"
     ]
    }
   ],
   "id": "business-cell-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 26. Multiple testing and false-discovery control\n",
    "\n",
    "**Business question:** How can a business investigate many effects without mistaking routine false positives for a list of winners?\n",
    "\n",
    "Testing many hypotheses creates many opportunities for a chance finding. Multiplicity procedures adjust the decision rule for the collection of tests. Benjamini–Hochberg targets the expected false-discovery proportion, while familywise methods address the chance of making any false rejection in a defined family.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Sort p_(1)≤…≤p_(m); k = largest i with p_(i)≤i q/m; reject ranks 1…k. BH adjusted p_(i) = min[1, min_(j≥i)(m p_(j)/j)].\n",
    "\n",
    "- **m**: Number of hypotheses in the declared family.\n",
    "- **q**: Chosen false-discovery-rate target.\n",
    "- **p_(i)**: The raw p-value at sorted rank i.\n",
    "- **k**: Largest passing rank; no rejection if none passes.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative analyst screens six planned differences in order-processing outcomes.\n",
    "\n",
    "- Raw p-values: 0.001, 0.010, 0.030, 0.040, 0.200 and 0.600.\n",
    "- All six tests belong to the same prespecified exploratory family.\n",
    "- Use Benjamini–Hochberg at q=0.05.\n",
    "\n",
    "1. The BH thresholds are approximately 0.00833, 0.01667, 0.02500, 0.03333, 0.04167 and 0.05000.\n",
    "2. The largest passing rank is 2: 0.010≤0.01667, while later ranks do not pass.\n",
    "3. The adjusted p-values are 0.006, 0.030, 0.060, 0.060, 0.240 and 0.600.\n",
    "4. Two results pass the adjusted 5% rule; four would pass an unadjusted p≤0.05 rule.\n",
    "\n",
    "**Result:** The adjustment reduces the illustrative candidate list from four apparent findings to two.\n",
    "\n",
    "The remaining two are leads for effect-size review and confirmation, not automatically profitable improvements. The calculation assumes that the original tests and the chosen dependence conditions are appropriate.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Each input p-value is valid under its own sampling design and null model.\n",
    "- The declared family includes the relevant comparisons rather than only favourable results.\n",
    "- BH’s independence or suitable positive-dependence conditions are defensible; arbitrary dependence needs another choice.\n",
    "- The procedure and stopping rules are not changed repeatedly in response to the results.\n",
    "\n",
    "**Decision rule to adapt:** Choose familywise control for decisions where any false claim is costly, or a justified FDR procedure for screening; always check practical benefit and validate selected findings.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · Benjamini–Hochberg and Benjamini–Yekutieli false-discovery control](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.false_discovery_control.html)\n"
   ],
   "id": "business-cell-051"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "multiple-testing"
   },
   "execution_count": 26,
   "source": [
    "import numpy as np\n",
    "from scipy.stats import false_discovery_control\n",
    "p_values = np.array([0.001,0.01,0.03,0.04,0.2,0.6])\n",
    "adjusted = false_discovery_control(p_values, method=\"bh\")\n",
    "print(\"Raw p-values:\", p_values.tolist())\n",
    "print(\"BH adjusted p-values:\", np.round(adjusted, 4).tolist())\n",
    "print(\"Reject at 5% FDR:\", (adjusted <= 0.05).tolist())"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Raw p-values: [0.001, 0.01, 0.03, 0.04, 0.2, 0.6]\n",
      "BH adjusted p-values: [0.006, 0.03, 0.06, 0.06, 0.24, 0.6]\n",
      "Reject at 5% FDR: [True, True, False, False, False, False]\n"
     ]
    }
   ],
   "id": "business-cell-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 27. Correlation and association\n",
    "\n",
    "**Business question:** Do two business measurements move together, and what can that pattern legitimately tell us?\n",
    "\n",
    "Correlation summarises association between paired measurements. Pearson’s coefficient measures linear co-movement, while Spearman’s coefficient uses ranks to describe monotonic association. Both can help investigate business relationships, but neither by itself explains causation or proves that changing one variable will change the other.\n",
    "\n",
    "### Formula\n",
    "\n",
    "r = Σ[(x_i−mean_x)(y_i−mean_y)] / √[Σ(x_i−mean_x)² × Σ(y_i−mean_y)²]; Spearman ρ = Pearson correlation of the ranks\n",
    "\n",
    "- **r**: Pearson sample linear correlation.\n",
    "- **ρ**: Spearman sample rank correlation in this module.\n",
    "- **x_i, y_i**: Measurements paired on the same observational unit.\n",
    "- **mean_x, mean_y**: Sample averages used to centre each measurement.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative monthly advertising spend and revenue for a small retailer, both measured in thousands of rand.\n",
    "\n",
    "- Advertising spend: 1, 2, 3, 4, 5, 6.\n",
    "- Revenue: 7, 9, 10, 13, 12, 16.\n",
    "- Six paired months; use these values as an arithmetic illustration, not an adequate marketing study.\n",
    "\n",
    "1. The sample means are 3.5 and approximately 11.1667.\n",
    "2. The centred cross-product sum is 28.5; the centred sums of squares are 17.5 and approximately 50.8333.\n",
    "3. Pearson r = 28.5/√(17.5×50.8333) ≈0.9555.\n",
    "4. Spearman rank correlation is approximately 0.9429; Pearson’s conventional two-sided p-value is about 0.002920.\n",
    "\n",
    "**Result:** The illustrative sample shows a strong positive linear and rank association.\n",
    "\n",
    "Six months of co-movement do not establish an advertising return. Seasonality, store growth, discounts or higher budgets in already busy months could explain the pattern. The coefficient is not a percentage sales increase or an ROI.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Pairs are correctly aligned and measured on appropriate numerical or ordered scales.\n",
    "- Independent pairs are needed for ordinary significance calculations; repeated or time-dependent observations require adjustment.\n",
    "- Pearson’s coefficient is most informative for linear patterns; Spearman’s targets monotonic ordering.\n",
    "- The sample has enough variation and is not dominated by recording errors, selected ranges or one extreme point.\n",
    "\n",
    "**Decision rule to adapt:** Use correlation as a diagnostic and modelling clue. Require a suitable design and an economic mechanism before treating the relationship as an intervention target.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · Pearson correlation and inference](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html)\n"
   ],
   "id": "business-cell-053"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "correlation"
   },
   "execution_count": 27,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "spend = np.array([1,2,3,4,5,6])\n",
    "revenue = np.array([7,9,10,13,12,16])\n",
    "pearson = stats.pearsonr(spend, revenue)\n",
    "spearman = stats.spearmanr(spend, revenue)\n",
    "print(\"Pearson r and p:\", round(pearson.statistic, 4), round(pearson.pvalue, 6))\n",
    "print(\"Spearman rank correlation:\", round(spearman.statistic, 4))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Pearson r and p: 0.9555 0.00292\n",
      "Spearman rank correlation: 0.9429\n"
     ]
    }
   ],
   "id": "business-cell-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 28. Simple linear regression\n",
    "\n",
    "**Business question:** How can one business measurement help estimate another in its original units?\n",
    "\n",
    "Simple linear regression fits a straight-line relationship between one predictor and a numerical outcome. It supplies an interpretable slope and a prediction rule, with assumptions and uncertainty that determine whether the model is useful for planning, diagnosis or an appropriately designed causal study.\n",
    "\n",
    "### Formula\n",
    "\n",
    "predicted y = b_0+b_1x; b_1 = Σ[(x−mean_x)(y−mean_y)]/Σ(x−mean_x)²; b_0 = mean_y−b_1mean_x\n",
    "\n",
    "- **b_0**: Fitted intercept; its practical meaning requires x=0 to be relevant.\n",
    "- **b_1**: Fitted outcome units per predictor unit.\n",
    "- **residual**: Observed outcome minus fitted outcome.\n",
    "- **R²**: 1−residual SS/total centred outcome SS, for an intercept model.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative retail advertising and revenue, measured in thousands of rand.\n",
    "\n",
    "- Spend x: 1, 2, 3, 4, 5, 6.\n",
    "- Revenue y: 7, 9, 10, 13, 12, 16.\n",
    "- Estimate the fitted mean revenue at advertising spend of R4,000.\n",
    "\n",
    "1. The centred cross-product sum is 28.5 and the predictor sum of squares is 17.5.\n",
    "2. Slope b_1 = 28.5/17.5 ≈1.628571; intercept b_0≈5.466667.\n",
    "3. At x=4, fitted revenue is 5.466667+1.628571×4≈11.980952 thousand rand.\n",
    "4. The sample R² is approximately 0.9131; fitted mean revenue is R11,980.95.\n",
    "\n",
    "**Result:** The fitted line is predicted revenue in R1,000 units = 5.4667 + 1.6286×advertising spend in R1,000 units.\n",
    "\n",
    "The slope describes an observed association in six illustrative points. It is not evidence that another R1,000 in advertising causes R1,628.57 more revenue, and revenue is not contribution. Prediction error and future validation must accompany operational use.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- A straight-line mean relationship is an adequate approximation in the range used.\n",
    "- For interpretable observational slopes, omitted influences related to the predictor must be considered; causality requires stronger identification.\n",
    "- Classical standard errors and intervals require appropriate error independence, variance and distribution assumptions.\n",
    "- The predictor is available when making the forecast and future data are sufficiently comparable to the training process.\n",
    "\n",
    "**Decision rule to adapt:** Use the model when it improves relevant held-out prediction error over a credible baseline and its uncertainty is tolerable for the decision. Do not use the slope as a causal ROI without suitable evidence.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy · simple least-squares regression](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html)\n"
   ],
   "id": "business-cell-055"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "linear-regression"
   },
   "execution_count": 28,
   "source": [
    "import numpy as np\n",
    "from scipy import stats\n",
    "spend = np.array([1,2,3,4,5,6])\n",
    "revenue = np.array([7,9,10,13,12,16])\n",
    "model = stats.linregress(spend, revenue)\n",
    "prediction = model.intercept + model.slope*4\n",
    "print(\"Intercept and slope:\", round(model.intercept, 4), round(model.slope, 4))\n",
    "print(\"R-squared:\", round(model.rvalue**2, 4))\n",
    "print(\"Predicted revenue at R4000 advertising (R):\", round(prediction*1000, 2))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Intercept and slope: 5.4667 1.6286\n",
      "R-squared: 0.9131\n",
      "Predicted revenue at R4000 advertising (R): 11980.95\n"
     ]
    }
   ],
   "id": "business-cell-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 29. Multiple linear regression\n",
    "\n",
    "**Business question:** How do several available business factors jointly relate to a numerical outcome?\n",
    "\n",
    "Multiple regression extends a straight-line prediction rule to several predictors. It can account for observable differences in job mix and produce a transparent planning baseline, but adding variables does not automatically remove bias, create causality or improve future prediction.\n",
    "\n",
    "### Formula\n",
    "\n",
    "predicted y = b_0+b_1x_1+…+b_px_p; estimate b by minimising Σ(y_i−predicted y_i)²\n",
    "\n",
    "- **x_j**: An included predictor available at forecast time.\n",
    "- **b_j**: Conditional fitted outcome change per predictor unit.\n",
    "- **p**: Number of predictors; enough information is needed to estimate them reliably.\n",
    "- **MAE**: Mean absolute held-out error, in the outcome’s original units.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Constructed delivery-cost teaching data use parcel count and route kilometres as inputs.\n",
    "\n",
    "- Eight parcel/km pairs: (10,2), (12,3), (14,1), (16,4), (18,2), (20,5), (22,3), (24,6).\n",
    "- Costs are generated as R100 + R2×parcels + R3×km plus small stated errors.\n",
    "- Fit only the first six rows and hold the final two rows aside.\n",
    "\n",
    "1. The fitted training intercept is R100.65.\n",
    "2. The fitted coefficients are approximately R1.8344 per parcel and R3.7062 per kilometre, conditional on the other input.\n",
    "3. For held-out (22,3), prediction =100.65+1.834375×22+3.70625×3≈R152.125.\n",
    "4. The second test prediction is approximately R166.912; mean absolute error over the two held-out rows is R1.394.\n",
    "\n",
    "**Result:** The fitted model gives an easily inspected delivery-cost rule and a small test error on this constructed example.\n",
    "\n",
    "The data were intentionally generated from a near-linear rule. Eight rows and two test cases are not enough to establish real-world accuracy or coefficient stability. The validation structure is the lesson, not a claim that delivery costs are this predictable.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The functional form adequately represents the conditional mean over the intended prediction range.\n",
    "- Included predictors are observed reliably and available before the outcome is known.\n",
    "- For classical inference, residual independence, variance and distribution conditions need appropriate checks or robust adjustments.\n",
    "- For causal interpretation, the design must address confounding and selection; including several columns alone does not do so.\n",
    "\n",
    "**Decision rule to adapt:** Adopt the model only if relevant held-out error, stability and operating constraints are acceptable relative to a simple baseline; interpret coefficients conditionally and within the observed range.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [scikit-learn · ordinary least-squares LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html)\n"
   ],
   "id": "business-cell-057"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "multiple-regression"
   },
   "execution_count": 29,
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_absolute_error\n",
    "x = np.array([[10,2],[12,3],[14,1],[16,4],[18,2],[20,5],[22,3],[24,6]])\n",
    "noise = np.array([1,-1,0,2,-2,1,0,-1])\n",
    "cost = 100 + 2*x[:,0] + 3*x[:,1] + noise\n",
    "model = LinearRegression().fit(x[:6], cost[:6])\n",
    "predictions = model.predict(x[6:])\n",
    "print(\"Intercept (R):\", round(model.intercept_, 4))\n",
    "print(\"Parcel and km coefficients:\", np.round(model.coef_, 4).tolist())\n",
    "print(\"Test predictions (R):\", np.round(predictions, 3).tolist())\n",
    "print(\"Test MAE (R):\", round(mean_absolute_error(cost[6:], predictions), 3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Intercept (R): 100.65\n",
      "Parcel and km coefficients: [1.8344, 3.7062]\n",
      "Test predictions (R): [152.125, 166.912]\n",
      "Test MAE (R): 1.394\n"
     ]
    }
   ],
   "id": "business-cell-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 30. Logistic regression for business probabilities\n",
    "\n",
    "**Business question:** Can available information estimate the probability of a binary outcome such as a late delivery?\n",
    "\n",
    "Logistic regression estimates a probability between zero and one for an event coded 1 versus 0. It is useful for prioritising reviews and planning interventions when the probabilities are validated and calibrated; choosing an action threshold is a separate business decision.\n",
    "\n",
    "### Formula\n",
    "\n",
    "score = b_0+Σb_jx_j; p = 1/[1+exp(−score)]; log[p/(1−p)] = score; conditional odds ratio for x_j = exp(b_j)\n",
    "\n",
    "- **p**: Fitted probability of the outcome coded 1.\n",
    "- **b_0**: Fitted intercept on the log-odds scale.\n",
    "- **b_j**: Coefficient per predictor unit on the log-odds scale.\n",
    "- **x_j**: A predictor available at the time the decision is made.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative historical service orders use planned lead time known at quotation to estimate eventual late-delivery risk.\n",
    "\n",
    "- Planned lead times: 5,10,15,20,25,30,35,40,45,50 days.\n",
    "- Matured late outcomes: 0,0,0,0,1,0,1,1,1,1.\n",
    "- Fit a regularised one-predictor logistic model with C=1.\n",
    "\n",
    "1. The teaching fit has intercept approximately −6.9694 and day coefficient approximately 0.2534.\n",
    "2. For 25 planned days, score is about −0.634 and logistic probability is approximately 0.3467.\n",
    "3. For 40 planned days, score is about 3.165 and probability is approximately 0.9596.\n",
    "4. exp(0.2534)≈1.288 is a conditional odds multiplier per planned day in this fit, not a 28.8-percentage-point risk increase.\n",
    "\n",
    "**Result:** The model illustrates how a linear score becomes a bounded, nonlinear probability.\n",
    "\n",
    "This ten-order training example provides no credible accuracy or calibration estimate. A real review policy needs substantially more representative mature outcomes, held-out evaluation and a defined intervention; changing promised lead time cannot be assumed to cause the fitted risk change.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Outcome labels are consistently defined and sufficiently complete over the same follow-up window.\n",
    "- Predictors are available before the prediction decision and are measured in consistent units.\n",
    "- The log-odds functional form and regularisation are adequate for the task; interactions or nonlinear terms may be needed.\n",
    "- Training and future decision populations are sufficiently comparable, with appropriate handling of dependence and class sampling.\n",
    "\n",
    "**Decision rule to adapt:** Use validated probabilities with a separately costed and capacity-aware action policy. Check whether the intervention improves outcomes rather than assuming that risk prediction itself creates a benefit.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [scikit-learn · LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html)\n"
   ],
   "id": "business-cell-059"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "logistic-regression"
   },
   "execution_count": 30,
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "days = np.array([5,10,15,20,25,30,35,40,45,50]).reshape(-1,1)\n",
    "late = np.array([0,0,0,0,1,0,1,1,1,1])\n",
    "model = LogisticRegression(C=1.0, solver=\"lbfgs\").fit(days, late)\n",
    "probabilities = model.predict_proba([[25],[40]])[:,1]\n",
    "print(\"Intercept and day coefficient:\", round(model.intercept_[0], 4), round(model.coef_[0,0], 4))\n",
    "print(\"Illustrative P(late) at 25 and 40 days:\", np.round(probabilities, 4).tolist())\n",
    "print(\"Training example only; future calibration and validation are still required.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Intercept and day coefficient: -6.9694 0.2534\n",
      "Illustrative P(late) at 25 and 40 days: [0.3467, 0.9596]\n",
      "Training example only; future calibration and validation are still required.\n"
     ]
    }
   ],
   "id": "business-cell-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 31. Classification thresholds, error costs and review capacity\n",
    "\n",
    "**Business question:** Which predicted risks should trigger action when mistakes have different costs?\n",
    "\n",
    "A probability model becomes a business policy only when a threshold or allocation rule turns its scores into actions. Confusion matrices, precision, recall and explicit error costs show the consequences of that policy. A default 0.5 threshold is rarely an economic law.\n",
    "\n",
    "### Formula\n",
    "\n",
    "precision = TP/(TP+FP); recall = TP/(TP+FN); illustrative error cost = C_FP×FP + C_FN×FN\n",
    "\n",
    "- **TP, FP**: Correctly flagged positives and incorrectly flagged negatives.\n",
    "- **FN, TN**: Missed positives and correctly unflagged negatives.\n",
    "- **C_FP**: Cost assigned to an unnecessary flag in the stated model.\n",
    "- **C_FN**: Cost assigned to a missed event in the stated model.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative held-out order-inspection data contain four genuine faults among ten orders.\n",
    "\n",
    "- Actual fault labels: 1,0,1,0,0,1,0,0,1,0.\n",
    "- Risk scores: 0.90,0.80,0.70,0.60,0.55,0.45,0.40,0.30,0.20,0.10.\n",
    "- Assume R50 per false positive and R300 per false negative; compare thresholds 0.50 and 0.30.\n",
    "\n",
    "1. At 0.50: TP=2, FP=3, FN=2, TN=3; precision=2/5=0.40 and recall=2/4=0.50.\n",
    "2. The illustrative error cost is 3×R50+2×R300=R750, with five orders flagged.\n",
    "3. At 0.30: TP=3, FP=5, FN=1, TN=1; precision=3/8=0.375 and recall=3/4=0.75.\n",
    "4. The error cost is 5×R50+1×R300=R550, but eight orders now require attention.\n",
    "\n",
    "**Result:** The lower threshold has R200 less error cost among the two tested options on these ten illustrative observations.\n",
    "\n",
    "That option is infeasible if only six reviews can be completed, and this comparison does not establish the globally optimal threshold or future savings. Review effort, correct-case treatment cost and actual intervention benefit are outside the simple error-cost model.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Evaluation outcomes are reliable and sufficiently mature, and the sample represents the intended decision population.\n",
    "- Scores are generated without leakage from labels or later information.\n",
    "- The stated cost model and operational capacity describe the actual decision closely enough to be useful.\n",
    "- Threshold tuning is separated from the final performance assessment.\n",
    "\n",
    "**Decision rule to adapt:** Select an action rule that meets the measured cost, capacity and quality requirements on representative validation data, then confirm it on an untouched or later evaluation sample.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [scikit-learn · classification metrics and model evaluation](https://scikit-learn.org/stable/modules/model_evaluation.html)\n"
   ],
   "id": "business-cell-061"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "classification-decisions"
   },
   "execution_count": 31,
   "source": [
    "import numpy as np\n",
    "from sklearn.metrics import confusion_matrix, precision_score, recall_score\n",
    "actual = np.array([1,0,1,0,0,1,0,0,1,0])\n",
    "probability = np.array([.9,.8,.7,.6,.55,.45,.4,.3,.2,.1])\n",
    "for threshold in [.5,.3]:\n",
    "    predicted = probability >= threshold\n",
    "    tn, fp, fn, tp = confusion_matrix(actual, predicted).ravel()\n",
    "    cost = fp*50 + fn*300\n",
    "    print(\"Threshold:\", threshold, \"TP/FP/FN/TN:\", tp, fp, fn, tn)\n",
    "    print(\"Precision/recall:\", round(precision_score(actual,predicted),3), round(recall_score(actual,predicted),3), \"Cost R:\", cost)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Threshold: 0.5 TP/FP/FN/TN: 2 3 2 3\n",
      "Precision/recall: 0.4 0.5 Cost R: 750\n",
      "Threshold: 0.3 TP/FP/FN/TN: 3 5 1 1\n",
      "Precision/recall: 0.375 0.75 Cost R: 550\n"
     ]
    }
   ],
   "id": "business-cell-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 32. Customer segmentation with clustering\n",
    "\n",
    "**Business question:** Are there useful groups of customers or jobs with similar observed behaviour?\n",
    "\n",
    "Clustering groups observations according to similarities in chosen features, without known outcome labels. It can organise exploratory customer or operational analysis, but the resulting groups are a modelling choice to validate, not proof that the business has discovered fixed natural customer types.\n",
    "\n",
    "### Formula\n",
    "\n",
    "K-means minimises Σ_k Σ_(i in cluster k) ||z_i−centre_k||², where z_i contains the chosen scaled features\n",
    "\n",
    "- **k**: A cluster label; the number of clusters is chosen by the analyst.\n",
    "- **z_i**: Feature vector for observation i after the stated preprocessing.\n",
    "- **centre_k**: Mean feature vector of the observations assigned to cluster k.\n",
    "- **silhouette**: A within-versus-between distance summary; higher values indicate separation under that definition.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Constructed six-customer teaching data use purchases during a fixed period and total spend in that same period.\n",
    "\n",
    "- Customer pairs (purchases, rand spend): (1,100), (2,120), (2,80), (8,900), (9,1000), (10,1100).\n",
    "- Standardise both columns using their observed means and scales.\n",
    "- Fit K-means with two clusters, random_state=42 and n_init=10.\n",
    "\n",
    "1. Standardisation makes purchase-count and spend variation comparable for the distance calculation.\n",
    "2. The fitted groups each contain three customers.\n",
    "3. Back-transformed centres are approximately (1.67 purchases, R100) and (9 purchases, R1,000).\n",
    "4. The silhouette score on this constructed sample is approximately 0.8788.\n",
    "\n",
    "**Result:** The method separates low-activity and high-activity examples under the specified feature scaling.\n",
    "\n",
    "The strong separation was deliberately built into the tiny teaching dataset. It is not evidence that two segments are optimal in a real customer base or that a new loyalty offer would improve retention.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The selected features and distance definition describe similarity relevant to the intended business action.\n",
    "- The dataset covers the customer or job population adequately and is not mainly a sample-selection artefact.\n",
    "- K-means’ compact, roughly spherical grouping preference is a useful approximation for the feature space.\n",
    "- Scaling, transformations and future assignment rules are consistently applied.\n",
    "\n",
    "**Decision rule to adapt:** Use a segmentation when it is interpretable, stable enough for its purpose and linked to an action that performs better in a measured pilot than the existing approach.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [scikit-learn · clustering and K-means](https://scikit-learn.org/stable/modules/clustering.html#k-means)\n"
   ],
   "id": "business-cell-063"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "segmentation-clustering"
   },
   "execution_count": 32,
   "source": [
    "import numpy as np\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.metrics import silhouette_score\n",
    "customers = np.array([[1,100],[2,120],[2,80],[8,900],[9,1000],[10,1100]])\n",
    "scaler = StandardScaler()\n",
    "scaled = scaler.fit_transform(customers)\n",
    "model = KMeans(n_clusters=2, random_state=42, n_init=10).fit(scaled)\n",
    "centres = scaler.inverse_transform(model.cluster_centers_)\n",
    "print(\"Cluster sizes:\", np.bincount(model.labels_).tolist())\n",
    "print(\"Centres: purchases, rand spend:\", np.round(centres,2).tolist())\n",
    "print(\"Silhouette:\", round(silhouette_score(scaled,model.labels_),4))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Cluster sizes: [3, 3]\n",
      "Centres: purchases, rand spend: [[1.67, 100.0], [9.0, 1000.0]]\n",
      "Silhouette: 0.8788\n"
     ]
    }
   ],
   "id": "business-cell-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 33. Principal component analysis\n",
    "\n",
    "**Business question:** Can many correlated measurements be summarised without carrying every variable separately?\n",
    "\n",
    "Principal component analysis transforms correlated numerical features into orthogonal components ordered by explained variance. It can simplify exploratory analysis and some predictive pipelines, but the direction with most variation is not automatically the direction with most business importance.\n",
    "\n",
    "### Formula\n",
    "\n",
    "scores Z = X_standardised W; explained-variance ratio_j = λ_j/Σλ; retained share = sum of selected ratios\n",
    "\n",
    "- **X_standardised**: The chosen centred and scaled feature matrix.\n",
    "- **W**: Matrix whose columns are component directions or loadings.\n",
    "- **λ_j**: Variance associated with principal component j.\n",
    "- **Z**: Scores of observations on the retained component axes.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Constructed daily sales counts for three product indicators demonstrate redundancy.\n",
    "\n",
    "- Rows: (10,20,5), (12,24,4), (14,28,6), (16,32,5), (18,36,7), (20,40,6).\n",
    "- The second indicator is exactly twice the first in the teaching data.\n",
    "- Standardise all three features and fit two principal components.\n",
    "\n",
    "1. The first component has an explained-variance ratio of approximately 0.8540.\n",
    "2. The second explains approximately 0.1460; the remaining component has effectively zero variance.\n",
    "3. Together, two components retain essentially all variation in this particular three-column sample.\n",
    "4. One valid first-component loading vector is approximately (0.6064, 0.6064, 0.5144); its simultaneous sign reversal is equivalent.\n",
    "\n",
    "**Result:** The arithmetic exposes the exact redundancy deliberately placed in the first two indicators.\n",
    "\n",
    "Retaining 100% here does not imply that two components will always retain all future business information. The six-row sample is illustrative, and variance retained is not a prediction accuracy or an economic benefit.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Numerical features and the chosen linear combinations are meaningful for the intended task.\n",
    "- The sample represents the variation the analysis is meant to summarise.\n",
    "- The selected scaling and variance-based compression criterion are appropriate business choices.\n",
    "- For prediction, all learned preprocessing is restricted to training data to avoid leakage.\n",
    "\n",
    "**Decision rule to adapt:** Retain only a dimensionality and preprocessing choice that serves the stated business task; judge success with downstream usefulness and validation, not an arbitrary variance threshold alone.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [scikit-learn · PCA and matrix decomposition](https://scikit-learn.org/stable/modules/decomposition.html#pca)\n"
   ],
   "id": "business-cell-065"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "principal-components"
   },
   "execution_count": 33,
   "source": [
    "import numpy as np\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.decomposition import PCA\n",
    "sales = np.array([[10,20,5],[12,24,4],[14,28,6],[16,32,5],[18,36,7],[20,40,6]])\n",
    "scaled = StandardScaler().fit_transform(sales)\n",
    "model = PCA(n_components=2).fit(scaled)\n",
    "print(\"Explained-variance ratios:\", np.round(model.explained_variance_ratio_,4).tolist())\n",
    "print(\"Cumulative retained variance:\", round(model.explained_variance_ratio_.sum(),4))\n",
    "print(\"First component weights:\", np.round(model.components_[0],4).tolist())"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Explained-variance ratios: [0.854, 0.146]\n",
      "Cumulative retained variance: 1.0\n",
      "First component weights: [0.6064, 0.6064, 0.5144]\n"
     ]
    }
   ],
   "id": "business-cell-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 34. Moving averages and simple exponential smoothing\n",
    "\n",
    "**Business question:** What transparent short-term forecast can be built from recent demand?\n",
    "\n",
    "A trailing moving average gives recent periods equal weight, while simple exponential smoothing gives progressively less weight to older observations. Both are useful baseline forecasting methods for a changing local level, provided their limitations with trend, seasonality and disruptions are understood.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Moving-average forecast = (y_t+…+y_(t−k+1))/k; level_t = αy_t+(1−α)level_(t−1); SES forecast_(t+h) = level_t\n",
    "\n",
    "- **k**: Number of past observations in the trailing window.\n",
    "- **α**: Smoothing weight between zero and one.\n",
    "- **y_t**: Latest actual observation known at the forecast origin.\n",
    "- **level_t**: Updated estimate of the current level.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative weekly demand for a regularly stocked consumable, with six complete observations.\n",
    "\n",
    "- Demand: 100,110,105,120,115,130 units.\n",
    "- Moving-average window: three weeks.\n",
    "- SES alpha=0.3; initialise the level to the first observation, 100.\n",
    "\n",
    "1. The naïve forecast for the next week is the last observed demand, 130.\n",
    "2. The three-week moving-average forecast is (120+115+130)/3≈121.667.\n",
    "3. SES successive levels after the first are 103, 103.6, 108.52, 110.464 and 116.3248.\n",
    "4. The final SES next-period forecast is approximately 116.325 units.\n",
    "\n",
    "**Result:** The three simple methods disagree because they balance current change and noise differently.\n",
    "\n",
    "There is no later observation here, so no method has demonstrated greater accuracy. The rising example also illustrates lag: a smooth estimate can understate continuing growth, while reacting to a temporary peak can overstate future demand.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Measurements are comparable, correctly ordered and regularly spaced for the chosen update rule.\n",
    "- Historical demand is informative about the local level during the intended forecast period.\n",
    "- Unmodelled trend, seasonality or known interventions are not being mistaken for random noise.\n",
    "- Training and tuning use earlier observations only; future outcomes are reserved for evaluation.\n",
    "\n",
    "**Decision rule to adapt:** Keep the simplest method that delivers acceptable rolling-origin error and bias for the planning horizon; add trend or seasonality when the evidence and operating context require them.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [Hyndman and Athanasopoulos · exponential smoothing](https://otexts.com/fpp3/exponential-smoothing.html)\n"
   ],
   "id": "business-cell-067"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "moving-average-smoothing"
   },
   "execution_count": 34,
   "source": [
    "import numpy as np\n",
    "sales = np.array([100,110,105,120,115,130])\n",
    "alpha = 0.3\n",
    "level = float(sales[0])\n",
    "for value in sales[1:]:\n",
    "    level = alpha*value + (1-alpha)*level\n",
    "print(\"Naive next-period forecast:\", sales[-1])\n",
    "print(\"Three-period moving average:\", round(sales[-3:].mean(),3))\n",
    "print(\"Simple exponential smoothing:\", round(level,3))\n",
    "print(\"These forecasts must be compared on later observations.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Naive next-period forecast: 130\n",
      "Three-period moving average: 121.667\n",
      "Simple exponential smoothing: 116.325\n",
      "These forecasts must be compared on later observations.\n"
     ]
    }
   ],
   "id": "business-cell-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 35. Seasonality and fitted seasonal forecasting\n",
    "\n",
    "**Business question:** How should recurring calendar patterns influence purchasing, staffing and capacity?\n",
    "\n",
    "Seasonal forecasting uses patterns that recur over a known cycle, such as weekdays, quarters or months. A seasonal-naïve baseline repeats the corresponding past season; a fitted model can add trend or other known drivers when sufficient history and validation justify the extra structure.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Seasonal-naïve forecast_(T+h) = y_(T+h−m), for 1≤h≤m; seasonal regression: log(y_t) = b_0+b_1t+γ_2Q2_t+γ_3Q3_t+γ_4Q4_t+error_t\n",
    "\n",
    "- **m**: Season length, four periods for quarterly data.\n",
    "- **T**: Last observation available at the forecast origin.\n",
    "- **Q2_t, Q3_t, Q4_t**: Quarter indicators; quarter one is represented by the intercept.\n",
    "- **b_1**: Time trend on the logarithmic scale.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Constructed quarterly demand deliberately combines a repeated seasonal profile with 10% annual growth.\n",
    "\n",
    "- Year one: 100,120,90,150 units.\n",
    "- Year two: 110,132,99,165 units.\n",
    "- Year three, reserved initially as a holdout: 121,145.2,108.9,181.5 units.\n",
    "\n",
    "1. Fit the log-linear seasonal regression only to the first eight observations.\n",
    "2. A seasonal-naïve holdout forecast repeats year two; its four-quarter MAE is 12.65 units.\n",
    "3. The fitted regression captures the constructed growth and quarter pattern, producing an approximately zero holdout MAE.\n",
    "4. After evaluating, refit the same specification to all twelve observations: next four point forecasts are 133.10,159.72,119.79 and 199.65 units.\n",
    "\n",
    "**Result:** The example distinguishes a baseline that repeats a season from a fitted model that also represents growth.\n",
    "\n",
    "A perfect result occurs because the data were designed from that structure. It is not evidence that the model will forecast real business demand perfectly. Three years of toy data cannot quantify the uncertainty from weather, promotions, disruptions or changing customer demand.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Calendar periods and outcomes are consistently recorded, with missing periods distinguished from zero demand.\n",
    "- The observed seasonal pattern and trend are informative about the intended future period.\n",
    "- Future predictors such as quarter indicators are known at prediction time; unknown drivers require scenarios.\n",
    "- The logarithmic example requires strictly positive demand and a suitable interpretation of back-transformed forecasts.\n",
    "\n",
    "**Decision rule to adapt:** Prefer a fitted seasonal method only when it improves a relevant chronological baseline and its uncertainty, maintenance effort and operating assumptions are acceptable for the decision.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [Hyndman and Athanasopoulos · time-series regression and seasonal predictors](https://otexts.com/fpp3/regression.html)\n",
    "- [Hyndman and Athanasopoulos · methods with seasonality](https://otexts.com/fpp3/exponential-smoothing.html)\n"
   ],
   "id": "business-cell-069"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "seasonal-forecasting"
   },
   "execution_count": 35,
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "sales = np.array([100,120,90,150,110,132,99,165,121,145.2,108.9,181.5])\n",
    "time = np.arange(len(sales))\n",
    "quarter = time % 4\n",
    "features = np.column_stack([time, quarter==1, quarter==2, quarter==3])\n",
    "model = LinearRegression().fit(features[:8], np.log(sales[:8]))\n",
    "seasonal_naive = sales[4:8]\n",
    "fitted_forecast = np.exp(model.predict(features[8:]))\n",
    "print(\"Seasonal-naive holdout MAE:\", round(np.abs(sales[8:]-seasonal_naive).mean(),3))\n",
    "print(\"Seasonal-regression holdout MAE:\", round(np.abs(sales[8:]-fitted_forecast).mean(),3))\n",
    "final_model = LinearRegression().fit(features, np.log(sales))\n",
    "future_time = np.arange(12,16)\n",
    "future_quarter = future_time % 4\n",
    "future = np.column_stack([future_time, future_quarter==1, future_quarter==2, future_quarter==3])\n",
    "print(\"Next four forecasts:\", np.round(np.exp(final_model.predict(future)),2).tolist())\n",
    "print(\"Constructed example; a perfect holdout result is not a real-world accuracy claim.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Seasonal-naive holdout MAE: 12.65\n",
      "Seasonal-regression holdout MAE: 0.0\n",
      "Next four forecasts: [133.1, 159.72, 119.79, 199.65]\n",
      "Constructed example; a perfect holdout result is not a real-world accuracy claim.\n"
     ]
    }
   ],
   "id": "business-cell-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 36. Forecast validation, backtesting and error metrics\n",
    "\n",
    "**Business question:** Does a forecasting method actually improve the decisions made from future demand estimates?\n",
    "\n",
    "Forecast validation recreates historical prediction decisions using only the information that would have been available at the time. Rolling-origin evaluation, simple baselines and decision-relevant error measures provide a stronger basis for choosing a method than how neatly it fits its training data.\n",
    "\n",
    "### Formula\n",
    "\n",
    "error_t = actual_t−forecast_t; MAE = mean(|error|); RMSE = √mean(error²); MASE = MAE / mean_training(|y_t−y_(t−m)|)\n",
    "\n",
    "- **m**: Seasonal lag for the scaling benchmark; m=1 for the nonseasonal example.\n",
    "- **forecast origin**: Date through which information is available for one prediction.\n",
    "- **horizon**: How far ahead the prediction is made.\n",
    "- **training scale**: Naïve absolute-error average estimated without future observations.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative twelve-period demand series compares a one-step naïve rule with a trailing three-period average.\n",
    "\n",
    "- Demand: 100,105,110,108,115,120,118,125,130,128,135,140.\n",
    "- Begin evaluation after six training observations; forecast one period ahead at each of six subsequent origins.\n",
    "- Keep the MASE scaling denominator fixed from the initial six observations.\n",
    "\n",
    "1. The training naïve absolute changes are 5,5,2,7,5; their mean is 4.8.\n",
    "2. At each evaluation step, use only the latest available history: last actual for naïve, last three actuals for moving average.\n",
    "3. Naïve MAE≈4.667, RMSE≈5.099 and MASE≈0.972.\n",
    "4. Moving-average MAE≈6.667, RMSE≈7.029 and MASE≈1.389.\n",
    "\n",
    "**Result:** The naïve rule performs better than the three-period moving average on this small constructed holdout sequence.\n",
    "\n",
    "The example shows why a smoother line need not be a better forecast. Six errors are not enough to establish a lasting advantage; compare more origins, appropriate seasonal periods and the actual decision horizon.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Historical records reproduce what was genuinely known at each forecast origin.\n",
    "- Evaluation periods and horizons represent the intended future operating decisions sufficiently well.\n",
    "- Every candidate uses equivalent information, outcomes and scoring rules.\n",
    "- The scaling benchmark is nonzero and appropriately chosen; dependent errors and structural changes are acknowledged.\n",
    "\n",
    "**Decision rule to adapt:** Choose the simplest maintainable method that performs acceptably on representative chronological evaluation at the required horizon and under the relevant cost and service constraints.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [Hyndman and Athanasopoulos · forecasting workflows, baselines and accuracy](https://otexts.com/fpp3/toolbox.html)\n"
   ],
   "id": "business-cell-071"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "forecast-validation"
   },
   "execution_count": 36,
   "source": [
    "import numpy as np\n",
    "sales = np.array([100,105,110,108,115,120,118,125,130,128,135,140])\n",
    "actual, naive, moving = [], [], []\n",
    "for t in range(6,len(sales)):\n",
    "    actual.append(sales[t])\n",
    "    naive.append(sales[t-1])\n",
    "    moving.append(sales[t-3:t].mean())\n",
    "actual = np.array(actual)\n",
    "scale = np.abs(np.diff(sales[:6])).mean()\n",
    "for name, forecast in [(\"Naive\",naive),(\"Moving average\",moving)]:\n",
    "    error = actual-np.array(forecast)\n",
    "    mae = np.abs(error).mean()\n",
    "    rmse = np.sqrt((error**2).mean())\n",
    "    print(name, \"MAE/RMSE/MASE:\", round(mae,3), round(rmse,3), round(mae/scale,3))\n",
    "print(\"Initial training-only scale:\", round(scale,3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Naive MAE/RMSE/MASE: 4.667 5.099 0.972\n",
      "Moving average MAE/RMSE/MASE: 6.667 7.029 1.389\n",
      "Initial training-only scale: 4.8\n"
     ]
    }
   ],
   "id": "business-cell-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 37. Individuals and moving-range control charts\n",
    "\n",
    "**Business question:** Has a process changed beyond its usual short-term variation?\n",
    "\n",
    "An I–MR chart monitors time-ordered continuous measurements collected one at a time. It separates investigation of unusual behaviour from routine adjustment of a stable process, which helps managers avoid both missed shifts and unnecessary tampering.\n",
    "\n",
    "### Formula\n",
    "\n",
    "MR_i = |x_i − x_(i−1)|; sigma_hat = mean(MR)/1.128; I limits = mean(x) ± 3 sigma_hat; MR UCL = 3.267 mean(MR), LCL = 0.\n",
    "\n",
    "- **x_i**: The i-th time-ordered reading in the selected operating condition.\n",
    "- **MR_i**: Absolute change from the previous reading.\n",
    "- **sigma_hat**: An estimate of short-term process standard deviation, not a specification tolerance.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative bottling line: twenty baseline fills are used to demonstrate a fixed-limit monitor.\n",
    "\n",
    "- Fills in ml: 500, 501, 499, 500, 502, 501, 500, 499, 501, 500, 500, 501, 499, 500, 501, 502, 500, 499, 500, 501.\n",
    "- New fill: 505 ml.\n",
    "\n",
    "1. The twenty-reading mean is 500.300 ml.\n",
    "2. The nineteen absolute successive differences average 1.210526 ml.\n",
    "3. Estimated sigma = 1.210526 / 1.128 = 1.073162 ml.\n",
    "4. I limits = 500.300 ± 3 × 1.073162 = 497.080515 to 503.519485 ml.\n",
    "5. The MR upper limit is 3.267 × 1.210526 = 3.954789 ml. The new 505 ml fill exceeds the I upper limit.\n",
    "\n",
    "**Result:** A 505 ml reading generates an individuals-chart investigation signal against this baseline.\n",
    "\n",
    "Check the event log, gauge and operating conditions. Do not automatically discard the bottle or alter the filler: acceptance still depends on separate product specifications.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Readings represent a sufficiently consistent operating condition and reliable measurement system.\n",
    "- Successive observations are approximately independent; strong serial correlation changes the signal behaviour.\n",
    "- Normal-based three-sigma limits are reasonable for the measured distribution.\n",
    "- The sampling frequency can detect changes relevant to delivery or quality before damage accumulates.\n",
    "\n",
    "**Decision rule to adapt:** Investigate a predefined chart signal, verify its cause and assess product risk separately; accept a revised baseline only after a justified change is stable.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Individuals Control Charts](https://www.itl.nist.gov/div898/handbook/pmc/section3/pmc322.htm)\n"
   ],
   "id": "business-cell-073"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "control-charts-imr"
   },
   "execution_count": 37,
   "source": [
    "import numpy as np\n",
    "x = np.array([500,501,499,500,502,501,500,499,501,500,500,501,499,500,501,502,500,499,500,501])\n",
    "mean_fill = x.mean()\n",
    "mean_range = np.abs(np.diff(x)).mean()\n",
    "sigma = mean_range / 1.128\n",
    "lower = mean_fill - 3 * sigma\n",
    "upper = mean_fill + 3 * sigma\n",
    "print(\"Baseline mean:\", round(mean_fill, 3), \"ml\")\n",
    "print(\"I limits:\", round(lower, 3), round(upper, 3), \"ml\")\n",
    "print(\"MR upper limit:\", round(3.267 * mean_range, 3), \"ml\")\n",
    "print(\"New reading signals:\", 505 < lower or 505 > upper)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Baseline mean: 500.3 ml\n",
      "I limits: 497.081 503.519 ml\n",
      "MR upper limit: 3.955 ml\n",
      "New reading signals: True\n"
     ]
    }
   ],
   "id": "business-cell-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 38. Attribute control charts: p, np, c and u\n",
    "\n",
    "**Business question:** Is the rate of failures or defects changing after allowing for inspection volume?\n",
    "\n",
    "Attribute charts monitor counts classified as pass/fail or counts of defects. Choosing the correct denominator prevents a busy week from appearing worse merely because more work was inspected.\n",
    "\n",
    "### Formula\n",
    "\n",
    "p_bar = sum(failed_i)/sum(n_i); p limits_i = p_bar ± 3 sqrt[p_bar(1−p_bar)/n_i], clipped to [0,1]. u_bar = sum(defects_i)/sum(exposure_i); u limits_i = u_bar ± 3 sqrt(u_bar/exposure_i), with lower limit at least 0.\n",
    "\n",
    "- **n_i**: Number of inspected units in sample i.\n",
    "- **failed_i**: Number of units failing the defined acceptance rule, counted once each.\n",
    "- **exposure_i**: Comparable defect opportunity, such as units, square metres or inspection hours.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative dispatch department: baseline samples have different numbers of inspected orders.\n",
    "\n",
    "- Baseline failed orders: 4, 6, 5, 3, 7.\n",
    "- Baseline inspected orders: 100, 150, 120, 80, 150.\n",
    "- New sample: 20 failed orders among 200 inspected.\n",
    "\n",
    "1. Pool the baseline: 25 failed / 600 inspected = 0.0416667, or 4.16667%.\n",
    "2. For n = 200, standard error = sqrt(0.0416667 × 0.9583333 / 200) = 0.01412985.\n",
    "3. Upper p limit = 0.0416667 + 3 × 0.01412985 = 0.0840562, or 8.40562%.\n",
    "4. The calculated lower limit is negative, so display 0.\n",
    "5. The new failed fraction is 20 / 200 = 10%, above the upper limit.\n",
    "\n",
    "**Result:** The sample signals an unusual failed-order fraction against the illustrative baseline.\n",
    "\n",
    "Investigate why this sample differs, including inspection changes and clustered order types. A higher count alone would not establish deterioration without its denominator.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Units or defect opportunities are approximately independent within the chosen model.\n",
    "- The baseline probability or defect rate is reasonably stable under the defined operating condition.\n",
    "- Inspection sensitivity, classification rules and exposure definitions remain consistent.\n",
    "- A normal approximation is suitable for the displayed limits; sparse counts receive appropriate special treatment.\n",
    "\n",
    "**Decision rule to adapt:** Investigate a sample-specific signal after checking the denominator and inspection process; assess whether the proposed change reduces the relevant error rate without weakening inspection.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Proportions Control Charts](https://www.itl.nist.gov/div898/handbook/pmc/section3/pmc332.htm)\n",
    "- [NIST: U Control Chart](https://www.itl.nist.gov/div898/software/dataplot/refman1/ch2/ucontrol.pdf)\n"
   ],
   "id": "business-cell-075"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "attribute-control-charts"
   },
   "execution_count": 38,
   "source": [
    "import numpy as np\n",
    "failed = np.array([4,6,5,3,7])\n",
    "inspected = np.array([100,150,120,80,150])\n",
    "p = failed.sum() / inspected.sum()\n",
    "new_n = 200\n",
    "lower = max(0, p - 3 * np.sqrt(p * (1-p) / new_n))\n",
    "upper = min(1, p + 3 * np.sqrt(p * (1-p) / new_n))\n",
    "new_rate = 20 / new_n\n",
    "print(\"Baseline failure %:\", round(100*p, 3))\n",
    "print(\"New-sample limits %:\", round(100*lower, 3), round(100*upper, 3))\n",
    "print(\"New failure %:\", round(100*new_rate, 3))\n",
    "print(\"Investigation signal:\", new_rate < lower or new_rate > upper)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Baseline failure %: 4.167\n",
      "New-sample limits %: 0 8.406\n",
      "New failure %: 10.0\n",
      "Investigation signal: True\n"
     ]
    }
   ],
   "id": "business-cell-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 39. Process capability: Cp, Cpk and expected rejects\n",
    "\n",
    "**Business question:** Can a stable process consistently meet the product specification?\n",
    "\n",
    "Capability analysis compares process variation with externally defined acceptance limits. It helps separate a process that is too variable from one that is poorly centred, and connects those differences to a modelled rejection rate.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Cp = (USL−LSL)/(6 sigma); Cpk = min[(USL−mu)/(3 sigma), (mu−LSL)/(3 sigma)]; reject probability = Phi((LSL−mu)/sigma) + 1−Phi((USL−mu)/sigma).\n",
    "\n",
    "- **LSL, USL**: Externally set lower and upper acceptance limits.\n",
    "- **mu, sigma**: Stable process mean and appropriate within-process standard deviation.\n",
    "- **Phi**: Standard normal cumulative distribution function; its applicability must be checked.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative bottling line: assume a stable normal fill process has a verified mean and within-process standard deviation.\n",
    "\n",
    "- Mean 502 ml; standard deviation 4 ml.\n",
    "- Acceptable range 490 to 510 ml; 10,000 bottles per day.\n",
    "- Assumed handling loss per rejected bottle: R3.\n",
    "\n",
    "1. Cp = (510−490)/(6 × 4) = 0.833333.\n",
    "2. Cpk = min[(510−502)/12, (502−490)/12] = min(0.666667,1) = 0.666667.\n",
    "3. Lower-tail z = (490−502)/4 = −3; upper-tail z = (510−502)/4 = 2.\n",
    "4. Normal rejection probability = 0.001349898 + 0.022750132 = 0.024100030.\n",
    "5. Expected daily rejects = 10,000 × 0.024100030 = 241.0003; modelled reject cost = R723.0009.\n",
    "\n",
    "**Result:** The model predicts about 241 rejects per day, with poorer protection at the upper specification.\n",
    "\n",
    "Centring can address the asymmetry, but the low Cp also indicates substantial spread relative to the tolerance. The predicted count is not an observed production result.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The process is stable over the period to which the capability statement applies.\n",
    "- The measurement system is sufficiently reliable relative to the tolerance.\n",
    "- The normal model is suitable for translating capability into the displayed tail probabilities.\n",
    "- The selected sigma definition and subgrouping method match the interpretation of Cp/Cpk.\n",
    "\n",
    "**Decision rule to adapt:** Compare capability with the applicable requirement and uncertainty, then verify any proposed improvement on fresh stable data and its actual accepted-output cost.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: What is Process Capability?](https://www.itl.nist.gov/div898/handbook/pmc/section1/pmc16.htm)\n"
   ],
   "id": "business-cell-077"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "process-capability"
   },
   "execution_count": 39,
   "source": [
    "from scipy.stats import norm\n",
    "mean, sigma = 502, 4\n",
    "lower, upper = 490, 510\n",
    "cp = (upper-lower) / (6*sigma)\n",
    "cpk = min((upper-mean)/(3*sigma), (mean-lower)/(3*sigma))\n",
    "reject_rate = norm.cdf((lower-mean)/sigma) + norm.sf((upper-mean)/sigma)\n",
    "print(\"Cp:\", round(cp, 3), \"Cpk:\", round(cpk, 3))\n",
    "print(\"Expected reject %:\", round(100*reject_rate, 4))\n",
    "print(\"Expected rejects per day:\", round(10000*reject_rate, 2))\n",
    "print(\"Modelled daily reject cost: R\", round(10000*reject_rate*3, 2))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Cp: 0.833 Cpk: 0.667\n",
      "Expected reject %: 2.41\n",
      "Expected rejects per day: 241.0\n",
      "Modelled daily reject cost: R 723.0\n"
     ]
    }
   ],
   "id": "business-cell-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 40. Measurement systems and crossed Gage R&R\n",
    "\n",
    "**Business question:** Are changes in the measurements coming from the product or the measurement system?\n",
    "\n",
    "A measurement study separates repeatability from operator-related reproducibility and part variation. It helps a business decide whether a reported process difference is measurable before investing in production changes or rejecting acceptable work.\n",
    "\n",
    "### Formula\n",
    "\n",
    "var_repeat = MS_E; var_interaction = max[(MS_PO−MS_E)/r,0]; var_operator = max[(MS_O−MS_PO)/(p r),0]; var_part = max[(MS_P−MS_PO)/(o r),0]; sigma_GRR = sqrt(var_repeat+var_interaction+var_operator).\n",
    "\n",
    "- **p, o, r**: Numbers of parts, operators and repeated readings per part–operator cell.\n",
    "- **MS_E, MS_PO, MS_O, MS_P**: Residual, interaction, operator and part ANOVA mean squares.\n",
    "- **Percent study variation**: 100 × sigma_GRR / sqrt(var_part+sigma_GRR²); not the variance percentage.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative dimensional gauge: five parts, two operators and three repeated measurements form a deliberately small balanced demonstration.\n",
    "\n",
    "- Part values: 9.7, 9.9, 10.1, 10.3 and 10.5 mm.\n",
    "- Operator offsets: −0.02 and +0.02 mm. Each cell has repeat offsets −0.01, 0 and +0.01 mm.\n",
    "- Tolerance width for the separate tolerance comparison: 2 mm.\n",
    "\n",
    "1. Residual mean square is 0.0001 mm²; the constructed interaction mean square is essentially zero.\n",
    "2. Operator variance component is 0.0008 mm²; part variance is 0.1000 mm². Negative interaction estimate is truncated to zero.\n",
    "3. Combined measurement variance = 0.0001 + 0.0008 + 0 = 0.0009 mm²; sigma_GRR = 0.0300 mm.\n",
    "4. Total study sigma = sqrt(0.1000 + 0.0009) = 0.3176476 mm.\n",
    "5. Percent study variation = 100 × 0.03 / 0.3176476 = 9.4444%; tolerance ratio = 100 × 6 × 0.03 / 2 = 9.0%.\n",
    "\n",
    "**Result:** The constructed example separates a 0.03 mm measurement standard deviation from much larger selected-part variation.\n",
    "\n",
    "The percentages describe this design and selected range. They do not establish absence of bias or justify a universal pass/fail threshold.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The example uses a balanced crossed random-effects design with repeat measurements in every cell.\n",
    "- Selected parts and operators represent the intended operating population sufficiently for the proposed interpretation.\n",
    "- Measurement errors are approximately independent with a common within-cell variance.\n",
    "- Parts remain stable during repeated measurement; repeat readings are not changed by destructive testing.\n",
    "\n",
    "**Decision rule to adapt:** Judge suitability against the actual decision, tolerance, uncertainty and misclassification consequences; do not approve a gauge solely from one percentage in a small demonstration.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Gauge R&R studies](https://www.itl.nist.gov/div898/handbook/mpc/section4/mpc4.htm)\n"
   ],
   "id": "business-cell-079"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "measurement-system-analysis"
   },
   "execution_count": 40,
   "source": [
    "import numpy as np\n",
    "parts = np.array([9.7,9.9,10.1,10.3,10.5])\n",
    "operators = np.array([-0.02,0.02])\n",
    "repeats = np.array([-0.01,0,0.01])\n",
    "y = parts[:,None,None] + operators[None,:,None] + repeats[None,None,:]\n",
    "p,o,r = y.shape\n",
    "grand = y.mean()\n",
    "part_means = y.mean(axis=(1,2))\n",
    "operator_means = y.mean(axis=(0,2))\n",
    "cell_means = y.mean(axis=2)\n",
    "ms_e = ((y-cell_means[:,:,None])**2).sum() / (p*o*(r-1))\n",
    "ms_p = o*r*((part_means-grand)**2).sum() / (p-1)\n",
    "ms_o = p*r*((operator_means-grand)**2).sum() / (o-1)\n",
    "interaction = cell_means-part_means[:,None]-operator_means[None,:]+grand\n",
    "ms_po = r*(interaction**2).sum() / ((p-1)*(o-1))\n",
    "var_po = max(0,(ms_po-ms_e)/r)\n",
    "var_o = max(0,(ms_o-ms_po)/(p*r))\n",
    "var_p = max(0,(ms_p-ms_po)/(o*r))\n",
    "sigma_grr = np.sqrt(ms_e+var_po+var_o)\n",
    "print(\"Measurement sigma:\",round(sigma_grr,4),\"mm\")\n",
    "print(\"Part variance:\",round(var_p,4),\"mm squared\")\n",
    "print(\"Study variation %:\",round(100*sigma_grr/np.sqrt(var_p+sigma_grr**2),3))\n",
    "print(\"Tolerance ratio %:\",round(100*6*sigma_grr/2,3))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Measurement sigma: 0.03 mm\n",
      "Part variance: 0.1 mm squared\n",
      "Study variation %: 9.444\n",
      "Tolerance ratio %: 9.0\n"
     ]
    }
   ],
   "id": "business-cell-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 41. Reliability and survival with censored observations\n",
    "\n",
    "**Business question:** What proportion of assets or customers remains failure-free after a specified time?\n",
    "\n",
    "Survival analysis models time until an event while retaining partial information from units whose event has not yet occurred. It helps estimate reliability, warranty exposure or customer persistence without treating incomplete follow-up as either a failure or permanent success.\n",
    "\n",
    "### Formula\n",
    "\n",
    "S_hat(t) = product over event times t_j ≤ t of (1−d_j/n_j); F_hat(t) = 1−S_hat(t).\n",
    "\n",
    "- **d_j**: Number of observed events at time t_j.\n",
    "- **n_j**: Number still at risk immediately before that event time, including appropriate tied censored records.\n",
    "- **S_hat(t)**: Estimated probability of remaining event-free beyond time t under the study conditions.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative pump cohort: six pumps have different event or observation-end times in months.\n",
    "\n",
    "- Observed times: 2, 3, 4, 4, 5 and 6 months.\n",
    "- Event indicators: 1, 0, 1, 0, 1, 0, where 0 means right-censored.\n",
    "\n",
    "1. At month 2, one event among six at risk gives S = 5/6 = 0.833333.\n",
    "2. The month-3 censoring removes a pump from later risk sets without lowering survival.\n",
    "3. At month 4, one event among four at risk gives S = (5/6) × (3/4) = 0.625. Remove the tied censored record after evaluating that risk set.\n",
    "4. At month 5, one event among the two remaining at risk gives S = 0.625 × 1/2 = 0.3125.\n",
    "5. The month-6 censoring produces no additional event-time drop.\n",
    "\n",
    "**Result:** The illustrative estimate after the month-5 event is 31.25% event-free survival.\n",
    "\n",
    "Only two pumps were at risk just before month 5, so tail uncertainty is substantial. The final censored pump is not evidence of a month-6 failure.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Censoring is non-informative for event risk, conditional on relevant information used in the analysis.\n",
    "- Units are independent or dependence is addressed in the study design and uncertainty calculation.\n",
    "- Event timing, entry time and event definition are recorded consistently.\n",
    "- The observed cohort and operating environment are relevant to the decision population.\n",
    "\n",
    "**Decision rule to adapt:** Choose a service or warranty action only after examining survival uncertainty, operating comparability and costs; flag tail estimates based on very small risk sets.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Kaplan–Meier approach](https://www.itl.nist.gov/div898/handbook/apr/section2/apr215.htm)\n"
   ],
   "id": "business-cell-081"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "reliability-survival"
   },
   "execution_count": 41,
   "source": [
    "import numpy as np\n",
    "times = np.array([2,3,4,4,5,6])\n",
    "event = np.array([1,0,1,0,1,0])\n",
    "survival = 1.0\n",
    "for time in sorted(set(times[event == 1])):\n",
    "    at_risk = (times >= time).sum()\n",
    "    failures = ((times == time) & (event == 1)).sum()\n",
    "    survival = survival * (1-failures/at_risk)\n",
    "    print(\"Month\",time,\"at risk\",at_risk,\"survival\",round(survival,6))\n",
    "print(\"Estimated event-free % after month 5:\",round(100*survival,2))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Month 2 at risk 6 survival 0.833333\n",
      "Month 4 at risk 4 survival 0.625\n",
      "Month 5 at risk 2 survival 0.3125\n",
      "Estimated event-free % after month 5: 31.25\n"
     ]
    }
   ],
   "id": "business-cell-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 42. Factorial experiments and interaction effects\n",
    "\n",
    "**Business question:** Does a process setting work differently when another setting changes?\n",
    "\n",
    "A factorial experiment deliberately varies several factors together so their separate effects and interactions can be estimated. It helps a business learn whether a combination of settings, rather than one setting alone, changes accepted output or another response.\n",
    "\n",
    "### Formula\n",
    "\n",
    "y = beta0 + betaA A + betaB B + betaAB AB + error, with A,B in {−1,+1}; two-level effect A = 2 betaA, effect B = 2 betaB, interaction effect = 2 betaAB.\n",
    "\n",
    "- **y**: Chosen response, such as accepted parts per run.\n",
    "- **A, B**: Coded low/high settings of the two experimental factors.\n",
    "- **betaAB**: Coefficient describing how the effect of one factor changes with the other.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative manufacturing pilot: two setup factors are tested at low and high levels, with two independent runs per combination.\n",
    "\n",
    "- Cell means: A− B− = 90; A+ B− = 100; A− B+ = 95; A+ B+ = 125 accepted units.\n",
    "- Each cell has responses two units below and above its mean: 88/92, 98/102, 93/97 and 123/127.\n",
    "\n",
    "1. A main effect = (100+125)/2 − (90+95)/2 = 20 units.\n",
    "2. B main effect = (95+125)/2 − (90+100)/2 = 15 units.\n",
    "3. AB interaction effect = (90+125−100−95)/2 = 10 units.\n",
    "4. The effect of A is 100−90 = 10 units at B−, but 125−95 = 30 units at B+.\n",
    "5. The coded regression coefficients are intercept 102.5, A 10, B 7.5 and AB 5.\n",
    "\n",
    "**Result:** The effect of A depends materially on B in this constructed pilot; the highest observed cell mean is A+ B+.\n",
    "\n",
    "Averaging A’s effect into one number hides its 10-versus-30-unit conditional effect. Confirm quality, cost and repeatability before adopting the combination.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Factors can be deliberately assigned and implemented at their specified levels.\n",
    "- Errors are sufficiently independent with suitable variance and distribution for the selected inferential model.\n",
    "- The design and model include important interactions or acknowledge what remains confounded.\n",
    "- Operating conditions and measurement methods remain comparable across randomised or blocked runs.\n",
    "\n",
    "**Decision rule to adapt:** Adopt a tested combination only after its worthwhile response change, uncertainty, quality guardrails and cost are supported by a confirmation trial.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [NIST: Two-level full factorial designs](https://www.itl.nist.gov/div898/handbook/pri/section3/pri3331.htm)\n"
   ],
   "id": "business-cell-083"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "factorial-experiments"
   },
   "execution_count": 42,
   "source": [
    "import numpy as np\n",
    "settings = [(-1,-1),(1,-1),(-1,1),(1,1)]\n",
    "means = [90,100,95,125]\n",
    "rows, values = [], []\n",
    "for (a,b), mean in zip(settings,means):\n",
    "    for error in [-2,2]:\n",
    "        rows.append([1,a,b,a*b])\n",
    "        values.append(mean+error)\n",
    "beta = np.linalg.lstsq(np.array(rows),np.array(values),rcond=None)[0]\n",
    "print(\"Intercept:\",round(beta[0],3))\n",
    "print(\"A, B and AB effects:\",np.round(2*beta[1:],3).tolist())\n",
    "print(\"A effect at B low:\",100-90,\"at B high:\",125-95)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Intercept: 102.5\n",
      "A, B and AB effects: [20.0, 15.0, 10.0]\n",
      "A effect at B low: 10 at B high: 30\n"
     ]
    }
   ],
   "id": "business-cell-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 43. Queueing, staffing and service-cost trade-offs\n",
    "\n",
    "**Business question:** How much service capacity is needed to control waiting without unnecessary operating cost?\n",
    "\n",
    "Queueing models connect random arrivals, variable service and available stations to long-run waiting. An M/M/c model can compare staffing choices, provided its operating assumptions and stability condition are made explicit.\n",
    "\n",
    "### Formula\n",
    "\n",
    "mu = 60/service_minutes; a = lambda/mu; rho = lambda/(c mu); P(wait) = [a^c/(c!(1−rho))]/[sum_(k=0)^(c−1) a^k/k! + a^c/(c!(1−rho))]; Wq = P(wait)/(c mu−lambda); Lq = lambda Wq.\n",
    "\n",
    "- **lambda, mu**: Arrival rate and service rate per station in the same time unit.\n",
    "- **c, rho**: Station count and average utilisation fraction.\n",
    "- **Wq, Lq**: Mean time in the queue and mean queued jobs; service time is excluded from Wq.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative packing operation: identical stations receive orders from one common queue.\n",
    "\n",
    "- 48 arrivals per hour; mean service time 4 minutes, giving mu = 15 orders per hour per station.\n",
    "- Current stations 4; R95 per station-hour; R60 per queued order-hour.\n",
    "- Compare 1–12 stations, with a maximum mean queue wait of 5 minutes.\n",
    "\n",
    "1. At 4 stations, rho = 48/(4 × 15) = 0.8. Erlang C gives P(wait) = 0.5964325.\n",
    "2. Mean queue wait = 0.5964325/(60−48) = 0.0497027 hours = 2.982162 minutes.\n",
    "3. Mean queued orders = 48 × 0.0497027 = 2.385730; hourly cost = 4 × R95 + 2.385730 × R60 = R523.1438.\n",
    "4. At 5 stations, mean wait is 0.641234 minutes and total hourly cost is R505.7793.\n",
    "5. Counts 1–3 are unstable. Among the stable counts meeting the 5-minute mean target, 5 has the lowest cost in this example.\n",
    "\n",
    "**Result:** The specified objective selects 5 stations, not the minimum count that merely has more capacity than mean demand.\n",
    "\n",
    "The recommendation is conditional on rates, cost assumptions, station range and the steady-state model. It is a candidate for operational validation, not a measured saving.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Arrivals are stationary Poisson and independent of independent exponential service durations.\n",
    "- Stations are identical and continuously available during the modelled operating condition.\n",
    "- One first-come queue has unlimited waiting space and jobs neither abandon nor block arrivals.\n",
    "- The decision concerns long-run average behaviour with consistent time units and defensible cost rates.\n",
    "\n",
    "**Decision rule to adapt:** Choose the lowest-cost stable candidate meeting the actual service constraint, then validate its observed performance and revisit the model if assumptions fail.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [MIT OCW: Queueing formulas for manufacturing systems](https://ocw.mit.edu/courses/15-763j-manufacturing-system-and-supply-chain-design-spring-2005/resources/que_for_sys_desn/)\n"
   ],
   "id": "business-cell-085"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "queueing-staffing"
   },
   "execution_count": 43,
   "source": [
    "from math import factorial\n",
    "arrival, service_rate = 48, 15\n",
    "options = []\n",
    "for stations in range(1,13):\n",
    "    rho = arrival / (stations*service_rate)\n",
    "    if rho >= 1:\n",
    "        continue\n",
    "    load = arrival / service_rate\n",
    "    tail = load**stations / (factorial(stations)*(1-rho))\n",
    "    normalizer = sum(load**k/factorial(k) for k in range(stations)) + tail\n",
    "    p_wait = tail / normalizer\n",
    "    wait_hours = p_wait / (stations*service_rate-arrival)\n",
    "    queued = arrival*wait_hours\n",
    "    cost = stations*95 + queued*60\n",
    "    if stations == 4:\n",
    "        print(\"Current wait minutes:\",round(60*wait_hours,6))\n",
    "        print(\"Current model cost: R\",round(cost,2))\n",
    "    if 60*wait_hours <= 5:\n",
    "        options.append((cost,stations,60*wait_hours))\n",
    "best = min(options)\n",
    "print(\"Lowest feasible cost stations:\",best[1])\n",
    "print(\"Selected wait minutes:\",round(best[2],6))\n",
    "print(\"Selected model cost: R\",round(best[0],2))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Current wait minutes: 2.982162\n",
      "Current model cost: R 523.14\n",
      "Lowest feasible cost stations: 5\n",
      "Selected wait minutes: 0.641234\n",
      "Selected model cost: R 505.78\n"
     ]
    }
   ],
   "id": "business-cell-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 44. Throughput, work in progress and Little’s law\n",
    "\n",
    "**Business question:** How do output rate, jobs in the system and delivery time relate?\n",
    "\n",
    "Little’s law connects average work in progress, throughput and elapsed time for a consistently defined operating system. Paired with production accounting, it helps managers distinguish useful completed output from activity and partially finished work.\n",
    "\n",
    "### Formula\n",
    "\n",
    "L = lambda W; OEE = availability × performance × quality = good_units × ideal_cycle_seconds /(planned_minutes × 60).\n",
    "\n",
    "- **L**: Long-run average jobs inside the stated system boundary.\n",
    "- **lambda**: Completed throughput per unit time under a consistent flow definition.\n",
    "- **W**: Average elapsed time spent inside that boundary, in the matching time unit.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Two illustrative checks concern a workshop’s order flow and a packaging shift’s production accounting.\n",
    "\n",
    "- Workshop: average WIP 30 jobs and accepted throughput 12 jobs per hour.\n",
    "- Packaging: planned production 480 minutes, stop time 45 minutes, ideal cycle 3 seconds, 8,000 total units and 7,840 first-pass accepted units.\n",
    "\n",
    "1. For the workshop, mean elapsed time W = 30 / 12 = 2.5 hours per job.\n",
    "2. A target of 15 completed jobs per hour at the same average WIP would be consistent with W = 30/15 = 2 hours; the formula alone does not show how to achieve it.\n",
    "3. Packaging run time = 480−45 = 435 minutes; availability = 435/480 = 90.625%.\n",
    "4. Performance = (8,000 × 3)/(435 × 60) = 91.9540%; quality = 7,840/8,000 = 98%.\n",
    "5. OEE = (7,840 × 3)/(480 × 60) = 81.6667%; accepted throughput per planned hour = 7,840/8 = 980.\n",
    "\n",
    "**Result:** The workshop averages 2.5 hours within the chosen boundary; the packaging shift delivers 980 accepted units per planned hour.\n",
    "\n",
    "These are different operational measures. Little’s law does not diagnose the cause of a delay, and OEE does not establish whether producing more units is commercially useful.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The selected boundary has consistent flow accounting; exits and throughput are defined compatibly.\n",
    "- Long-run averages are meaningful, finite and measured over a sufficiently representative period.\n",
    "- Time and count units match across every term in the relationship.\n",
    "- The OEE illustration uses a validated ideal cycle, a common product definition and counts from the same planned production window.\n",
    "\n",
    "**Decision rule to adapt:** Adopt a flow change when accepted end-to-end delivery improves at a sustainable cost, with WIP and elapsed time measured under the same consistent boundary.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [MIT OCW: Queueing notes and Little’s law](https://ocw.mit.edu/courses/15-763j-manufacturing-system-and-supply-chain-design-spring-2005/22f4805864deb06eee85acc1601463ba_queueing_note.pdf)\n",
    "- [Vorne: Calculating OEE](https://www.oee.com/calculating-oee/)\n"
   ],
   "id": "business-cell-087"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "throughput-littles-law"
   },
   "execution_count": 44,
   "source": [
    "wip, throughput = 30, 12\n",
    "print(\"Average lead time hours:\",wip/throughput)\n",
    "planned, stops = 480, 45\n",
    "cycle, total, good = 3, 8000, 7840\n",
    "availability = (planned-stops)/planned\n",
    "performance = total*cycle/((planned-stops)*60)\n",
    "quality = good/total\n",
    "oee = availability*performance*quality\n",
    "print(\"Availability %:\",round(100*availability,3))\n",
    "print(\"Performance %:\",round(100*performance,3))\n",
    "print(\"Quality %:\",round(100*quality,3))\n",
    "print(\"OEE %:\",round(100*oee,3))\n",
    "print(\"Accepted units per planned hour:\",good/(planned/60))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Average lead time hours: 2.5\n",
      "Availability %: 90.625\n",
      "Performance %: 91.954\n",
      "Quality %: 98.0\n",
      "OEE %: 81.667\n",
      "Accepted units per planned hour: 980.0\n"
     ]
    }
   ],
   "id": "business-cell-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 45. Inventory: EOQ, reorder points and safety stock\n",
    "\n",
    "**Business question:** How much should be ordered, and when should a replenishment order be released?\n",
    "\n",
    "Inventory models separate the quantity decision from the reorder trigger. Economic order quantity balances ordering and holding costs under a simple operating model; a reorder point can add protection against uncertain demand during replenishment lead time.\n",
    "\n",
    "### Formula\n",
    "\n",
    "EOQ = sqrt(2 D K/h); safety_stock = z sigma_d sqrt(L); reorder_point = mean_d L + safety_stock.\n",
    "\n",
    "- **D, K, h**: Annual demand, cost per replenishment order and annual holding cost per unit.\n",
    "- **mean_d, sigma_d**: Daily demand mean and standard deviation, estimated from relevant demand rather than censored sales alone.\n",
    "- **L, z**: Fixed lead time in days and standard normal quantile for the chosen cycle-service target.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative industrial consumable: demand is regular enough for an EOQ and normal lead-time approximation.\n",
    "\n",
    "- 12,000 units per year over 250 operating days; R200 per order and R20 annual holding cost per unit.\n",
    "- Daily mean 48 units; daily standard deviation 10 units; fixed lead time 5 operating days.\n",
    "- Chosen cycle-service target 95%, giving z = 1.644854.\n",
    "\n",
    "1. EOQ = sqrt(2 × 12,000 × 200 / 20) = 489.897949 units, suggesting a feasible batch near 490.\n",
    "2. Mean lead-time demand = 48 × 5 = 240 units.\n",
    "3. Lead-time standard deviation = 10 × sqrt(5) = 22.360680 units.\n",
    "4. Safety stock = 1.644854 × 22.360680 = 36.780045 units.\n",
    "5. Continuous reorder point = 276.780045 units; rounding upwards gives a whole-unit trigger of 277.\n",
    "\n",
    "**Result:** The illustrative policy is approximately 490 units per order with a reorder trigger near inventory position 277.\n",
    "\n",
    "The values follow the entered cost horizon and demand model. They are not an assurance that 95% of all individual unit demand will be filled without delay.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The EOQ illustration assumes steady known annual demand, instantaneous full replenishment and no quantity price discount.\n",
    "- Ordering and holding costs use a consistent annual horizon and represent relevant incremental costs.\n",
    "- The safety-stock calculation assumes fixed lead time, independent daily demand and a suitable normal approximation.\n",
    "- The service target is cycle service, and inventory position is accurately recorded.\n",
    "\n",
    "**Decision rule to adapt:** Choose feasible batch and trigger values that meet the explicitly chosen service measure at acceptable total inventory cost, then validate them on out-of-sample demand and actual lead times.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [MIT OCW: Inventory and EOQ Models](https://ocw.mit.edu/courses/esd-273j-logistics-and-supply-chain-management-fall-2009/resources/mitesd_273jf09_lec02/)\n",
    "- [MIT OCW: Probabilistic demand and safety stock](https://ocw.mit.edu/courses/esd-260j-logistics-systems-fall-2006/resources/lect11/)\n"
   ],
   "id": "business-cell-089"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "inventory-reorder"
   },
   "execution_count": 45,
   "source": [
    "from math import sqrt, ceil\n",
    "from scipy.stats import norm\n",
    "annual_demand, order_cost, annual_holding = 12000, 200, 20\n",
    "eoq = sqrt(2*annual_demand*order_cost/annual_holding)\n",
    "daily_mean, daily_sd, lead_days = 48, 10, 5\n",
    "z = norm.ppf(0.95)\n",
    "safety_stock = z*daily_sd*sqrt(lead_days)\n",
    "reorder_point = daily_mean*lead_days+safety_stock\n",
    "print(\"EOQ units:\",round(eoq,3))\n",
    "print(\"Safety stock units:\",round(safety_stock,3))\n",
    "print(\"Whole-unit reorder trigger:\",ceil(reorder_point))\n",
    "print(\"Target metric: 95% cycle service under the model\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "EOQ units: 489.898\n",
      "Safety stock units: 36.78\n",
      "Whole-unit reorder trigger: 277\n",
      "Target metric: 95% cycle service under the model\n"
     ]
    }
   ],
   "id": "business-cell-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 46. Product mix with resource and demand constraints\n",
    "\n",
    "**Business question:** Which feasible product quantities produce the greatest contribution in the planning period?\n",
    "\n",
    "Product-mix optimisation is operations research rather than a statistical significance test. It translates a business objective and resource limits into an explicit model, then searches for the best feasible plan within those assumptions.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Maximise margin_A A + margin_B B subject to 2A+B ≤ machine_hours, A+2B ≤ labour_hours, 0 ≤ A ≤ demand_A, 0 ≤ B ≤ demand_B, with integer A and B.\n",
    "\n",
    "- **A, B**: Whole batches of the two products in the same planning period.\n",
    "- **margin_A, margin_B**: Contribution per batch after variable costs, before fixed costs.\n",
    "- **Resource coefficients**: Machine and labour hours used per batch; different resources have separate constraints.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative workshop: two products compete for the same available machine and labour budgets.\n",
    "\n",
    "- Product A: R300 contribution, 2 machine hours and 1 labour hour per batch; maximum demand 40.\n",
    "- Product B: R250 contribution, 1 machine hour and 2 labour hours per batch; maximum demand 50.\n",
    "- Available machine and labour budgets: 100 hours each.\n",
    "\n",
    "1. A fractional intersection solves 2A+B = 100 and A+2B = 100, giving A = B = 33.333333.\n",
    "2. The fractional contribution is R18,333.33, but thirds of a batch are not permitted.\n",
    "3. Checking whole-number feasible plans gives A = 34 and B = 32.\n",
    "4. Resource use is 2 × 34 + 32 = 100 machine hours and 34 + 2 × 32 = 98 labour hours.\n",
    "5. Contribution is 34 × R300 + 32 × R250 = R18,200. The best single-product plan contributes max(40 × R300, 50 × R250) = R12,500.\n",
    "\n",
    "**Result:** An optimal integer plan is 34 A batches and 32 B batches, contributing R18,200 before fixed costs.\n",
    "\n",
    "The R5,700 improvement over the best single-product plan is a model comparison. Its delivery depends on the specified times, margins, demand and omitted operational details.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Resource use and contribution per batch are constant over the illustrated planning range.\n",
    "- Available machine and labour hours are separate, accurate budgets for the same period.\n",
    "- Every selected batch can be sold within the stated demand limits.\n",
    "- The example excludes setups, sequencing, uncertain processing times, overtime and working-capital constraints.\n",
    "\n",
    "**Decision rule to adapt:** Choose a feasible plan that meets all material operating constraints and improves the stated objective over the baseline; verify its executable schedule and sensitivity before committing.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [SciPy: Mixed-integer linear programming](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.milp.html)\n"
   ],
   "id": "business-cell-091"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "product-mix-optimisation"
   },
   "execution_count": 46,
   "source": [
    "best_contribution = -1\n",
    "best_a, best_b = 0, 0\n",
    "for a in range(41):\n",
    "    for b in range(51):\n",
    "        if 2*a+b <= 100 and a+2*b <= 100:\n",
    "            contribution = 300*a+250*b\n",
    "            if contribution > best_contribution:\n",
    "                best_contribution = contribution\n",
    "                best_a, best_b = a, b\n",
    "print(\"Optimal whole batches A and B:\",best_a,best_b)\n",
    "print(\"Machine hours:\",2*best_a+best_b)\n",
    "print(\"Labour hours:\",best_a+2*best_b)\n",
    "print(\"Contribution: R\",best_contribution)\n",
    "print(\"Improvement over best single product: R\",best_contribution-12500)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Optimal whole batches A and B: 34 32\n",
      "Machine hours: 100\n",
      "Labour hours: 98\n",
      "Contribution: R 18200\n",
      "Improvement over best single product: R 5700\n"
     ]
    }
   ],
   "id": "business-cell-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 47. Monte Carlo simulation and decision risk\n",
    "\n",
    "**Business question:** How wide is the range of plausible outcomes under explicit uncertain inputs?\n",
    "\n",
    "Monte Carlo simulation repeatedly samples uncertain inputs and calculates the resulting business outcomes. It exposes a distribution of results and decision trade-offs that a single average-input forecast can conceal.\n",
    "\n",
    "### Formula\n",
    "\n",
    "profit_s = (price−variable_cost) demand_s − fixed_cost; estimated mean = sum(profit_s)/N; MCSE(mean) = sample_sd(profit_s)/sqrt(N); paired difference_s = profit_B,s−profit_A,s.\n",
    "\n",
    "- **s, N**: Scenario index and number of independent simulation replications.\n",
    "- **demand_s**: A simulated demand value under the declared demand model.\n",
    "- **MCSE**: Monte Carlo standard error: numerical precision of the estimated model mean, not total business uncertainty.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative annual operating comparison: two policies face identical simulated demand and differ in cost structure.\n",
    "\n",
    "- Policy A: price R100, variable cost R60 and fixed cost R200,000.\n",
    "- Policy B: variable cost R58 and fixed cost R210,000, with the same price and demand.\n",
    "- Demand is a normal draw with mean 5,000 and standard deviation 800, rounded to a non-negative whole number; use 100,000 draws and seed 42.\n",
    "\n",
    "1. At exactly 5,000 units, Policy A profit is (100−60) × 5,000−200,000 = R0.\n",
    "2. The scenario-level policy difference is 2 × demand−10,000, so it is also zero at 5,000 units.\n",
    "3. Ignoring negligible lower-tail truncation and small rounding effects, Policy A profit standard deviation is 40 × 800 = R32,000.\n",
    "4. With 100,000 independent scenarios, the expected scale of MCSE for Policy A’s mean is R32,000/sqrt(100,000) ≈ R101.19.\n",
    "5. The paired-difference standard deviation is about 2 × 800 = R1,600, giving an MCSE near R5.06. The code calculates the seeded sample results directly.\n",
    "6. The seeded 100,000-run sample gives Policy A mean −R135.50, loss probability 50.359% and mean MCSE R101.57. Its mean paired B−A difference is −R6.78 with MCSE R5.08; these are simulated sample estimates, not exact model expectations.\n",
    "\n",
    "**Result:** Both policies have approximately zero expected profit under the specified symmetric demand model, but their loss probabilities, spreads and paired differences remain visible.\n",
    "\n",
    "The seeded results illustrate numerical sampling variation around approximately zero model expectations. A small policy difference may be numerical noise or assumption sensitivity. Neither policy is assumed to change demand, and that assumption is not established by the simulation.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The scenario generator is a plausible representation of uncertainty for the question being asked.\n",
    "- Replications used in the simple MCSE calculation are independent across scenarios.\n",
    "- The two policies can meaningfully share the same demand draw in the paired comparison.\n",
    "- No unmodelled feedback, capacity cap or accounting inconsistency changes how the policies translate demand into profit.\n",
    "\n",
    "**Decision rule to adapt:** Prefer a policy only when its modelled advantage is meaningful relative to numerical error, downside risk, implementation cost and uncertainty in the assumptions; seek external validation.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [MIT OCW: Monte Carlo Simulation and standard error resources](https://ocw.mit.edu/courses/6-0002-introduction-to-computational-thinking-and-data-science-fall-2016/download/)\n"
   ],
   "id": "business-cell-093"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "monte-carlo-risk"
   },
   "execution_count": 47,
   "source": [
    "import numpy as np\n",
    "rng = np.random.default_rng(42)\n",
    "n = 100000\n",
    "demand = np.maximum(0,np.rint(rng.normal(5000,800,n)))\n",
    "profit_a = (100-60)*demand-200000\n",
    "profit_b = (100-58)*demand-210000\n",
    "difference = profit_b-profit_a\n",
    "print(\"Policy A mean profit: R\",round(profit_a.mean(),2))\n",
    "print(\"Policy A loss probability %:\",round(100*np.mean(profit_a<0),3))\n",
    "print(\"Policy A profit 5th/95th percentiles:\",np.round(np.quantile(profit_a,[0.05,0.95]),2).tolist())\n",
    "print(\"Policy A mean MCSE: R\",round(profit_a.std(ddof=1)/np.sqrt(n),2))\n",
    "print(\"Mean paired B minus A: R\",round(difference.mean(),2))\n",
    "print(\"Paired-difference MCSE: R\",round(difference.std(ddof=1)/np.sqrt(n),2))"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Policy A mean profit: R -135.5\n",
      "Policy A loss probability %: 50.359\n",
      "Policy A profit 5th/95th percentiles: [-53080.0, 52680.0]\n",
      "Policy A mean MCSE: R 101.57\n",
      "Mean paired B minus A: R -6.78\n",
      "Paired-difference MCSE: R 5.08\n"
     ]
    }
   ],
   "id": "business-cell-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 48. Sensitivity, scenario analysis and break-even assumptions\n",
    "\n",
    "**Business question:** Which assumptions could change the decision, and by how much?\n",
    "\n",
    "Sensitivity analysis varies a specified input while holding other inputs fixed. Scenario analysis changes a coherent set of inputs together. Both are quantitative decision tools that make model dependence visible without pretending that an unassigned scenario has a known probability.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Modelled operating result = (P − V) × Q − F; demand break-even Q* = F/(P − V) when P > V; sensitivity change = outcome at changed input − base outcome.\n",
    "\n",
    "- **P, V**: Selling price and variable cost per unit.\n",
    "- **Q, F**: Sold quantity and fixed operating cost over the same period.\n",
    "- **Scenario**: A specified joint set of input values, not an automatic probability forecast.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative product line: a manager tests whether the planned demand and input costs leave enough operating result.\n",
    "\n",
    "- Base price R120, variable cost R70, quantity 5,000 and fixed operating cost R180,000.\n",
    "- Demand sensitivities: 4,000 and 6,000 units.\n",
    "- Variable-cost sensitivities: R63 and R77 per unit.\n",
    "- Combined stress: 4,000 units and R77 variable cost.\n",
    "\n",
    "1. Base contribution = (120−70) × 5,000−180,000 = R70,000.\n",
    "2. At 4,000 and 6,000 units with other inputs unchanged, results are R20,000 and R120,000.\n",
    "3. At variable costs R63 and R77 with base demand, results are R105,000 and R35,000.\n",
    "4. Combined stress gives (120−77) × 4,000−180,000 = −R8,000.\n",
    "5. Base contribution per unit is R50, so demand break-even is 180,000/50 = 3,600 units.\n",
    "\n",
    "**Result:** The isolated sensitivities remain positive, but the combined stress produces an R8,000 modelled loss.\n",
    "\n",
    "This demonstrates why joint assumptions matter. It says nothing about the probability of that stress without additional evidence and a probability model.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The underlying business calculation includes the material costs and constraints for the chosen decision.\n",
    "- Input changes and any fixed variables are explicitly stated rather than silently mixed.\n",
    "- Scenario combinations are operationally possible and share the same accounting period.\n",
    "- No probability interpretation is attached unless a defensible probability model is added.\n",
    "\n",
    "**Decision rule to adapt:** Proceed when the plan remains acceptable across relevant assumptions or a credible response protects the downside; investigate assumptions near a decision-switching threshold.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [OpenStax: Break-Even Sensitivity Analysis](https://openstax.org/books/principles-managerial-accounting/pages/3-3-perform-break-even-sensitivity-analysis-for-a-single-product-under-changing-business-situations)\n"
   ],
   "id": "business-cell-095"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "sensitivity-scenarios"
   },
   "execution_count": 48,
   "source": [
    "price, cost, quantity, fixed = 120,70,5000,180000\n",
    "base = (price-cost)*quantity-fixed\n",
    "print(\"Base operating result: R\",base)\n",
    "for q in [4000,6000]:\n",
    "    print(\"Demand\",q,\"contribution: R\",(price-cost)*q-fixed)\n",
    "for v in [63,77]:\n",
    "    print(\"Variable cost\",v,\"contribution: R\",(price-v)*quantity-fixed)\n",
    "print(\"Combined stress contribution: R\",(price-77)*4000-fixed)\n",
    "print(\"Base demand break-even:\",fixed/(price-cost),\"units\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Base operating result: R 70000\n",
      "Demand 4000 contribution: R 20000\n",
      "Demand 6000 contribution: R 120000\n",
      "Variable cost 63 contribution: R 105000\n",
      "Variable cost 77 contribution: R 35000\n",
      "Combined stress contribution: R -8000\n",
      "Base demand break-even: 3600.0 units\n"
     ]
    }
   ],
   "id": "business-cell-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 49. Difference-in-differences for business interventions\n",
    "\n",
    "**Business question:** Did a business change improve the outcome beyond the change that would otherwise have occurred?\n",
    "\n",
    "Difference-in-differences compares changes in an intervention group with changes in a suitable comparison group. It can support a causal interpretation only when the counterfactual assumptions and study design are credible.\n",
    "\n",
    "### Formula\n",
    "\n",
    "DiD = (mean_treated_after−mean_treated_before) − (mean_comparison_after−mean_comparison_before).\n",
    "\n",
    "- **Treated group**: Business units exposed to the intervention in the study period.\n",
    "- **Comparison group**: Units used to represent the counterfactual change without the intervention.\n",
    "- **Parallel counterfactual trends**: An identifying assumption about what would have happened without treatment, not a directly observed post-treatment trend.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative service-policy evaluation: two branches report comparable accepted jobs per week before and after one changes its process.\n",
    "\n",
    "- Treated branch mean: 80 before and 100 after.\n",
    "- Comparison branch mean: 70 before and 80 after.\n",
    "- These are illustrative aggregates; no underlying panel or assignment study is supplied.\n",
    "\n",
    "1. Treated change = 100−80 = 20 jobs per week.\n",
    "2. Comparison change = 80−70 = 10 jobs per week.\n",
    "3. DiD point estimate = 20−10 = 10 jobs per week.\n",
    "4. Under additive parallel trends, the treated branch’s no-intervention counterfactual would be 80+10 = 90.\n",
    "5. The observed treated outcome 100 exceeds that counterfactual by 10. A naive before/after comparison attributes the full 20 to the intervention.\n",
    "\n",
    "**Result:** The illustrative DiD point estimate is an additional 10 accepted jobs per week.\n",
    "\n",
    "This becomes a causal effect estimate only if the identifying assumptions are defended. Different demand, simultaneous equipment changes or selective staffing could explain the difference instead.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Parallel untreated trends are plausible under the stated design and outcome scale.\n",
    "- Treatment does not change outcomes before its defined introduction.\n",
    "- Comparison units are not materially affected by spillovers or treatment-related resource reallocations.\n",
    "- Measurement, composition and concurrent changes do not create an unexplained differential trend.\n",
    "\n",
    "**Decision rule to adapt:** Consider expansion only when the effect is practically worthwhile, uncertainty and identifying assumptions are credible, and full costs and quality guardrails support the decision.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [Roth, Sant’Anna, Bilinski and Poe: What’s Trending in Difference-in-Differences?](https://psantanna.com/files/RSBP_DiD_Review.pdf)\n"
   ],
   "id": "business-cell-097"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "causal-difference-in-differences"
   },
   "execution_count": 49,
   "source": [
    "treated_before, treated_after = 80,100\n",
    "comparison_before, comparison_after = 70,80\n",
    "treated_change = treated_after-treated_before\n",
    "comparison_change = comparison_after-comparison_before\n",
    "did = treated_change-comparison_change\n",
    "counterfactual = treated_before+comparison_change\n",
    "print(\"Treated change:\",treated_change,\"jobs per week\")\n",
    "print(\"Comparison change:\",comparison_change,\"jobs per week\")\n",
    "print(\"DiD point estimate:\",did,\"jobs per week\")\n",
    "print(\"Assumed treated counterfactual:\",counterfactual)\n",
    "print(\"No p-value: four means do not supply valid uncertainty.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Treated change: 20 jobs per week\n",
      "Comparison change: 10 jobs per week\n",
      "DiD point estimate: 10 jobs per week\n",
      "Assumed treated counterfactual: 90\n",
      "No p-value: four means do not supply valid uncertainty.\n"
     ]
    }
   ],
   "id": "business-cell-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 50. Markov chains for customer and operating states\n",
    "\n",
    "**Business question:** How might the numbers of customers or assets in different states evolve under stated transition probabilities?\n",
    "\n",
    "A Markov chain tracks movement among defined states using a transition matrix. It gives a structured scenario for retention, risk status or equipment condition while exposing its memory and transition-stability assumptions.\n",
    "\n",
    "### Formula\n",
    "\n",
    "expected_counts_(t+1) = expected_counts_t P; expected_counts_t = expected_counts_0 P^t when P is constant.\n",
    "\n",
    "- **P_ij**: Conditional probability of moving from current state i to next-period state j.\n",
    "- **State-count vector**: Expected numbers in each state, written as a row vector in this example.\n",
    "- **Absorbing state**: A state with probability one of remaining in itself once reached.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative customer cohort with active, at-risk and lost states and no new acquisitions during a two-month scenario.\n",
    "\n",
    "- Initial counts: 800 active, 150 at risk and 50 lost.\n",
    "- Active transition row: 0.80, 0.15, 0.05. At-risk row: 0.30, 0.50, 0.20. Lost row: 0, 0, 1.\n",
    "- Illustrative monthly contributions: R100 per active customer, R40 per at-risk customer and zero per lost customer.\n",
    "\n",
    "1. Month-1 active = 800 × 0.80 + 150 × 0.30 = 685.\n",
    "2. Month-1 at risk = 800 × 0.15 + 150 × 0.50 = 195; lost = 40+30+50 = 120.\n",
    "3. Month-2 active = 685 × 0.80 + 195 × 0.30 = 606.5.\n",
    "4. Month-2 at risk = 685 × 0.15 + 195 × 0.50 = 200.25; lost = 193.25.\n",
    "5. Month-1 contribution = 685 × R100 + 195 × R40 = R76,300; month-2 contribution = R68,660.\n",
    "\n",
    "**Result:** The fixed-cohort scenario moves from 800 active customers to an expected 606.5 active after two periods.\n",
    "\n",
    "The path is conditional on the supplied matrix and absorbing lost state. It does not show that a company will follow this path or that an intervention can achieve different transitions.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- Current state captures the history relevant to the next transition for this approximation.\n",
    "- Transition probabilities remain sufficiently stable over the horizon or are explicitly time-varying.\n",
    "- All material states and acquisition, reactivation or exit mechanisms are represented.\n",
    "- Customers or assets have comparable transitions within states, or heterogeneity is modelled separately.\n",
    "\n",
    "**Decision rule to adapt:** Use a transition scenario when states and probabilities validate adequately for the horizon; base intervention decisions on evidence about achievable transition changes and their cost.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [MIT OCW: Finite-state Markov chains, matrix approach](https://live.ocw.mit.edu/courses/6-262-discrete-stochastic-processes-spring-2011/2fdbd4633466ba1429e7cc24bce37514_MIT6_262S11_lec07.pdf)\n"
   ],
   "id": "business-cell-099"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "markov-chains"
   },
   "execution_count": 50,
   "source": [
    "import numpy as np\n",
    "transition = np.array([[0.8,0.15,0.05],[0.3,0.5,0.2],[0,0,1]])\n",
    "counts = np.array([800.0,150.0,50.0])\n",
    "margin = np.array([100,40,0])\n",
    "assert np.allclose(transition.sum(axis=1),1)\n",
    "for month in [1,2]:\n",
    "    counts = counts @ transition\n",
    "    print(\"Month\",month,\"active/at-risk/lost:\",np.round(counts,3).tolist())\n",
    "    print(\"Expected contribution: R\",round(counts @ margin,2))\n",
    "print(\"Lost is absorbing; this model includes no new customers.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Month 1 active/at-risk/lost: [685.0, 195.0, 120.0]\n",
      "Expected contribution: R 76300.0\n",
      "Month 2 active/at-risk/lost: [606.5, 200.25, 193.25]\n",
      "Expected contribution: R 68660.0\n",
      "Lost is absorbing; this model includes no new customers.\n"
     ]
    }
   ],
   "id": "business-cell-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 51. Retention, cohorts and customer lifetime value\n",
    "\n",
    "**Business question:** What future contribution could a customer relationship support under explicit retention and timing assumptions?\n",
    "\n",
    "Customer lifetime value combines future relationship persistence with contribution and discounting. It supports an economic comparison of acquisition or retention proposals when margin, horizon, survival definition and cash timing are unambiguous.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Future-horizon CLV = sum_(t=1)^T [m r^t /(1+d)^t] − CAC; period retention = retained eligible customers / eligible customers at period start.\n",
    "\n",
    "- **m**: Contribution per active customer at a future period end, after relevant variable fulfilment costs.\n",
    "- **r, d**: Per-period retention probability and discount rate using the same time unit.\n",
    "- **T, CAC**: Finite future horizon and acquisition cost included for the stated current decision.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative annual subscription: a new acquisition is evaluated using future contribution only.\n",
    "\n",
    "- R120 contribution per active customer at each future year end.\n",
    "- Constant annual retention 80%; annual discount rate 10%; five-year future horizon.\n",
    "- R150 acquisition cost paid now; no immediate current-period margin is included.\n",
    "\n",
    "1. Year-1 expected discounted contribution = R120 × 0.8/1.1 = R87.272727.\n",
    "2. Year-2 value = R120 × 0.8²/1.1² = R63.471074.\n",
    "3. Continue through year 5 using the same survival and discount convention.\n",
    "4. The five future discounted contributions total R254.891680.\n",
    "5. Subtract R150 acquisition cost to obtain R104.891680. For an existing customer whose acquisition cost is sunk, remaining value under these assumptions is R254.891680.\n",
    "\n",
    "**Result:** The new-acquisition scenario has R104.89 in expected discounted contribution after the specified acquisition cost.\n",
    "\n",
    "This is a finite-horizon model conditional on constant retention and margin, not realised customer value, revenue or a guarantee that retention spending will pay.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The example has constant homogeneous retention and contribution for five future periods.\n",
    "- Retention and discount rates use the same annual unit and stated year-end cash convention.\n",
    "- Contribution excludes variable costs; acquisition cost is neither omitted nor double-counted.\n",
    "- Referrals, expansion, reactivation and intervention effects are omitted unless explicitly added.\n",
    "\n",
    "**Decision rule to adapt:** Choose a customer investment when credible incremental discounted contribution exceeds full incremental cost, considering sensitivity, capacity and the time needed to measure its effect.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [Fader and Hardie: Reconciling and Clarifying CLV Formulas](https://brucehardie.com/notes/024/)\n",
    "- [Fader and Hardie: How to Project Customer Retention](https://brucehardie.com/papers/021/)\n"
   ],
   "id": "business-cell-101"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "retention-lifetime-value"
   },
   "execution_count": 51,
   "source": [
    "margin, retention, discount = 120,0.8,0.1\n",
    "horizon, acquisition_cost = 5,150\n",
    "present_values = []\n",
    "for year in range(1,horizon+1):\n",
    "    value = margin*retention**year/(1+discount)**year\n",
    "    present_values.append(value)\n",
    "future_value = sum(present_values)\n",
    "print(\"Future annual present values:\",[round(v,4) for v in present_values])\n",
    "print(\"Future contribution before acquisition: R\",round(future_value,2))\n",
    "print(\"CLV after current acquisition cost: R\",round(future_value-acquisition_cost,2))\n",
    "print(\"Convention: future year-end margin only, no immediate current-period margin.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Future annual present values: [87.2727, 63.4711, 46.1608, 33.5715, 24.4156]\n",
      "Future contribution before acquisition: R 254.89\n",
      "CLV after current acquisition cost: R 104.89\n",
      "Convention: future year-end margin only, no immediate current-period margin.\n"
     ]
    }
   ],
   "id": "business-cell-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 52. Price elasticity, revenue and contribution\n",
    "\n",
    "**Business question:** How sensitive is demand to price, and what does that mean for contribution rather than revenue alone?\n",
    "\n",
    "Price elasticity expresses quantity responsiveness relative to a price change. It helps structure a pricing analysis, but a descriptive price–sales comparison does not by itself establish the causal customer response to a proposed new price.\n",
    "\n",
    "### Formula\n",
    "\n",
    "Arc elasticity = [(Q2−Q1)/((Q1+Q2)/2)] / [(P2−P1)/((P1+P2)/2)]; revenue = P Q; contribution before fixed costs = (P−V) Q.\n",
    "\n",
    "- **P1, P2**: Prices in two comparable conditions, with a nonzero price change.\n",
    "- **Q1, Q2**: Corresponding demand quantities over comparable periods and exposure.\n",
    "- **V**: Relevant variable cost per sold unit; it is constant only in this illustration.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative retail comparison: two prices are associated with different quantities, with no causal assignment information supplied.\n",
    "\n",
    "- Condition 1: price R100 and quantity 1,000 units.\n",
    "- Condition 2: price R110 and quantity 850 units.\n",
    "- Variable cost R60 per unit in either condition; fixed costs excluded.\n",
    "\n",
    "1. Midpoint quantity change = (850−1,000)/925 = −0.1621622, or −16.21622%.\n",
    "2. Midpoint price change = (110−100)/105 = 0.0952381, or 9.52381%.\n",
    "3. Arc elasticity = −0.1621622/0.0952381 = −1.7027027.\n",
    "4. Revenue changes from R100,000 to R93,500, a decline of R6,500.\n",
    "5. Contribution changes from (100−60) × 1,000 = R40,000 to (110−60) × 850 = R42,500, an increase of R2,500.\n",
    "\n",
    "**Result:** The pair has an elastic descriptive arc response with magnitude about 1.70, while its accounting contribution is higher at the second condition.\n",
    "\n",
    "The example separates revenue from contribution. It neither proves that price caused the quantity change nor identifies the best price outside the two observations.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The descriptive comparison uses positive prices and quantities with a nonzero price difference.\n",
    "- Quantities refer to comparable demand exposure rather than differently sized or stocked periods.\n",
    "- The contribution example holds variable cost per unit constant and excludes unchanged fixed costs.\n",
    "- A causal interpretation requires a suitable identification design beyond the two observed pairs.\n",
    "\n",
    "**Decision rule to adapt:** Consider a price change when credible demand-response evidence and full incremental contribution support it, with customer, capacity and quality guardrails and uncertainty made explicit.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [OpenStax: Price Elasticity of Demand and Supply](https://openstax.org/books/principles-economics-3e/pages/5-1-price-elasticity-of-demand-and-price-elasticity-of-supply)\n"
   ],
   "id": "business-cell-103"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "price-elasticity"
   },
   "execution_count": 52,
   "source": [
    "price_1, price_2 = 100,110\n",
    "quantity_1, quantity_2 = 1000,850\n",
    "variable_cost = 60\n",
    "quantity_change = (quantity_2-quantity_1)/((quantity_1+quantity_2)/2)\n",
    "price_change = (price_2-price_1)/((price_1+price_2)/2)\n",
    "elasticity = quantity_change/price_change\n",
    "print(\"Midpoint quantity change %:\",round(100*quantity_change,4))\n",
    "print(\"Midpoint price change %:\",round(100*price_change,4))\n",
    "print(\"Arc elasticity:\",round(elasticity,6))\n",
    "print(\"Revenue before and after: R\",price_1*quantity_1,price_2*quantity_2)\n",
    "print(\"Contribution before and after: R\",(price_1-variable_cost)*quantity_1,(price_2-variable_cost)*quantity_2)\n",
    "print(\"This pair alone does not identify a causal price effect.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Midpoint quantity change %: -16.2162\n",
      "Midpoint price change %: 9.5238\n",
      "Arc elasticity: -1.702703\n",
      "Revenue before and after: R 100000 93500\n",
      "Contribution before and after: R 40000 42500\n",
      "This pair alone does not identify a causal price effect.\n"
     ]
    }
   ],
   "id": "business-cell-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 53. Discounted cash flow, NPV and payback\n",
    "\n",
    "**Business question:** Does a proposed business project cover its cost after allowing for cash timing and the stated required return?\n",
    "\n",
    "Discounted cash-flow analysis translates future cash flows to a common present-time basis. Net present value and payback are quantitative financial decision measures, not statistical tests or guarantees about the project’s future performance.\n",
    "\n",
    "### Formula\n",
    "\n",
    "NPV = −initial_outlay + sum_(t=1)^T cash_flow_t /(1+r)^t; simple fractional payback = full years before recovery + unrecovered outlay / next-year cash flow, under a uniform-within-year approximation.\n",
    "\n",
    "- **cash_flow_t**: Incremental net cash flow at the stated period end, not accounting profit.\n",
    "- **r**: Discount rate per matching period, consistent with the cash-flow basis.\n",
    "- **T**: Explicit project horizon, including relevant terminal and working-capital cash flows if present.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Illustrative equipment proposal with a current outlay and three future annual net cash inflows.\n",
    "\n",
    "- Initial outlay R100,000 at time 0.\n",
    "- Year-end incremental net cash inflows: R40,000, R45,000 and R50,000.\n",
    "- Annual discount rate 10%; no additional terminal, tax or working-capital flows are included in this simplified example.\n",
    "\n",
    "1. Year-1 present value = R40,000/1.1 = R36,363.636364.\n",
    "2. Year-2 present value = R45,000/1.1² = R37,190.082645.\n",
    "3. Year-3 present value = R50,000/1.1³ = R37,565.740045.\n",
    "4. NPV = R36,363.636364 + R37,190.082645 + R37,565.740045 − R100,000 = R11,119.459053.\n",
    "5. Undiscounted recovery after year 2 leaves R15,000; assuming uniform inflow within year 3 gives simple payback 2 + 15,000/50,000 = 2.3 years.\n",
    "\n",
    "**Result:** The scenario has NPV R11,119.46 at 10%, with approximate simple payback of 2.3 years under the separate timing convention.\n",
    "\n",
    "The positive modelled NPV supports consideration under these assumptions. It is not evidence that the equipment will achieve those cash flows or that the project automatically meets all business constraints.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The example uses current initial expenditure and end-of-year future inflows.\n",
    "- The discount rate and cash flows use the same annual time unit and nominal/real convention.\n",
    "- Only relevant incremental cash flows belong in the project comparison; sunk costs are treated appropriately.\n",
    "- Forecast distributions, capital constraints and omitted tax or working-capital effects need separate treatment in an actual decision.\n",
    "\n",
    "**Decision rule to adapt:** Consider a feasible project when its risk-consistent incremental NPV and relevant operating and liquidity constraints are acceptable across credible assumptions; compare alternatives before committing.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [OpenStax: Net Present Value Method](https://openstax.org/books/principles-finance/pages/16-2-net-present-value-npv-method)\n"
   ],
   "id": "business-cell-105"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "financial-decision-maths"
   },
   "execution_count": 53,
   "source": [
    "initial_outlay = 100000\n",
    "cash_flows = [40000,45000,50000]\n",
    "discount_rate = 0.10\n",
    "present_values = []\n",
    "for year, cash in enumerate(cash_flows,start=1):\n",
    "    present_values.append(cash/(1+discount_rate)**year)\n",
    "npv = sum(present_values)-initial_outlay\n",
    "print(\"Future cash-flow present values:\",[round(v,2) for v in present_values])\n",
    "print(\"NPV at 10%: R\",round(npv,2))\n",
    "payback = 2+(initial_outlay-cash_flows[0]-cash_flows[1])/cash_flows[2]\n",
    "print(\"Approximate simple payback:\",round(payback,2),\"years\")\n",
    "print(\"Payback fraction assumes uniform year-3 inflow; NPV uses year-end cash flows.\")"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Future cash-flow present values: [36363.64, 37190.08, 37565.74]\n",
      "NPV at 10%: R 11119.46\n",
      "Approximate simple payback: 2.3 years\n",
      "Payback fraction assumes uniform year-3 inflow; NPV uses year-end cash flows.\n"
     ]
    }
   ],
   "id": "business-cell-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 54. Decision costs, contribution and break-even thresholds\n",
    "\n",
    "**Business question:** How much volume or risk reduction is needed for an action to cover its relevant cost?\n",
    "\n",
    "Break-even and expected-cost calculations connect business decisions to contribution, fixed cost and uncertain consequences. They are decision-accounting tools that use statistical estimates as inputs; the arithmetic does not establish that demand or risk estimates are correct.\n",
    "\n",
    "### Formula\n",
    "\n",
    "unit contribution = P−V; break-even quantity = F/(P−V) when P>V; expected net value of a perfect preventive inspection = p L−C; inspection switching probability = C/L for L>0.\n",
    "\n",
    "- **P, V, F**: Selling price, variable cost per sold unit and relevant fixed cost in one period.\n",
    "- **p, L**: Probability of the preventable defect and its incremental loss if not prevented.\n",
    "- **C**: Incremental action cost; the simple inspection example assumes perfect detection and prevention.\n",
    "\n",
    "### Worked business example\n",
    "\n",
    "Two separate illustrative checks show volume break-even and an inspection decision.\n",
    "\n",
    "- Product: selling price R150, variable cost R90 and monthly fixed cost R90,000; planned sales 1,800 units.\n",
    "- Separate inspection case: R80 inspection cost per item, defect probability 30% and R400 avoidable loss per defective item.\n",
    "- Inspection is assumed to detect and prevent all relevant loss, with no additional errors or costs.\n",
    "\n",
    "1. Unit contribution = R150−R90 = R60.\n",
    "2. Monthly break-even = R90,000/R60 = 1,500 sold units.\n",
    "3. At 1,800 units, the modelled operating result after fixed cost = 1,800 × R60 − R90,000 = R18,000.\n",
    "4. Without inspection, expected defect loss = 0.30 × R400 = R120 per item; perfect inspection costs R80, giving R40 expected net benefit.\n",
    "5. The inspection switching probability is 80/400 = 0.20, or 20%. At exactly 20%, this simplified expected-cost comparison is indifferent.\n",
    "\n",
    "**Result:** The product case breaks even at 1,500 units. In the separate perfect-inspection case, a 30% defect risk exceeds the 20% switching threshold.\n",
    "\n",
    "Neither threshold predicts volume or proves the defect probability. The decision changes if contribution, prevention effectiveness, capacity or consequence estimates differ.\n",
    "\n",
    "### Assumptions and interpretation\n",
    "\n",
    "- The volume example has constant unit price and variable cost within its stated operating range.\n",
    "- Fixed costs and volumes share the same monthly horizon, and all counted units are sold.\n",
    "- The inspection example uses risk-neutral expected cost and a defensible defect probability.\n",
    "- The simple threshold assumes perfect prevention, no false-positive loss and no material capacity or other intervention cost.\n",
    "\n",
    "**Decision rule to adapt:** Select a feasible action when credible incremental benefit exceeds relevant incremental cost and consequence constraints; examine uncertainty around the threshold rather than treating it as a certainty.\n",
    "\n",
    "### Sources\n",
    "\n",
    "- [OpenStax: Break-Even Point in Units and Dollars](https://openstax.org/books/principles-managerial-accounting/pages/3-2-calculate-a-break-even-point-in-units-and-dollars)\n"
   ],
   "id": "business-cell-107"
  },
  {
   "cell_type": "code",
   "metadata": {
    "business_module": "decision-costs-break-even"
   },
   "execution_count": 54,
   "source": [
    "from math import ceil\n",
    "price, variable_cost, fixed_cost = 150,90,90000\n",
    "unit_contribution = price-variable_cost\n",
    "break_even = ceil(fixed_cost/unit_contribution)\n",
    "planned_units = 1800\n",
    "print(\"Unit contribution: R\",unit_contribution)\n",
    "print(\"Whole-unit break-even:\",break_even)\n",
    "print(\"Operating result at 1800 units: R\",planned_units*unit_contribution-fixed_cost)\n",
    "defect_probability, avoided_loss, inspection_cost = 0.30,400,80\n",
    "net_value = defect_probability*avoided_loss-inspection_cost\n",
    "print(\"Separate perfect-inspection expected net benefit: R\",net_value)\n",
    "print(\"Perfect-inspection switching risk %:\",100*inspection_cost/avoided_loss)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Unit contribution: R 60\n",
      "Whole-unit break-even: 1500\n",
      "Operating result at 1800 units: R 18000\n",
      "Separate perfect-inspection expected net benefit: R 40.0\n",
      "Perfect-inspection switching risk %: 20.0\n"
     ]
    }
   ],
   "id": "business-cell-108"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12.14"
  },
  "business_learning_resource": {
   "author": "Gareth Grant",
   "modules": 54,
   "tested_packages": {
    "numpy": "2.3.5",
    "scipy": "1.17.0",
    "scikit-learn": "1.8.0"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
