
Students in this course will develop a comprehensive understanding of business analytics and artificial intelligence fundamentals, covering topics such as business requirement analysis, data collection, and machine learning. Designed specifically for undergraduate and Master of Business Administration (MBA) students with zero prior programming background, this course emphasizes intuitive, evidence-based reasoning over abstract theoretical complexity.
Through hands-on exercises, students gain operational proficiency in Python programming, progressing from core syntax to intermediate techniques essential for enterprise data projects. Students acquire data manipulation skills using foundational libraries including NumPy and Pandas for data cleaning, aggregation, and financial visualization. They also master automated web data extraction techniques using HyperText Markup Language (HTML), Cascading Style Sheets (CSS), and Beautiful Soup to collect public competitor intelligence.
With an introduction to modern machine learning tools through Scikit-Learn, participants learn to implement, interpret, and evaluate predictive models. Ethical considerations in artificial intelligence projects, algorithmic risk management, and governance frameworks are examined to ensure the responsible application of these analytical technologies.
Module 1 establishes the computational foundation for business students. Students learn to translate executive business questions into structured quantitative workflows, set up a standardized Python execution environment, master variables and arithmetic for commercial metrics, control program flow, and inspect tabular corporate filings using Pandas.

Lecture Presentation: Download Slides (PDF)
Python Interpreter: The computational engine that reads Python source code and executes instructions sequentially line-by-line in real time without requiring compilation.Variable Assignment: Storing data in computer memory using an assignment operator (=) and an intuitive descriptive label (such as net_sales = 574785.0), replacing fragile cell coordinates like C13.Primitive Data Types: The foundational categories of information processed by Python: whole numbers (int), decimal numbers (float), and text strings (str).Traceback & Exception: The automatic diagnostic navigation report generated by Python when an instruction violates a syntax or runtime rule, pinpointing the exact file and line number.Integrated Development Environment (IDE): A unified software workstation (Google Antigravity IDE) providing an editor, execution terminal, file explorer, and integrated AI assistant in a single interface.=C13-E13) to self-documenting computational recipes (operating_expense = net_sales - operating_income). Code variables retain clear business meaning and eliminate silent formula drift.net_sales = 574785.0, operating_income = 36852.0) and calculating Operating Expense and Operating Margin Percentage with standard math operators (-, /, *).netsales instead of net_sales), observing the NameError in the terminal, capturing it with Windows Key + Shift + S, and pasting into the AI chat to verify how the co-pilot identifies the typo and supplies the correction.Segment_Name: North America, International, AWS, Consolidated Total.Net_Sales_USD_M: Revenue in millions of U.S. Dollars.Operating_Income_USD_M: Operating income in millions of U.S. Dollars.
[1] File Explorer (Left Panel): Workspace file hierarchy. Used to organize corporate datasets (data/), slide decks (slides/), Python scripts (.py), and curriculum documentation (.md).[2] Code Editor & Notebook Canvas (Center Top): Primary workspace for writing Python code, defining financial variables, and executing arithmetic business formulas.[3] AI Agent Chat Canvas (Right Panel): An interactive AI pair-programming assistant powered by Gemini. Students paste code snippets or error screenshots directly into this window to receive plain-English root cause explanations and verified code corrections.[4] Integrated Terminal & Console (Center Bottom): Command line interface running the Python execution kernel. Displays script output results and detailed system error tracebacks.[4] (Terminal), which names the error type (e.g., NameError, SyntaxError, TypeError).Windows Key + Shift + S (Windows) or Command + Shift + 4 (macOS).[3] (AI Agent Chat), press Ctrl + V to attach the captured image, and ask: “Why did this error happen, and what is the exact corrected code?”[2].data/session_1_1_dataset.csv in your working directory and open the raw file via Panel [1] (File Explorer) to observe comma-separated tabular records.$574,785 million and Operating Income equaled $36,852 million.# Amazon Consolidated Financial Metrics for FY2023 (in USD Millions)
net_sales = 574785.0
operating_income = 36852.0
# Calculate Operating Expenses
operating_expense = net_sales - operating_income
# Calculate Operating Margin Percentage
operating_margin_pct = (operating_income / net_sales) * 100.0
print("Operating Expense (USD M):", operating_expense)
print("Operating Margin (%):", round(operating_margin_pct, 2))
Net_Sales is in cell C13 (574785.00) and Operating_Income is in cell E13 (36852.00), the expense formula in cell D13 is =C13-E13, and the margin formula in cell F13 is =(E13/C13)*100.operating_income / net_sales) performs the identical mathematical operation as cell references, but uses memorable descriptive English words instead of abstract grid coordinates like E13.aws_sales = 90757.0
aws_income = 24631.0
aws_margin_pct = (aws_income / aws_sales) * 100.0
print("AWS Operating Margin (%):", round(aws_margin_pct, 2))
Confirm that the AWS operating margin (27.14%) is over four times higher than the consolidated corporate operating margin (6.41%), demonstrating how cloud infrastructure drives corporate operating cash flow.
session_1_1_practice.py to calculate financial metrics across multiple business units and practice error debugging.aws_sales = 90757.0, aws_income = 24631.0). Compute aws_margin_pct and print the formatted result with round(..., 2).print() statement (e.g., print("AWS Margin:", round(aws_margin_pct, 2)). Run the script in Panel [4] (Terminal), observe the SyntaxError, capture the terminal message using Windows Key + Shift + S, paste it into Panel [3] (AI Agent Chat) with Ctrl + V, and verify the AI’s explanation and fix.
| Schedule: Week 2 (115/09/20 - 115/09/26) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Boolean Expression: A logical comparison that evaluates strictly to True or False, used by computers to test commercial conditions (such as annual_spend >= 50000.0).Conditional Branching (else): Directing code execution down distinct logical pathways depending on operational thresholds, eliminating complex spreadsheet nested logic.List Collection: An ordered, mutable sequence of business records enclosed in square brackets (e.g., daily_orders = [120, 85, 94, 142]), indexed sequentially starting from zero.Dictionary Collection: A key-value associative data structure enclosed in curly braces (e.g., {"client_id": "CUST-101", "annual_spend_USD": 145000.0}), enabling instant data retrieval by descriptive business keys rather than numeric indices.Definite Iteration (for loop): A programmatic control structure that automatically iterates over every record in a collection, executing identical business rules across thousands of entries in milliseconds.=IF(C2>100000, "Platinum", IF(C2>50000, "Gold", IF(C2>20000, "Silver", "Standard"))). These formulas quickly become unreadable, impossible to audit, and vulnerable to formula drift. In Python, conditional branching (if-elif-else) structures business rules into clean vertical indentation blocks that mirror managerial decision trees.for loop executes repetitive calculations across 10 records or 1,000,000 records with identical mathematical precision and zero cognitive degradation.{} or BEGIN/END tokens, Python enforces clean code formatting through whitespace indentation (4 spaces). An IndentationError occurs when code blocks are misaligned, serving as an automated guardrail for code readability.annual_spend = 82000.0
if annual_spend >= 100000.0:
tier = "Platinum"
discount_rate = 0.15
elif annual_spend >= 50000.0:
tier = "Gold"
discount_rate = 0.10
elif annual_spend >= 20000.0:
tier = "Silver"
discount_rate = 0.05
else:
tier = "Standard"
discount_rate = 0.0
print(f"Customer Tier: {tier} | Approved Discount: {discount_rate * 100:.0f}%")
daily_sales = [4200.0, 5100.0, 3900.0, 6200.0, 7800.0, 8400.0, 4900.0]
total_revenue = 0.0
for sale in daily_sales:
total_revenue += sale
avg_daily_sales = total_revenue / len(daily_sales)
print("Total Weekly Revenue (USD):", round(total_revenue, 2))
print("Average Daily Sales (USD):", round(avg_daily_sales, 2))
client = {
"client_id": "CUST-104",
"company_name": "Apex Logistics",
"annual_spend_USD": 215000.0,
"credit_limit_USD": 75000.0,
"outstanding_balance_USD": 23400.0
}
available_credit = client["credit_limit_USD"] - client["outstanding_balance_USD"]
print(f"{client['company_name']} Available Credit: ${available_credit:,.2f}")
Customer_ID: Unique client identification code (e.g., CUST-101).Industry_Segment: Commercial vertical (Retail, Technology, Healthcare, Finance, Manufacturing).Annual_Spend_USD: Total historical purchase volume in U.S. Dollars.Order_Count: Total orders completed in the fiscal year.Avg_Order_Value_USD: Average transaction size in U.S. Dollars.Payment_Terms_Days_Count: Invoiced credit settlement period (30, 60, 90 days).Risk_Score_Count: Internal risk assessment index (1 to 100).session_1_2_automation.py in your working directory.data/session_1_2_dataset.csv:
clients = [
{"id": "CUST-101", "segment": "Retail", "spend": 145000.0, "risk": 15},
{"id": "CUST-102", "segment": "Technology", "spend": 82000.0, "risk": 22},
{"id": "CUST-103", "segment": "Healthcare", "spend": 31000.0, "risk": 38},
{"id": "CUST-104", "segment": "Finance", "spend": 215000.0, "risk": 12},
{"id": "CUST-105", "segment": "Manufacturing", "spend": 64000.0, "risk": 45}
]
for loop that iterates over each client, applies conditional branching based on spend, and computes an approved credit limit:
for c in clients:
# Tiering logic based on annual purchase volume
if c["spend"] >= 100000.0 and c["risk"] < 30:
c["tier"] = "Platinum"
c["credit_limit"] = c["spend"] * 0.40
elif c["spend"] >= 50000.0 and c["risk"] < 50:
c["tier"] = "Gold"
c["credit_limit"] = c["spend"] * 0.25
else:
c["tier"] = "Standard"
c["credit_limit"] = c["spend"] * 0.10
print(f"Client {c['id']} ({c['segment']}): Tier={c['tier']} | Credit Limit=${c['credit_limit']:,.2f}")
[4] (Terminal) using $ python session_1_2_automation.py. Confirm that all 5 client accounts are evaluated and printed with proper credit limits.session_1_2_practice.py to automate a multi-tier commercial commission payout pipeline.sales_reps = [{"name": "Alice", "revenue": 142000.0}, {"name": "Bob", "revenue": 68000.0}, {"name": "Charlie", "revenue": 35000.0}]. Write a loop calculating commission payouts: 12% for revenue over $100,000, 8% for revenue between $50,000 and $100,000, and 5% for revenue below $50,000.if block (e.g., adding 2 extra spaces or removing indentation). Run the script in Panel [4] (Terminal), observe the red IndentationError: unexpected indent, capture the terminal traceback with Windows Key + Shift + S, paste the image into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains whitespace alignment.commission_payout back into each rep’s dictionary, and print a formatted compensation summary with zero syntax errors. Verify that the script terminates with return code 0.
| Schedule: Week 3 (115/09/27 - 115/10/03) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Vectorized Computation: Executing mathematical operations across entire numeric arrays or data columns simultaneously in compiled C memory, replacing slow Python row-by-row loops.Pandas Series: A one-dimensional labeled array in Pandas capable of holding any data type, representing a single column in an enterprise tabular dataset.Pandas DataFrame: A two-dimensional, size-mutable tabular data structure with labeled axes (rows and columns), serving as the primary analytical workhorse for commercial data.Tabular CSV Ingestion: Reading structured comma-separated corporate ledgers directly into memory using pd.read_csv(), parsing data types and column headers automatically.Explicit Data Selection (.loc[] vs .iloc[]): Selecting specific subsets of records using label-based indexing (.loc[]) or integer position-based indexing (.iloc[]).for loops are intuitive, calculating metrics across 500,000 retail records using a loop is computationally slow. NumPy and Pandas use vectorized execution, operating on entire memory blocks in parallel, reducing execution time from seconds to milliseconds.float64, int64, object, datetime64). This prevents silent financial corruption during aggregation..info() (data types and null counts), .describe() (descriptive summary statistics), and .shape (row and column dimensions).import pandas as pd
df = pd.read_csv("data/session_1_3_dataset.csv")
print("Dataset Dimensions (Rows, Columns):", df.shape)
print("Column Data Types:\\n", df.dtypes)
print(df.head(3))
df["Operating_Profit_USD"] = df["Monthly_Sales_USD"] - df["Operating_Cost_USD"]
df["Operating_Margin_Pct"] = (df["Operating_Profit_USD"] / df["Monthly_Sales_USD"]) * 100.0
print(df[["Store_ID", "Monthly_Sales_USD", "Operating_Margin_Pct"]].head(3))
# Select high-revenue stores in the West region
west_high_sales = df.loc[(df["Region_Name"] == "West") & (df["Monthly_Sales_USD"] >= 150000.0)]
# Impute missing satisfaction scores with median value
median_score = df["Customer_Satisfaction_Score"].median()
df["Customer_Satisfaction_Score"] = df["Customer_Satisfaction_Score"].fillna(median_score)
print("Median Satisfaction Score Imputed:", median_score)
Store_ID: Unique retail location code (e.g., STR-1001).Region_Name: Geographic division (East, West, North, South).Monthly_Sales_USD: Gross store revenue in U.S. Dollars.Operating_Cost_USD: Monthly operational store overhead in U.S. Dollars.Customer_Footfall_Count: Total monthly foot traffic count.Customer_Satisfaction_Score: Customer review rating (1.0 to 5.0 scale).session_1_3_wrangling.py. Verify that data/session_1_3_dataset.csv is present in Panel [1].import pandas as pd
# Ingest audited retail dataset
df = pd.read_csv("data/session_1_3_dataset.csv")
# Vectorized column creation
df["Operating_Profit_USD"] = df["Monthly_Sales_USD"] - df["Operating_Cost_USD"]
df["Operating_Margin_Pct"] = (df["Operating_Profit_USD"] / df["Monthly_Sales_USD"]) * 100.0
# Display executive summary
summary = df.describe()
print("Descriptive Financial Statistics:\\n", summary[["Monthly_Sales_USD", "Operating_Margin_Pct"]])
=(C2-D2)/C2*100 in cell E2 and dragging it down across rows. If someone accidentally types a number into cell E5, the formula is permanently corrupted.df["Operating_Margin_Pct"] applies the formula simultaneously to all records, preserving complete audit integrity.[4] (Terminal) using $ python session_1_3_wrangling.py. Confirm that summary statistics are printed accurately.session_1_3_practice.py, write a data filtering script that extracts all stores with Operating_Margin_Pct >= 30.0% and Customer_Satisfaction_Score >= 4.5..loc[] to select the qualified stores and output only Store_ID, Region_Name, and Operating_Margin_Pct.df["Monthly_Sale_USD"] instead of "Monthly_Sales_USD"). Observe the terminal KeyError, capture the traceback with Windows Key + Shift + S, paste it into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains DataFrame column key lookups.Operating_Margin_Pct descending, export the filtered table to data/top_performing_stores.csv, and verify return code 0.
| Schedule: Week 4 (115/10/04 - 115/10/10) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Boolean Masking: Filtering tabular rows using boolean condition vectors combined with bitwise logical operators (& for AND, | for OR, ~ for NOT).Split-Apply-Combine Pattern: The computational workflow of splitting data into operational groups, applying analytical functions, and combining results into an aggregated table.Multi-Metric Aggregation (.agg()): Computing different statistical metrics simultaneously across multiple columns (e.g., total expenses, average variance, maximum transaction size).Relational Merging: Joining two DataFrames based on common business keys (such as Cost_Center_Code), replacing error-prone spreadsheet VLOOKUP and XLOOKUP functions.Financial Variance Auditing: Programmatically comparing actual transactional expenses against authorized budget baselines to flag cost center overruns.&, |) because standard Python and/or operate on single scalar booleans, whereas Pandas evaluates element-wise boolean arrays.Division_Name, Fiscal_Quarter) to calculate sub-totals and unit economics without manually building pivot tables.how="inner", how="left") explicitly specifies match criteria and logs unmapped rows automatically.Variance_Flag when Actual_Expense > Budget_Expense * 1.05) to route financial discrepancies directly to corporate controllers.import pandas as pd
df = pd.read_csv("data/session_1_4_dataset.csv")
mask = (df["Division_Name"] == "Consumer") & (df["Actual_Expense_USD"] > df["Budget_Expense_USD"])
overrun_txns = df[mask]
print(f"Consumer Overrun Transactions Count: {len(overrun_txns)}")
div_summary = df.groupby("Division_Name").agg(
Total_Budget_USD=("Budget_Expense_USD", "sum"),
Total_Actual_USD=("Actual_Expense_USD", "sum"),
Transaction_Count=("Transaction_ID", "count")
)
div_summary["Variance_USD"] = div_summary["Total_Actual_USD"] - div_summary["Total_Budget_USD"]
div_summary["Variance_Pct"] = (div_summary["Variance_USD"] / div_summary["Total_Budget_USD"]) * 100.0
print(div_summary[["Total_Actual_USD", "Variance_USD", "Variance_Pct"]])
dept_info = pd.DataFrame({
"Cost_Center_Code": ["CC-101", "CC-202", "CC-303", "CC-404"],
"VP_Lead": ["Sarah Chen", "Marcus Vance", "Elena Rostova", "David Kim"]
})
merged_ledger = pd.merge(df, dept_info, on="Cost_Center_Code", how="left")
print(merged_ledger[["Transaction_ID", "Division_Name", "VP_Lead", "Actual_Expense_USD"]].head(3))
Transaction_ID: Unique transactional audit identifier (e.g., TXN-5001).Division_Name: Operating business unit (Cloud, Consumer, Enterprise, Logistics).Cost_Center_Code: Accounting cost center (CC-101, CC-202, CC-303, CC-404).Fiscal_Quarter: Financial reporting quarter (Q1, Q2, Q3, Q4).Budget_Expense_USD: Authorized spending budget in U.S. Dollars.Actual_Expense_USD: Realized expenditure in U.S. Dollars.Audit_Status: Internal audit classification (Verified, Variance_Flag).session_1_4_audit.py.import pandas as pd
df = pd.read_csv("data/session_1_4_dataset.csv")
# Compute transactional variance
df["Variance_USD"] = df["Actual_Expense_USD"] - df["Budget_Expense_USD"]
df["Variance_Pct"] = (df["Variance_USD"] / df["Budget_Expense_USD"]) * 100.0
# Group by Division and Quarter
quarterly_audit = df.groupby(["Division_Name", "Fiscal_Quarter"]).agg(
Total_Actual=("Actual_Expense_USD", "sum"),
Total_Variance=("Variance_USD", "sum"),
Mean_Variance_Pct=("Variance_Pct", "mean")
)
print("Quarterly Division Audit Summary:\\n", quarterly_audit)
Total_Variance values, enabling executive leadership to pinpoint quarterly cost overruns immediately.[4] (Terminal) using $ python session_1_4_audit.py and confirm clean execution.session_1_4_practice.py, write an automated compliance auditing script that flags all cost centers where annual actual spending exceeded authorized budgets by more than 3.0%.Cost_Center_Code, sum budget and actual expenses, and compute the annual variance percentage.dept_info using mismatched column names (e.g., left_on="CostCenter" without defining right_on). Observe the KeyError, capture the terminal traceback with Windows Key + Shift + S, paste it into Panel [3] (AI Agent Chat) with Ctrl + V, and review the AI’s explanation of join keys.Module 2 shifts focus from internal corporate records to external market intelligence and visual storytelling. Students learn to extract public competitor price data using web scrapers, construct publication-grade business charts, and present audited exploratory findings during the midterm milestone.

