import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
# --- Page Config ---
st.set_page_config(page_title="Make vs. Buy Decision Engine", layout="wide")
# --- Helper Functions ---
def calculate_learning_curve_cost(base_cost, total_units, learning_rate):
"""
Calculates cumulative average cost and total cost using Wright's Law.
Formula: Y = aX^b
Y = Cumulative average cost per unit
a = Cost of first unit
X = Cumulative units
b = log(learning_rate) / log(2)
"""
if total_units == 0:
return 0, 0
b = np.log(learning_rate) / np.log(2)
# Cumulative Average Cost for all X units
cum_avg_cost = base_cost * (total_units ** b)
# Total Cost
total_cost = cum_avg_cost * total_units
return cum_avg_cost, total_cost
# --- Sidebar: Inputs ---
st.sidebar.title("⚙️ Configuration")
st.sidebar.header("1. Volume Settings")
max_units = st.sidebar.number_input("Maximum Units to Analyze", value=5000, step=100)
st.sidebar.header("2. 'Make' Costs (Internal)")
make_fixed = st.sidebar.number_input("Fixed Costs (Tooling, Setup, R&D)", value=50000.0, step=1000.0)
make_unit_cost = st.sidebar.number_input("Unit Cost (1st Run)", value=100.0, step=1.0)
make_learning = st.sidebar.slider("Learning Curve Rate (%)", 70, 100, 90,
help="The rate at which costs decline every time production doubles. Standard is 80-90%.")
make_var_others = st.sidebar.number_input("Variable Overhead per Unit", value=5.0, step=1.0)
st.sidebar.header("3. 'Buy' Costs (Supplier)")
buy_fixed = st.sidebar.number_input("Fixed Costs (Shipping, Ordering Fees)", value=1000.0, step=100.0)
buy_unit_cost = st.sidebar.number_input("Unit Price (Supplier)", value=60.0, step=1.0)
# --- Calculations ---
volumes = np.arange(0, max_units + 1)
df = pd.DataFrame(volumes, columns=['Volume'])
# Learning Curve Exponent
b = np.log(make_learning / 100.0) / np.log(2)
# Make Costs Calculation
# Cost of unit X = FirstUnitCost * X^b
# To get Total Cost for N units, we sum the cost of 1..N
# Using the Cumulative Average approximation for speed:
# Total Cost = N * (FirstUnitCost * N^b)
# Note: We add the specific variable overhead separately
df['Make_Total_Cost'] = df['Volume'].apply(
lambda x: make_fixed + (calculate_learning_curve_cost(make_unit_cost, x, make_learning/100.0)[1]) + (x * make_var_others)
)
# Buy Costs Calculation (Simple Linear)
df['Buy_Total_Cost'] = (df['Volume'] * buy_unit_cost) + buy_fixed
# Unit Costs for Comparison
df['Make_Unit_Avg'] = df['Make_Total_Cost'] / df['Volume'].replace(0, np.nan)
df['Buy_Unit_Avg'] = df['Buy_Total_Cost'] / df['Volume'].replace(0, np.nan)
# --- Dashboard Display ---
st.title("🏭 Make vs. Buy Decision Engine")
st.markdown("""
This tool analyzes the total cost of production, incorporating **Wright's Law (Learning Curves)**.
* **Make:** Costs typically start high due to fixed costs, but unit costs decrease as volume increases (learning effect).
* **Buy:** Costs are typically linear.
""")
col1, col2, col3 = st.columns(3)
# Find Crossover Point
crossover_idx = np.where(df['Buy_Total_Cost'] < df['Make_Total_Cost'])[0]
if len(crossover_idx) > 0:
# Find the last volume where Buy is cheaper than Make
# Actually we want the point where Make becomes cheaper than Buy
crossover_vol = df.loc[df['Make_Total_Cost'] <= df['Buy_Total_Cost'], 'Volume'].min()
# Logic check: At volume 0, Make is Fixed Cost, Buy is Fixed Cost.
# Usually Make Fixed > Buy Fixed. So we look for the intersection.
intersection_volumes = df['Volume'][df['Make_Total_Cost'] <= df['Buy_Total_Cost']]
if not intersection_volumes.empty:
# The first volume where Make is cheaper or equal
decision_vol = intersection_volumes.iloc[0]
decision_cost = df.loc[df['Volume'] == decision_vol, 'Make_Total_Cost'].values[0]
else:
decision_vol = "N/A (Buy always cheaper)"
decision_cost = "N/A"
else:
decision_vol = "N/A"
decision_cost = "N/A"
with col1:
st.metric("Crossover Volume", f"{decision_vol:,.0f}" if isinstance(decision_vol, (int, float)) else decision_vol,
help="The production volume at which it becomes cheaper to 'Make' than to 'Buy'.")
with col2:
st.metric("Initial 'Make' Unit Cost", f"${make_unit_cost + make_var_others:,.2f}",
delta=f"-{(1-(make_learning/100)):.0f}% per doubling",
help="Includes variable overhead. The delta shows cost reduction efficiency.")
with col3:
st.metric("Supplier Unit Cost", f"${buy_unit_cost:,.2f}")
# --- Charting ---
fig = go.Figure()
# Make Cost Line
fig.add_trace(go.Scatter(
x=df['Volume'], y=df['Make_Total_Cost'],
mode='lines', name='Total Cost: MAKE',
line=dict(color='#FF4B4B', width=3),
hovertemplate='Volume: %{x}<br>Total Cost: $%{y:,.2f}<extra></extra>'
))
# Buy Cost Line
fig.add_trace(go.Scatter(
x=df['Volume'], y=df['Buy_Total_Cost'],
mode='lines', name='Total Cost: BUY',
line=dict(color='#1F77B4', width=3, dash='dot'),
hovertemplate='Volume: %{x}<br>Total Cost: $%{y:,.2f}<extra></extra>'
))
# Crossover Annotation
if isinstance(decision_vol, (int, float)) and decision_vol > 0:
fig.add_vline(x=decision_vol, line_width=2, line_dash="dash", line_color="green",
annotation_text=f"Breakeven: {decision_vol:,.0f} units",
annotation_position="top left")
fig.update_layout(
title="Total Cost Comparison: Make vs. Buy",
xaxis_title="Production Volume",
yaxis_title="Total Cost ($)",
hovermode="x unified",
height=500
)
st.plotly_chart(fig, use_container_width=True)
# --- Detailed Analysis Table ---
with st.expander("📊 View Detailed Cost Breakdown"):
# Show only every 10th row to keep table clean, plus the crossover point
display_df = df[df['Volume'] % 100 == 0].copy()
display_df['Decision'] = np.where(display_df['Make_Total_Cost'] < display_df['Buy_Total_Cost'], 'MAKE ✅', 'BUY 🛒')
display_df['Savings'] = display_df['Buy_Total_Cost'] - display_df['Make_Total_Cost']
st.dataframe(display_df.set_index('Volume').style.format({
'Make_Total_Cost': '${:,.2f}',
'Buy_Total_Cost': '${:,.2f}',
'Make_Unit_Avg': '${:,.2f}',
'Buy_Unit_Avg': '${:,.2f}',
'Savings': '${:,.2f}'
}).applymap(
lambda x: 'background-color: #d4edda' if 'MAKE' in str(x) else 'background-color: #fff3cd' if 'BUY' in str(x) else '',
subset=['Decision']
))