| Schedule: Week 5 (115/10/11 - 115/10/17) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
HyperText Transfer Protocol (HTTP GET): The standard communication protocol used by web browsers and Python scripts to request public web page markup from external web servers.Document Object Model (DOM Tree): The hierarchical tree structure representing an HTML web page, where parent tags contain nested child elements, classes, and text attributes.CSS Selector Targeting (.select() / .find()): Directing Python to extract specific information from a web page by matching tag names (<table>), CSS classes (.price-tag), or element identifiers (#product-grid).Beautiful Soup Parser: A Python library (bs4) that navigates, searches, and modifies the Document Object Model tree to extract clean textual data.Ethical Scraping Protocols: Operating web crawlers responsibly by respecting server rate limits, adding descriptive User-Agent headers, and complying with robots.txt exclusion rules.<div class="product-card">) housing title headings, price tags, and inventory spans.time.sleep(2)) to avoid overwhelming public servers, preventing IP blocking and maintaining compliance with commercial terms of service.requests library:
import requests
from bs4 import BeautifulSoup
# Simulated public e-commerce pricing table
html_markup = """
<div class="catalog">
<div class="product" data-sku="SKU-801">
<h3 class="name">Enterprise Router</h3>
<span class="price">$299.99</span>
<span class="stock">In Stock (45 units)</span>
</div>
<div class="product" data-sku="SKU-802">
<h3 class="name">Office Desk Chair</h3>
<span class="price">$49.50</span>
<span class="stock">Low Stock (8 units)</span>
</div>
</div>
"""
soup = BeautifulSoup(html_markup, "html.parser")
print("Document Title Extracted:", soup.find("h3").text)
products = []
for item in soup.select(".product"):
sku = item["data-sku"]
name = item.select_one(".name").text.strip()
raw_price = item.select_one(".price").text.strip()
price_usd = float(raw_price.replace("$", ""))
products.append({"sku": sku, "name": name, "price_usd": price_usd})
print("Parsed Products:", products)
import pandas as pd
catalog_df = pd.DataFrame(products)
print(catalog_df.describe())
Product_SKU: Product inventory identifier (e.g., SKU-801).Competitor_Name: Competitor enterprise (AlphaRetail, BetaMart, GammaGlobal).Category_Name: Commercial merchandise category (Electronics, Office Supplies, Hardware, Appliances).List_Price_USD: Extracted competitor catalog price in U.S. Dollars.Promotion_Discount_Pct: Advertised promotional markdown percentage.Stock_Availability_Units: Available warehouse stock units.session_2_1_scraper.py.import pandas as pd
from bs4 import BeautifulSoup
# Load audited competitor dataset
df = pd.read_csv("data/session_2_1_dataset.csv")
# Compute effective selling price after discount
df["Effective_Price_USD"] = df["List_Price_USD"] * (1.0 - (df["Promotion_Discount_Pct"] / 100.0))
# Benchmark competitor pricing by category
category_benchmark = df.groupby(["Category_Name", "Competitor_Name"]).agg(
Avg_List_Price=("List_Price_USD", "mean"),
Avg_Effective_Price=("Effective_Price_USD", "mean"),
Total_Stock=("Stock_Availability_Units", "sum")
)
print("Competitor Category Pricing Benchmark:\\n", category_benchmark)
[4] (Terminal) using $ python session_2_1_scraper.py. Confirm that the pricing benchmark prints with zero syntax errors.session_2_1_practice.py, write an HTML scraping parser that extracts product titles, raw prices, and inventory counts from an HTML snippet containing missing tags.<span class="stock"> tag. Use if tag is not None checks to prevent runtime crashes..text on a non-existent element (e.g., soup.find("span", class_="discount").text). Observe the terminal AttributeError: 'NoneType' object has no attribute 'text', capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains safe parsing techniques..get_text(strip=True) and safe fallback logic, export the clean competitor intelligence DataFrame to data/competitor_price_audit.csv, and verify return code 0.
| Schedule: Week 6 (115/10/18 - 115/10/24) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Visual Encoding Hierarchy: Mapping quantitative commercial data to spatial coordinates, lengths, and colors following cognitive visual perception principles.Figure & Axes Architecture: The object-oriented Matplotlib canvas model where a top-level Figure container manages one or more individual Axes plotting subplots.Time-Series Revenue Curves: Continuous line plots visualizing revenue, marketing spend, and customer acquisition costs across fiscal months.Categorical Distribution Plots: Clean bar plots and box plots created with Seaborn to compare performance metrics across corporate business units.Correlation Heatmap: A color-encoded matrix displaying pairwise correlation coefficients between multiple operational metrics to uncover commercial relationships.plt.plot()) in favor of explicit object-oriented architecture (fig, ax = plt.subplots()). This enables precise control over tick marks, dual y-axes, titles, and export resolutions.#991B1B and Slate #475569) with clear high-contrast typography, ensuring dashboards remain legible when printed in grayscale.import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("data/session_2_2_dataset.csv")
fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.plot(df["Month_Name"], df["Organic_Revenue_USD_M"], color="#991B1B", marker="o", label="Revenue (USD M)")
ax1.set_ylabel("Organic Revenue (USD M)", color="#991B1B")
ax2 = ax1.twinx()
ax2.plot(df["Month_Name"], df["Customer_Acquisition_Cost_USD"], color="#475569", linestyle="--", label="CAC (USD)")
ax2.set_ylabel("Customer Acquisition Cost (USD)", color="#475569")
plt.title("Revenue Growth vs. Acquisition Cost Efficiency")
plt.savefig("data/dual_axis_trend.png", dpi=150, bbox_inches="tight")
import seaborn as sns
fig, ax = plt.subplots(figsize=(8, 4))
sns.barplot(data=df, x="Month_Name", y="Paid_Marketing_Spend_USD_M", color="#991B1B", ax=ax)
ax.set_title("Paid Marketing Budget Allocation by Month")
ax.set_ylabel("Marketing Spend (USD M)")
plt.savefig("data/marketing_spend_bar.png", dpi=150, bbox_inches="tight")
numeric_cols = ["Organic_Revenue_USD_M", "Paid_Marketing_Spend_USD_M", "Customer_Acquisition_Cost_USD", "Net_Promoter_Score"]
corr_matrix = df[numeric_cols].corr()
fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(corr_matrix, annot=True, cmap="Reds", fmt=".2f", ax=ax)
ax.set_title("Commercial KPI Correlation Matrix")
plt.savefig("data/kpi_correlation_heatmap.png", dpi=150, bbox_inches="tight")
Month_Index: Sequential fiscal month index (1 to 12).Month_Name: Three-letter calendar month identifier (Jan through Dec).Organic_Revenue_USD_M: Organic sales revenue in millions of U.S. Dollars.Paid_Marketing_Spend_USD_M: Paid marketing expenditures in millions of U.S. Dollars.Customer_Acquisition_Cost_USD: Blended acquisition cost per customer in U.S. Dollars.Net_Promoter_Score: Customer satisfaction index (1 to 100 scale).session_2_2_dashboard.py.import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("data/session_2_2_dataset.csv")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
# Panel 1: Revenue Curve
ax1.plot(df["Month_Name"], df["Organic_Revenue_USD_M"], color="#991B1B", marker="s", linewidth=2)
ax1.set_title("Monthly Revenue Trajectory (FY2024)", fontsize=14, fontweight="bold")
ax1.set_ylabel("Revenue (USD M)")
ax1.grid(True, linestyle=":", alpha=0.6)
# Panel 2: NPS vs CAC Relationship
ax2.scatter(df["Customer_Acquisition_Cost_USD"], df["Net_Promoter_Score"], color="#1E293B", s=80)
ax2.set_title("Customer Loyalty (NPS) vs. Acquisition Cost", fontsize=14, fontweight="bold")
ax2.set_xlabel("CAC (USD)")
ax2.set_ylabel("Net Promoter Score")
ax2.grid(True, linestyle=":", alpha=0.6)
plt.tight_layout()
plt.savefig("data/executive_dashboard_2panel.png", dpi=200)
print("Dashboard saved: data/executive_dashboard_2panel.png")
data/executive_dashboard_2panel.png via Panel [1] (File Explorer) and verify that tick labels, legends, and gridlines render crisply without overlapping text.[4] (Terminal) using $ python session_2_2_dashboard.py and confirm clean execution.session_2_2_practice.py, construct a 4-panel (2x2) executive analytics dashboard displaying revenue trends, marketing spend distributions, CAC efficiency curves, and the correlation heatmap.fig, axes = plt.subplots(2, 2, figsize=(16, 10)) and populate each subplot with distinct commercial metrics.axes[2].plot(...) instead of axes[1, 0]). Observe the terminal IndexError: index 2 is out of bounds for axis 0 with size 2, capture the message with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains 2D array indexing.plt.tight_layout(), export the 4-panel dashboard to data/boardroom_analytics_master.png at 300 DPI, and verify return code 0.
| Schedule: Week 7 (115/10/25 - 115/10/31) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Analytical Hypothesis Framing: Translating ambiguous managerial problems into falsifiable, testable quantitative statements expressed in executable code.Exploratory Data Analysis (EDA): Systematic statistical inspection of dataset distributions, correlations, and anomalies to inform analytical design.Data Hygiene Audit: Automated scanning for missing records, duplicate primary keys, unexpected negative numbers, and data type inconsistencies.Baseline Metric Architecture: Calculating baseline benchmarks (e.g., historical contract renewal rate) against which analytical improvements are measured.Technical Debt Profiling: Auditing student codebase for modular function structure, descriptive variable naming, and automated exception handling.data/, scripts/, output/) with automated logging, ensuring any auditor can replicate findings in seconds.import pandas as pd
df = pd.read_csv("data/session_2_3_dataset.csv")
def audit_dataset_hygiene(data):
return {
"Total_Rows": len(data),
"Missing_Values_Total": int(data.isnull().sum().sum()),
"Duplicate_Accounts": int(data["Account_ID"].duplicated().sum()),
"Min_SLA_Compliance": float(data["SLA_Compliance_Pct"].min()),
"Total_Contract_Value_USD": float(data["Contract_Value_USD"].sum())
}
audit_report = audit_dataset_hygiene(df)
print("Data Hygiene Audit Report:", audit_report)
sla_breaches = df[df["SLA_Compliance_Pct"] < 95.0]
print(f"Accounts Breaching SLA (<95%): {len(sla_breaches)}")
print(sla_breaches[["Account_ID", "Enterprise_Client", "SLA_Compliance_Pct", "Client_Retention_Risk"]])
risk_summary = df.groupby("Client_Retention_Risk").agg(
Total_Contract_Value_USD=("Contract_Value_USD", "sum"),
Account_Count=("Account_ID", "count"),
Mean_Billing_Discrepancies=("Billing_Discrepancy_Count", "mean")
)
print("Client Retention Financial Exposure Summary:\\n", risk_summary)
Account_ID: Unique client enterprise identifier (e.g., ACC-301).Enterprise_Client: Corporate enterprise name (Titan Tech, Beacon Health, Vanguard Retail, etc.).Contract_Value_USD: Annualized contract value in U.S. Dollars.SLA_Compliance_Pct: Audited Service Level Agreement uptime percentage.Billing_Discrepancy_Count: Total billing disputes logged during the contract period.Client_Retention_Risk: Qualitative account health classification (Low, Medium, High).session_2_3_formulation.py.import pandas as pd
df = pd.read_csv("data/session_2_3_dataset.csv")
# Hypothesis 1: Billing discrepancies drive high retention risk
h1_test = df.groupby("Client_Retention_Risk")["Billing_Discrepancy_Count"].mean()
print("Hypothesis 1 (Billing Disputes vs. Risk Tier):\\n", h1_test)
# Hypothesis 2: Low SLA compliance triggers customer disputes
h2_correlation = df["SLA_Compliance_Pct"].corr(df["Billing_Discrepancy_Count"])
print(f"\\nHypothesis 2 Correlation (SLA vs. Billing Disputes): {h2_correlation:.3f}")
# Output executive risk profile
high_risk_exposure = df[df["Client_Retention_Risk"] == "High"]["Contract_Value_USD"].sum()
print(f"\\nTotal Enterprise Revenue at Immediate Risk: ${high_risk_exposure:,.2f}")
[4] (Terminal) using $ python session_2_3_formulation.py and verify clean execution.session_2_3_practice.py, develop a data profiling module that validates inbound CSV data against strict corporate data contracts.assert df["SLA_Compliance_Pct"].between(0, 100).all(), assert (df["Contract_Value_USD"] > 0).all().SLA_Compliance_Pct = 105.0). Observe the terminal AssertionError, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains programmatic data quality guardrails.try-except block, log validation errors to data/audit_exceptions.log, output an executive summary of compliant records, and verify return code 0.
| Schedule: Week 8 (115/11/01 - 115/11/07) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Reproducible Data Pipeline: A self-contained, end-to-end Python script execution sequence that reliably transforms raw data into verified executive reports with zero manual intervention.Executive Code Defense: Articulating the business rationale, methodology, and computational assumptions behind an analytics codebase to executive decision-makers.Exploratory Data Findings: Structuring quantitative insights into concise, actionable findings linked directly to operating cash flows and margin expansion.Cross-Functional Technical Translation: The ability to explain computational trade-offs, data limitations, and algorithmic results to non-technical stakeholders.Peer Review Audit Protocol: Performing structured code inspections of classmate scripts to verify PEP 8 compliance, error handling, and numerical reproducibility.import time
import pandas as pd
start_time = time.time()
df = pd.read_csv("data/session_2_4_dataset.csv")
# Compute platform take rate and cash flows
df["Recognized_Revenue_USD_M"] = df["Gross_Merchandise_Value_USD_M"] * (df["Platform_Take_Rate_Pct"] / 100.0)
df["Cash_Flow_Conversion_Pct"] = (df["Operating_Cash_Flow_USD_M"] / df["Recognized_Revenue_USD_M"]) * 100.0
elapsed_time = time.time() - start_time
print(f"Pipeline Executed in {elapsed_time:.4f} seconds | Processed {len(df)} records.")
segment_audit = df.groupby("Market_Segment").agg(
Total_GMV_USD_M=("Gross_Merchandise_Value_USD_M", "sum"),
Total_Revenue_USD_M=("Recognized_Revenue_USD_M", "sum"),
Total_Operating_Cash_Flow_USD_M=("Operating_Cash_Flow_USD_M", "sum"),
Mean_Take_Rate=("Platform_Take_Rate_Pct", "mean")
)
print("Geographic Cash Flow Conversion Audit:\\n", segment_audit)
import hashlib
summary_str = segment_audit.to_string()
audit_hash = hashlib.sha256(summary_str.encode("utf-8")).hexdigest()[:12]
segment_audit.to_csv("data/midterm_defense_summary.csv")
print(f"Audited Executive Summary Exported. Verification Hash: {audit_hash}")
Quarter_Code: Fiscal reporting quarter (2024-Q1 through 2024-Q4).Market_Segment: Geographic platform division (North_America, Europe, Asia_Pacific).Gross_Merchandise_Value_USD_M: Total merchandise transacted in millions of U.S. Dollars.Platform_Take_Rate_Pct: Enterprise monetization take rate percentage.Operating_Cash_Flow_USD_M: Operating cash flow generated in millions of U.S. Dollars.session_2_4_defense.py.import pandas as pd
df = pd.read_csv("data/session_2_4_dataset.csv")
df["Net_Revenue_USD_M"] = df["Gross_Merchandise_Value_USD_M"] * (df["Platform_Take_Rate_Pct"] / 100.0)
df["Conversion_Efficiency_Pct"] = (df["Operating_Cash_Flow_USD_M"] / df["Net_Revenue_USD_M"]) * 100.0
# Executive quarterly comparison
quarterly_review = df.groupby("Quarter_Code").agg(
Total_GMV=("Gross_Merchandise_Value_USD_M", "sum"),
Total_Revenue=("Net_Revenue_USD_M", "sum"),
Total_Cash_Flow=("Operating_Cash_Flow_USD_M", "sum")
)
print("Executive Defense Performance Trajectory:\\n", quarterly_review)
[4] (Terminal) using $ python session_2_4_defense.py and confirm return code 0.session_2_4_practice.py, conduct a formal peer review audit on an external dataset. Write a function calculating cash flow conversion variance and flag quarters where conversion dropped below 90%."Total GMV: " + df["Gross_Merchandise_Value_USD_M"].sum()). Observe the TypeError: can only concatenate str (not "numpy.float64") to str, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains f-string interpolation.data/midterm_final_signoff.csv, and verify return code 0.Module 3 introduces managerial artificial intelligence and machine learning frameworks. Students explore how machine learning models generate enterprise value, prepare data through feature engineering, build predictive models using Scikit-Learn, and evaluate model trade-offs between precision, recall, and financial cost.

| Schedule: Week 9 (115/11/08 - 115/11/14) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Artificial Intelligence (AI): Broad computational systems capable of performing tasks that typically require human cognition, including perception, language understanding, and automated decision-making.Machine Learning (ML): A subfield of artificial intelligence where statistical models learn patterns and relationships directly from data rather than following rigid, hand-coded rules.Deep Learning (DL): A subset of machine learning based on multi-layered artificial neural networks, specialized in unstructured data processing (images, audio, natural language).Rule-Based vs. Statistical Systems: Transitioning from deterministic if-then heuristics to probabilistic algorithms that generalize across noisy, unseen real-world data.Enterprise Return on Investment (ROI Calculation): The quantitative evaluation of machine learning initiatives comparing development and compute costs against projected labor savings and risk reduction.import pandas as pd
df = pd.read_csv("data/session_3_1_dataset.csv")
df["Net_Annual_Savings_USD"] = df["Projected_Cost_Savings_USD"] - (df["Implementation_Cost_USD"] * 0.15) # 15% maintenance
df["Calculated_Payback_Months"] = (df["Implementation_Cost_USD"] / df["Net_Annual_Savings_USD"]) * 12.0
df["3Year_Net_ROI_Pct"] = (((df["Net_Annual_Savings_USD"] * 3.0) - df["Implementation_Cost_USD"]) / df["Implementation_Cost_USD"]) * 100.0
print(df[["Project_ID", "Department_Name", "Calculated_Payback_Months", "3Year_Net_ROI_Pct"]].head(3))
# Rule-Based Heuristic
def rule_based_flag(spend):
return "Flagged" if spend > 250000.0 else "Approved"
# Probabilistic Scoring Equivalence
def statistical_score(spend, risk_score):
prob = (spend / 500000.0) * 0.5 + (risk_score / 100.0) * 0.5
return "High_Risk" if prob >= 0.65 else "Low_Risk"
print("Rule-Based Evaluation:", rule_based_flag(260000.0))
print("Probabilistic Evaluation:", statistical_score(260000.0, 75))
high_priority = df[(df["Calculated_Payback_Months"] <= 6.0) & (df["Annual_Labor_Hours_Saved_Count"] >= 4000)]
print(f"High Priority AI Projects Count: {len(high_priority)}")
print(high_priority[["Project_ID", "Department_Name", "Calculated_Payback_Months"]])
Project_ID: Capital allocation tracking code (e.g., AI-PRJ-101).Department_Name: Enterprise sponsor division (Supply Chain, Customer Service, Marketing, Finance, Fraud Operations).Implementation_Cost_USD: Initial capital expenditure in U.S. Dollars.Annual_Labor_Hours_Saved_Count: Verified operational hours recovered per fiscal year.Projected_Cost_Savings_USD: Annualized financial savings in U.S. Dollars.Payback_Period_Months_Count: Projected break-even timeline in months.session_3_1_capital.py.import pandas as pd
df = pd.read_csv("data/session_3_1_dataset.csv")
# Financial evaluation calculations
df["Net_Annual_Benefit_USD"] = df["Projected_Cost_Savings_USD"] - (df["Implementation_Cost_USD"] * 0.10)
df["3Yr_ROI_Pct"] = (((df["Net_Annual_Benefit_USD"] * 3.0) - df["Implementation_Cost_USD"]) / df["Implementation_Cost_USD"]) * 100.0
ranked_portfolio = df.sort_values(by="3Yr_ROI_Pct", ascending=False)
print("Ranked Enterprise AI Portfolio by 3-Year ROI:\\n", ranked_portfolio[["Project_ID", "Department_Name", "3Yr_ROI_Pct"]])
[4] (Terminal) using $ python session_3_1_capital.py and verify clean execution.session_3_1_practice.py, develop an automated capital budgeting algorithm that allocates a fixed $500,000 corporate AI fund to maximize total annual labor hours saved.Annual_Labor_Hours_Saved_Count / Implementation_Cost_USD), iteratively fund projects until the $500,000 cap is reached, and calculate total hours saved.Implementation_Cost_USD = 0.0 into the efficiency formula. Observe the terminal ZeroDivisionError: float division by zero, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains safe division guardrails.max(cost, 1.0), print a formatted 3-bullet capital allocation decision memo for the Chief Financial Officer (CFO), and verify return code 0.
| Schedule: Week 10 (115/11/15 - 115/11/21) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Feature Matrix & Target Vector (X & y): The standardized machine learning mathematical representation where X is a two-dimensional matrix of input attributes and y is a one-dimensional vector of ground-truth outcomes.One-Hot Categorical Encoding: Transforming text categories (e.g., Bachelor, Master, Doctorate) into binary numerical indicator columns (0 or 1) for machine learning models.Feature Standardization (StandardScaler): Rescaling continuous numeric features to have a mean of 0 and a standard deviation of 1, preventing high-magnitude columns from dominating distance calculations.Missing Value Imputation (SimpleImputer): Statistically replacing missing data with median or mean values to prevent model training crashes.Train-Test Partitioning: Dividing historical data into an 80% training set to fit the model and a 20% test set held out to evaluate true generalization performance.Master = 2 * Bachelor). Use One-Hot Encoding (pd.get_dummies or OneHotEncoder) with drop_first=True to prevent multicollinearity.Annual_Income ranges from $50,000 to $200,000 while Credit_Utilization ranges from 0.1 to 0.9, distance-based models (such as K-Nearest Neighbors, Support Vector Machines, and regularized regressions) will prioritize income entirely. Standardization ensures fair feature weighting.X_train, and transform X_test using the learned training parameters.import pandas as pd
df = pd.read_csv("data/session_3_2_dataset.csv")
X_raw = df.drop(columns=["Client_ID", "Defaulted_Binary"])
y = df["Defaulted_Binary"]
print("Feature Matrix Shape:", X_raw.shape)
print("Target Vector Distribution:\\n", y.value_counts())
X_encoded = pd.get_dummies(X_raw, columns=["Education_Tier"], drop_first=True, dtype=float)
print("Encoded Feature Columns:\\n", X_encoded.columns.tolist())
print(X_encoded.head(2))
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Split into 80% Train and 20% Test sets
X_train, X_test, y_train, y_test = train_test_split(X_encoded, y, test_size=0.25, random_state=42, stratify=y)
# Fit scaler strictly on X_train
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(f"X_train scaled shape: {X_train_scaled.shape} | X_test scaled shape: {X_test_scaled.shape}")
Client_ID: Unique credit applicant code (e.g., CLI-701).Age_Years_Count: Applicant age in years.Annual_Income_USD: Verified annual income in U.S. Dollars.Credit_Utilization_Pct: Credit card revolving balance utilization percentage.Education_Tier: Highest level of education (Bachelor, Master, Doctorate).Defaulted_Binary: Ground truth loan default outcome (0 = Repaid, 1 = Defaulted).session_3_2_preprocessing.py.import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("data/session_3_2_dataset.csv")
# Feature selection and encoding
X = pd.get_dummies(df.drop(columns=["Client_ID", "Defaulted_Binary"]), drop_first=True, dtype=float)
y = df["Defaulted_Binary"]
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# Standardization
scaler = StandardScaler()
X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train), columns=X.columns)
X_test_scaled = pd.DataFrame(scaler.transform(X_test), columns=X.columns)
print("Training Feature Means (Standardized):\\n", X_train_scaled.mean().round(2))
print("Training Feature Std (Standardized):\\n", X_train_scaled.std().round(2))
X_train_scaled have a mean of approximately 0.00 and standard deviation of 1.00.[4] (Terminal) using $ python session_3_2_preprocessing.py and verify clean execution.session_3_2_practice.py, construct an automated feature pipeline that engineers a new interaction feature (Debt_to_Income_Ratio = (Credit_Utilization_Pct * 1000) / Annual_Income_USD) before scaling.Debt_to_Income_Ratio and inspect its correlation with the default target.scaler.fit_transform(X_test) instead of scaler.transform(X_test). Run the script, observe how test set distribution is artificially altered, capture the code with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains data leakage hazards.transform(X_test), export preprocessed training matrices to data/preprocessed_credit_features.csv, and verify return code 0.
| Schedule: Week 11 (115/11/22 - 115/11/28) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Unified Estimator API: The standard three-stage Scikit-Learn interface: instantiate model, fit on training data (.fit()), predict on new data (.predict()), and evaluate accuracy (.score()).Linear Regression: A fundamental supervised regression algorithm that models the linear relationship between continuous independent variables and a target business metric.Logistic Regression: A foundational supervised classification algorithm that models the probability of a binary categorical event using the logistic sigmoid function.K-Fold Cross-Validation: Splitting training data into K subsets to iteratively train and validate the model K times, providing an unbiased estimate of generalization performance.Root Mean Squared Error (RMSE): A standard regression performance metric that penalizes large forecasting errors by taking the square root of mean squared residuals..fit() and .predict() unlocks hundreds of advanced machine learning algorithms.model.coef_) indicate the marginal financial return of adding square footage or reducing distance to commercial business districts.[0, 1], logistic regression squashes predictions into calibrated probabilities between 0.0 and 1.0, ideal for loan default or churn risk scoring.import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = pd.read_csv("data/session_3_3_dataset.csv")
X = df[["Square_Feet_Units", "Bedrooms_Count", "Distance_To_CBD_Miles", "Local_Tax_Rate_Pct"]]
y = df["Sale_Price_USD"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print("Model Intercept:", round(model.intercept_, 2))
print("Model Coefficients (Feature Weights):", dict(zip(X.columns, model.coef_.round(2))))
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
y_pred = model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print(f"Test Set RMSE: ${rmse:,.2f}")
print(f"Test Set R-Squared (Variance Explained): {r2:.4f}")
from sklearn.model_selection import cross_val_score
cv_scores = cross_val_score(model, X, y, cv=5, scoring="r2")
print("5-Fold Cross-Validation R-Squared Scores:", cv_scores.round(3))
print(f"Mean Cross-Validated R-Squared: {cv_scores.mean():.3f} (+/- {cv_scores.std():.3f})")
Property_ID: Unique property transaction code (e.g., PROP-401).Square_Feet_Units: Usable interior floor area in square feet.Bedrooms_Count: Total number of partitioned office suites or bedrooms.Distance_To_CBD_Miles: Distance to Central Business District in miles.Local_Tax_Rate_Pct: Municipal commercial property tax percentage.Sale_Price_USD: Realized commercial transaction price in U.S. Dollars.session_3_3_regression.py.import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
df = pd.read_csv("data/session_3_3_dataset.csv")
features = ["Square_Feet_Units", "Bedrooms_Count", "Distance_To_CBD_Miles"]
X = df[features]
y = df["Sale_Price_USD"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
reg = LinearRegression()
reg.fit(X_train, y_train)
y_pred = reg.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print("Valuation Engine Coefficients:\\n", dict(zip(features, reg.coef_.round(2))))
print(f"Validation RMSE: ${rmse:,.2f} | R-Squared: {r2:.3f}")
[4] (Terminal) using $ python session_3_3_regression.py and confirm clean execution.session_3_3_practice.py, build a price valuation pipeline that evaluates individual predictions and computes percentage absolute forecasting error for each property.Mean_Absolute_Percentage_Error = mean(abs(y_true - y_pred) / y_true) * 100.reg.predict([1500, 3, 5.0]) instead of [[1500, 3, 5.0]]). Observe the terminal ValueError: Expected 2D array, got 1D array instead, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains 2D array reshaping..reshape(1, -1), print a clean formatted comparison table of actual vs predicted prices, and verify return code 0.
| Schedule: Week 12 (115/11/29 - 115/12/05) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Supervised vs. Unsupervised Learning: Supervised learning trains on labeled historical targets (y), whereas unsupervised learning identifies natural groupings and structural patterns in unlabeled data (X).Confusion Matrix: A 2x2 contingency table tabulating classification outcomes into True Positives (TP), False Positives (FP), True Negatives (TN), and False Negatives (FN).Precision & Recall Trade-Off: Precision measures how many flagged cases were truly positive, while Recall measures what percentage of all actual positives were caught.Receiver Operating Characteristic (ROC-AUC): A graphical plot illustrating the diagnostic ability of a binary classifier across all classification thresholds, summarized by the Area Under the Curve (AUC).K-Means Clustering: An unsupervised algorithm that partitions commercial customer accounts into K distinct clusters by iteratively minimizing the sum of squared distances to cluster centroids.$4,000 fraudulent transaction) costs the bank $4,000. A False Positive (sending an automated verification SMS) costs $0.05. Models must be optimized for financial cost rather than naive accuracy.import pandas as pd
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
df = pd.read_csv("data/session_3_4_dataset.csv")
y_true = df["Actual_Fraud_Binary"]
# Simulated model probability predictions
y_pred = (df["Cardholder_Risk_Score"] >= 70).astype(int)
cm = confusion_matrix(y_true, y_pred)
prec = precision_score(y_true, y_pred)
rec = recall_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred)
print("Confusion Matrix (TN, FP / FN, TP):\\n", cm)
print(f"Precision: {prec:.3f} | Recall: {rec:.3f} | F1-Score: {f1:.3f}")
from sklearn.metrics import roc_auc_score
risk_prob = df["Cardholder_Risk_Score"] / 100.0
auc_score = roc_auc_score(y_true, risk_prob)
print(f"Model Diagnostic ROC-AUC Score: {auc_score:.4f}")
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
features = df[["Transaction_Amount_USD", "Cardholder_Risk_Score"]]
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features)
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
df["Cluster_ID"] = kmeans.fit_predict(scaled_features)
cluster_profiles = df.groupby("Cluster_ID")[["Transaction_Amount_USD", "Cardholder_Risk_Score"]].mean()
print("Unsupervised Cluster Archetype Profiles:\\n", cluster_profiles)
Transaction_ID: Unique financial transaction identifier (e.g., F-TXN-8001).Transaction_Amount_USD: Total transacted amount in U.S. Dollars.Foreign_IP_Flag: Binary indicator of international network origin (0 = Domestic, 1 = Foreign).Failed_Login_Attempts_Count: Prior failed security authentication attempts.Cardholder_Risk_Score: Internal behavioral risk index (1 to 100 scale).Actual_Fraud_Binary: Audited ground truth fraud confirmation (0 = Legitimate, 1 = Confirmed Fraud).session_3_4_evaluation.py.import pandas as pd
from sklearn.metrics import confusion_matrix, precision_score, recall_score
df = pd.read_csv("data/session_3_4_dataset.csv")
y_true = df["Actual_Fraud_Binary"]
y_pred = (df["Cardholder_Risk_Score"] >= 70).astype(int)
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
prec = precision_score(y_true, y_pred)
rec = recall_score(y_true, y_pred)
# Financial Cost Modeling: FP cost = $5 (investigation), FN cost = $1,500 (stolen funds)
total_financial_loss = (fp * 5.0) + (fn * 1500.0)
print(f"Classification Metrics: Precision={prec:.2f}, Recall={rec:.2f}")
print(f"Outcome Counts: TP={tp}, TN={tn}, FP={fp}, FN={fn}")
print(f"Total Operational Financial Loss from Errors: ${total_financial_loss:,.2f}")
[4] (Terminal) using $ python session_3_4_evaluation.py and confirm clean execution.session_3_4_practice.py, write a threshold tuning script that iterates classification thresholds from 50 to 90 in increments of 5, identifying the exact threshold that minimizes total financial loss.confusion_matrix(y_true, y_prob). Observe the terminal ValueError: Classification metrics can't handle a mix of binary and continuous targets, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains threshold binarization (.astype(int)).data/fraud_threshold_optimization.csv, and verify return code 0.Module 4 focuses on executive deployment, decision integration, and risk management. Students examine how machine learning predictions translate into operational policies, explore dynamic pricing and churn mitigation algorithms, and evaluate ethical considerations including algorithmic bias, data privacy, and artificial intelligence governance.

| Schedule: Week 13 (115/12/06 - 115/12/12) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
End-to-End Decision Pipeline: A unified software pipeline connecting data ingestion, automated preprocessing, model inference, and operational decision triggers into a single automated system.Batch vs. Real-Time Inference: Batch inference scores millions of records offline on scheduled schedules (e.g., nightly credit updates), while real-time inference scores individual transactions in milliseconds via APIs.Model Serialization (joblib): Saving trained Scikit-Learn model weights and preprocessing transformers to disk (.joblib format) to load into production systems without retraining.Data Drift & Model Degradation: The real-world phenomenon where macroeconomic shifts or consumer behavior changes degrade model accuracy over time, requiring continuous monitoring.Production Health Monitoring: Programmatically tracking execution latency, throughput volumes, and prediction distributions to detect pipeline failures.joblib allows developers to deploy pre-trained pipelines directly into production execution environments, separating heavy training compute from lightweight inference.import joblib
from sklearn.linear_model import LogisticRegression
import numpy as np
# Train a baseline model
X_sample = np.array([[10, 0.2], [50, 0.8], [20, 0.3], [70, 0.9]])
y_sample = np.array([0, 1, 0, 1])
clf = LogisticRegression().fit(X_sample, y_sample)
# Serialize model to disk
joblib.dump(clf, "data/production_fraud_model.joblib")
# Reload model in production context
deployed_model = joblib.load("data/production_fraud_model.joblib")
new_transaction = np.array([[35, 0.6]])
prediction = deployed_model.predict(new_transaction)
print("Production Model Loaded. New Transaction Prediction:", prediction[0])
import pandas as pd
df = pd.read_csv("data/session_4_1_dataset.csv")
def run_batch_inference(data_batch, model):
# Simulated batch score
data_batch["Inference_Confidence"] = data_batch["Model_Accuracy_Score"] * 0.98
data_batch["Action_Required"] = data_batch["Inference_Confidence"].apply(
lambda x: "Review" if x < 0.94 else "Auto_Approve"
)
return data_batch
scored_batch = run_batch_inference(df, deployed_model)
print(scored_batch[["Batch_Run_ID", "Pipeline_Stage", "Action_Required"]].head(3))
latency_threshold_ms = 500
latency_alerts = df[df["Latency_Milliseconds"] > latency_threshold_ms]
print(f"Pipeline Stages Exceeding Latency Threshold ({latency_threshold_ms}ms): {len(latency_alerts)}")
Batch_Run_ID: Production execution run code (e.g., RUN-2024-10).Pipeline_Stage: Operational workflow stage (Ingestion, Validation, Inference, Action_Trigger).Record_Throughput_Count: Total records processed during the execution stage.Latency_Milliseconds: Total stage latency in milliseconds.Model_Accuracy_Score: Real-time model accuracy validation metric.Pipeline_Health_Status: Automated operational health flag (Normal, Alert).session_4_1_production.py.import pandas as pd
import time
start_timer = time.time()
df = pd.read_csv("data/session_4_1_dataset.csv")
# Apply automated decision trigger thresholds
df["Throughput_Efficiency"] = df["Record_Throughput_Count"] / (df["Latency_Milliseconds"] / 1000.0)
df["Executive_Status"] = df.apply(
lambda row: "Escalate" if row["Latency_Milliseconds"] > 600 or row["Model_Accuracy_Score"] < 0.94 else "Optimal",
axis=1
)
runtime = time.time() - start_timer
print(f"End-to-End Decision System Evaluated in {runtime:.4f} seconds.")
print("Production Execution Status:\\n", df[["Batch_Run_ID", "Pipeline_Stage", "Throughput_Efficiency", "Executive_Status"]].head(4))
[4] (Terminal) using $ python session_4_1_production.py and confirm clean execution.session_4_1_practice.py, construct a production monitoring module that evaluates data drift between baseline training distributions and live incoming batch distributions.joblib.load("models/missing_weights.joblib")). Observe the terminal FileNotFoundError, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains robust file path handling with os.path.exists().os.path.exists() check with an automated fallback, export production monitoring metrics to data/production_pipeline_audit.csv, and verify return code 0.
| Schedule: Week 14 (115/12/13 - 115/12/19) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Customer Churn Probability: The continuous probability output (predict_proba) generated by a classification model estimating the likelihood of a subscriber canceling services.Customer Lifetime Value (CLV): The present value of future net profit margins generated by a customer relationship across their projected relationship tenure.Revenue At Risk: Quantifying the total annual revenue at risk by multiplying individual churn probabilities by annualized subscriber contract values.Targeted Retention Incentives: Programmatically matching customer churn tiers to specific cost-effective intervention strategies (e.g., proactive customer support outreach vs. discount incentives).Retention Campaign Return on Investment: The financial equation comparing saved customer revenue against the operational cost of retention interventions.$1,800 annual revenue at risk allows executive leadership to evaluate retention budgets quantitatively.(Saved Customers * Annual Value) - (Campaign Cost + Incurred Discounts).import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("data/session_4_2_dataset.csv")
X = df[["Tenure_Months_Count", "Customer_Support_Calls_Count", "Usage_Drop_Last_30_Days_Pct"]]
y = df["Churned_Within_60_Days_Binary"]
model = LogisticRegression().fit(X, y)
df["Churn_Probability"] = model.predict_proba(X)[:, 1].round(3)
print(df[["Subscriber_ID", "Tenure_Months_Count", "Churn_Probability"]].head(3))
df["Annual_Subscription_USD"] = df["Monthly_Subscription_Fee_USD"] * 12.0
df["Revenue_At_Risk_USD"] = (df["Churn_Probability"] * df["Annual_Subscription_USD"]).round(2)
total_risk = df["Revenue_At_Risk_USD"].sum()
print(f"Total Portfolio Revenue at Risk: ${total_risk:,.2f}")
def assign_retention_campaign(row):
if row["Churn_Probability"] >= 0.70 and row["Annual_Subscription_USD"] >= 1500.0:
return "VIP_Dedicated_Account_Manager"
elif row["Churn_Probability"] >= 0.50:
return "15Pct_Contract_Discount_Offer"
else:
return "Standard_Product_Newsletter"
df["Assigned_Campaign"] = df.apply(assign_retention_campaign, axis=1)
print("Retention Campaign Allocation:\\n", df["Assigned_Campaign"].value_counts())
Subscriber_ID: Unique account identifier (e.g., SUB-901).Tenure_Months_Count: Active customer relationship length in months.Monthly_Subscription_Fee_USD: Monthly recurring invoice fee in U.S. Dollars.Customer_Support_Calls_Count: Inbound complaint calls logged in the last 90 days.Usage_Drop_Last_30_Days_Pct: Platform usage decline percentage in the trailing 30 days.Churned_Within_60_Days_Binary: Ground truth subscriber cancellation outcome (0 = Retained, 1 = Churned).session_4_2_churn.py.import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("data/session_4_2_dataset.csv")
features = ["Tenure_Months_Count", "Customer_Support_Calls_Count", "Usage_Drop_Last_30_Days_Pct"]
clf = LogisticRegression().fit(df[features], df["Churned_Within_60_Days_Binary"])
df["Churn_Probability"] = clf.predict_proba(df[features])[:, 1]
df["Annual_Value_USD"] = df["Monthly_Subscription_Fee_USD"] * 12.0
df["Revenue_At_Risk_USD"] = df["Churn_Probability"] * df["Annual_Value_USD"]
# Target high-risk subscribers
actionable_subscribers = df[df["Churn_Probability"] >= 0.50]
total_saved_revenue = actionable_subscribers["Annual_Value_USD"].sum() * 0.40 # 40% retention success rate
campaign_cost = len(actionable_subscribers) * 75.0 # $75 per targeted outreach
net_campaign_roi = ((total_saved_revenue - campaign_cost) / campaign_cost) * 100.0
print(f"Actionable High-Risk Subscribers: {len(actionable_subscribers)}")
print(f"Projected Saved Revenue: ${total_saved_revenue:,.2f}")
print(f"Net Campaign ROI: {net_campaign_roi:.1f}%")
[4] (Terminal) using $ python session_4_2_churn.py and confirm clean execution.session_4_2_practice.py, build a dynamic threshold simulator evaluating retention ROI across churn probability thresholds from 0.30 to 0.80..copy() (e.g., high_risk["Campaign"] = "Discount"). Observe the terminal SettingWithCopyWarning, capture the message with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains DataFrame memory views vs explicit .copy()..copy(), print the optimal threshold recommendation, export the prioritized subscriber outreach call list to data/retention_call_sheet.csv, and verify return code 0.
| Schedule: Week 15 (115/12/20 - 115/12/26) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Price Elasticity of Demand (PED): The percentage change in quantity demanded resulting from a 1% change in product price, quantifying consumer price sensitivity.Revenue Management Optimization: Programmatically identifying the price point that maximizes total gross profit ((Price - Unit_Cost) * Quantity) subject to market demand curves.Gross Margin Simulation: Simulating projected sales volume and financial profit across discrete pricing scenarios (+5%, +10%, -10%).Competitor Price Gap Sensitivity: Modeling how the premium or discount relative to competitor catalog prices influences customer purchase conversion.Constrained Inventory Markdown: Algorithmic pricing logic that automatically applies markdown discounts when inventory velocity indicates risk of unsold seasonal stock.Current_Price / Competitor_Price as a primary explanatory feature.import pandas as pd
import numpy as np
df = pd.read_csv("data/session_4_3_dataset.csv")
# Percentage premium relative to competitor
df["Price_Premium_Pct"] = ((df["Current_Price_USD"] - df["Competitor_Price_USD"]) / df["Competitor_Price_USD"]) * 100.0
# Empirical Price Elasticity: % Change in Sales / % Change in Price
base_price = df["Current_Price_USD"].mean()
base_sales = df["Historical_Daily_Sales_Units"].mean()
# Simulated elasticity: For every 10% price premium, daily sales drop by 15% (Elasticity = -1.5)
elasticity_coefficient = -1.5
print(f"Empirical Price Elasticity of Demand Coefficient: {elasticity_coefficient}")
def simulate_pricing_scenario(data, price_adjustment_pct):
simulated = data.copy()
simulated["Simulated_Price_USD"] = simulated["Current_Price_USD"] * (1.0 + price_adjustment_pct)
# Quantity adjusted by elasticity
simulated["Simulated_Daily_Units"] = simulated["Historical_Daily_Sales_Units"] * (1.0 + (elasticity_coefficient * price_adjustment_pct))
simulated["Simulated_Gross_Profit_USD"] = (simulated["Simulated_Price_USD"] - simulated["Unit_Cost_USD"]) * simulated["Simulated_Daily_Units"]
return simulated["Simulated_Gross_Profit_USD"].sum()
current_profit = simulate_pricing_scenario(df, 0.0)
plus_5_profit = simulate_pricing_scenario(df, 0.05)
minus_5_profit = simulate_pricing_scenario(df, -0.05)
print(f"Current Daily Gross Profit: ${current_profit:,.2f}")
print(f"Daily Gross Profit at +5% Price: ${plus_5_profit:,.2f}")
print(f"Daily Gross Profit at -5% Price: ${minus_5_profit:,.2f}")
# Days of inventory remaining at current sales velocity
df["Days_Of_Inventory_Remaining"] = df["Inventory_Units_Count"] / df["Historical_Daily_Sales_Units"]
df["Markdown_Recommended"] = df["Days_Of_Inventory_Remaining"].apply(lambda d: "Markdown_15Pct" if d > 20 else "Maintain_Price")
print(df[["Product_ID", "Inventory_Units_Count", "Days_Of_Inventory_Remaining", "Markdown_Recommended"]].head(3))
Product_ID: Product stock keeping identifier (e.g., PRD-201).Current_Price_USD: Active enterprise retail price in U.S. Dollars.Competitor_Price_USD: Direct market competitor price in U.S. Dollars.Inventory_Units_Count: Active warehouse stock in units.Historical_Daily_Sales_Units: Historical average daily sales volume in units.Unit_Cost_USD: Landed cost of goods sold per unit in U.S. Dollars.session_4_3_pricing.py.import pandas as pd
import numpy as np
df = pd.read_csv("data/session_4_3_dataset.csv")
# Compute baseline daily unit economics
df["Unit_Gross_Margin_USD"] = df["Current_Price_USD"] - df["Unit_Cost_USD"]
df["Daily_Gross_Profit_USD"] = df["Unit_Gross_Margin_USD"] * df["Historical_Daily_Sales_Units"]
# Test pricing grid from -15% to +15%
test_rates = [-0.15, -0.10, -0.05, 0.0, 0.05, 0.10, 0.15]
profit_curve = {}
for rate in test_rates:
sim_price = df["Current_Price_USD"] * (1.0 + rate)
sim_units = df["Historical_Daily_Sales_Units"] * np.maximum(0.1, (1.0 + (-1.4 * rate)))
sim_profit = ((sim_price - df["Unit_Cost_USD"]) * sim_units).sum()
profit_curve[f"{rate*100:+.0f}%"] = round(sim_profit, 2)
print("Simulated Daily Portfolio Profit Across Price Adjustments:\\n", profit_curve)
[4] (Terminal) using $ python session_4_3_pricing.py and confirm clean execution.session_4_3_practice.py, develop a product-specific optimization script that sets prices dynamically to ensure all inventory clears within 15 days while maximizing gross margin.Inventory / 15.0) and solve for the optimal price adjustment percentage.df["Optimal_Price"] = df.apply(lambda r: r["Current_Price_USD"] * (1.0 + r["Adj"])). Observe the terminal SyntaxError: unexpected EOF while parsing, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains lambda function syntax.data/optimized_price_catalog.csv, and verify return code 0.
| Schedule: Week 16 (115/12/27 - 116/01/02) | In-person classes (1:2 Delivery Ratio: 60 Min Lecture + 120 Min Lab) |
Algorithmic Disparate Impact: A legal and quantitative metric occurring when an automated decision system yields substantially different adverse outcomes across protected demographic groups.Demographic Parity Metric: The fairness standard requiring that the likelihood of receiving a positive algorithmic outcome (e.g., credit approval) is equal across all demographic groups.Model Explainability (SHAP / Feature Attribution): Algorithmic frameworks that decompose complex black-box model predictions into transparent, auditable feature contributions for adverse action notices.Regulatory Compliance (EU AI Act Framework): Auditing machine learning systems against emerging international governance standards (such as the European Union Artificial Intelligence Act for high-risk credit and hiring systems).Boardroom AI Governance: Enterprise governance architecture establishing risk management protocols, algorithmic audit trails, human-in-the-loop overrides, and executive accountability.import pandas as pd
df = pd.read_csv("data/session_4_4_dataset.csv")
# Approval rate by demographic group (Threshold >= 0.70)
df["Approved_Binary"] = (df["Algorithmic_Approval_Score"] >= 0.70).astype(int)
approval_rates = df.groupby("Demographic_Group")["Approved_Binary"].mean()
disparate_impact_ratio = approval_rates["Group_B"] / approval_rates["Group_A"]
print("Approval Rates by Demographic Group:\\n", approval_rates)
print(f"Disparate Impact Ratio (Group B / Group A): {disparate_impact_ratio:.3f}")
# Four-Fifths (80%) Rule Compliance
compliance = "Compliant (>= 0.80)" if disparate_impact_ratio >= 0.80 else "Non-Compliant Violation (< 0.80)"
print(f"Regulatory Four-Fifths Rule Status: {compliance}")
def generate_adverse_action_notice(applicant_row):
reasons = []
if applicant_row["Credit_Score_Count"] < 700:
reasons.append("Credit score below prime benchmark (700)")
if applicant_row["Debt_To_Income_Pct"] > 30.0:
reasons.append("Debt-to-income ratio exceeds underwriting ceiling (30%)")
return "; ".join(reasons) if reasons else "Approved"
df["Regulatory_Explanation"] = df.apply(generate_adverse_action_notice, axis=1)
rejected_sample = df[df["Approved_Binary"] == 0].iloc[0]
print(f"Adverse Action Notice for {rejected_sample['Applicant_ID']}: {rejected_sample['Regulatory_Explanation']}")
audit_record = {
"Model_Name": "Credit_Underwriting_Risk_Engine_v1.4",
"Total_Audited_Applicants": len(df),
"Group_A_Approval_Rate": float(approval_rates["Group_A"]),
"Group_B_Approval_Rate": float(approval_rates["Group_B"]),
"Disparate_Impact_Ratio": float(disparate_impact_ratio),
"Governance_Status": "Audited_Board_Review_Required"
}
print("Governance Audit Certificate:", audit_record)
Applicant_ID: Unique applicant tracking code (e.g., APP-6001).Demographic_Group: Anonymized protected demographic category (Group_A, Group_B).Credit_Score_Count: Historical consumer credit bureau rating.Debt_To_Income_Pct: Total monthly debt service relative to verified income.Algorithmic_Approval_Score: Uncalibrated raw model creditworthiness score (0.0 to 1.0).Adverse_Action_Notice_Flag: Regulatory requirement indicator (0 = No Notice, 1 = Mandated Notice).session_4_4_governance.py.import pandas as pd
df = pd.read_csv("data/session_4_4_dataset.csv")
# Threshold evaluation
df["Approved"] = (df["Algorithmic_Approval_Score"] >= 0.70).astype(int)
rates = df.groupby("Demographic_Group")["Approved"].mean()
ratio = rates["Group_B"] / rates["Group_A"]
print(f"Group A Approval: {rates['Group_A']*100:.1f}% | Group B Approval: {rates['Group_B']*100:.1f}%")
print(f"Disparate Impact Ratio: {ratio:.3f}")
if ratio < 0.80:
print("CRITICAL ALERT: System violates the EEOC Four-Fifths Rule. Mitigating calibration required.")
else:
print("System compliant with demographic parity benchmarks.")
[4] (Terminal) using $ python session_4_4_governance.py and confirm clean execution.session_4_4_practice.py, develop a bias mitigation threshold optimizer that adjusts the approval threshold for Group B to restore the Disparate Impact ratio to at least 0.85 while maintaining overall portfolio loss risk below 5.0%.threshold_A, threshold_B) that satisfies the Four-Fifths rule.print(calibrated_threshold) after loop termination). Observe the terminal NameError: name 'calibrated_threshold' is not defined, capture the traceback with Windows Key + Shift + S, paste into Panel [3] (AI Agent Chat) with Ctrl + V, and review how the AI explains variable scope and return statements.data/board_ai_governance_audit.csv, and verify return code 0.
“””