import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import numpy_financial as npf
# --- 1. INPUT ASSUMPTIONS ---
# You can change these values to fit your specific scenario
inputs = {
"asset_cost": 100000, # Purchase price of the asset
"loan_down_payment": 20000, # Initial cash outlay if buying
"loan_interest_rate": 0.07, # Annual interest rate on the loan
"loan_term_years": 5, # Duration of the loan and the lease
"lease_payment_monthly": 1800, # Monthly lease payment
"corporate_tax_rate": 0.21, # Effective corporate tax rate
"discount_rate_wacc": 0.06, # Your Weighted Average Cost of Capital (for NPV)
"depreciation_method": "straight_line", # 'straight_line' or 'macrs_5yr'
"residual_value": 20000, # Estimated resale value at end of term (for Buying)
"lease_buyout": 25000 # Option to buy asset at end of lease (optional)
}
# --- 2. CORE CALCULATION FUNCTIONS ---
def calculate_loan_schedule(principal, annual_rate, years):
"""Generates an amortization schedule."""
monthly_rate = annual_rate / 12
n_payments = years * 12
monthly_payment = npf.pmt(monthly_rate, n_payments, -principal)
schedule = []
bal = principal
for m in range(1, n_payments + 1):
interest = bal * monthly_rate
principal_paid = monthly_payment - interest
bal -= principal_paid
schedule.append({
"Month": m,
"Interest": interest,
"Principal": principal_paid,
"Payment": monthly_payment,
"Balance": max(bal, 0)
})
return pd.DataFrame(schedule)
def calculate_buy_npv(inputs):
"""Calculates NPV of Buying Cash Flows."""
# Initialize Cash Flows (Year 0)
cf_y0 = -inputs["loan_down_payment"]
# Calculate Loan Schedule
loan_principal = inputs["asset_cost"] - inputs["loan_down_payment"]
loan_df = calculate_loan_schedule(loan_principal, inputs["loan_interest_rate"], inputs["loan_term_years"])
# Aggregate to Annual for Tax Purposes
loan_df['Year'] = (loan_df['Month'] - 1) // 12 + 1
annual_interest = loan_df.groupby('Year')['Interest'].sum()
# Depreciation Schedule (Simple Straight Line for this tool)
# Note: Real world often uses MACRS. This simplifies to Salvage=0 for tax dep. basis.
annual_depreciation = inputs["asset_cost"] / inputs["loan_term_years"]
cash_flows = [cf_y0]
for year in range(1, inputs["loan_term_years"] + 1):
# 1. Operating Cost (Assume equal for both, ignored here to isolate financing differences)
# 2. Loan Payments (Outflow)
# We look at actual cash out the door (Total Payment), not just interest
# However, Principal is not tax deductible, Interest is.
# Annual Cash Outflow
total_annual_loan_pmt = loan_df[loan_df['Year'] == year]['Payment'].sum()
# 3. Tax Shield (Inflow / Savings)
# Tax Shield = (Interest + Depreciation) * Tax Rate
interest_y = annual_interest.get(year, 0)
tax_shield = (interest_y + annual_depreciation) * inputs["corporate_tax_rate"]
# 4. Net Cash Flow for the Year
# In a loan, you pay the full payment, but get a tax refund on the shield portion.
net_cf = -total_annual_loan_pmt + tax_shield
# 5. Terminal Value (Resale) - Occurs in final year
if year == inputs["loan_term_years"]:
# Assume we sell for residual value.
# Tax implication: If Book Value != Residual, there is a gain/loss tax event.
# Book Value = Cost - Accum Depr
book_value = inputs["asset_cost"] - (annual_depreciation * year)
resale_value = inputs["residual_value"]
if resale_value > book_value:
# Recapture (Taxed)
tax_on_gain = (resale_value - book_value) * inputs["corporate_tax_rate"]
net_terminal = resale_value - tax_on_gain
else:
# Loss (Tax Benefit)
tax_benefit = (book_value - resale_value) * inputs["corporate_tax_rate"]
net_terminal = resale_value + tax_benefit
net_cf += net_terminal
cash_flows.append(net_cf)
# Calculate NPV
npv = npf.npv(inputs["discount_rate_wacc"], cash_flows)
return npv, cash_flows
def calculate_lease_npv(inputs):
"""Calculates NPV of Leasing Cash Flows."""
cash_flows = [0] # Year 0 usually no down payment for operating lease (assume 0)
monthly_pmt = inputs["lease_payment_monthly"]
term_months = inputs["loan_term_years"] * 12
# Aggregate Monthly to Annual
for year in range(1, inputs["loan_term_years"] + 1):
# Total Lease Payments for the year
annual_lease_pmt = monthly_pmt * 12
# Tax Shield: Lease payments are fully deductible operating expenses
tax_shield = annual_lease_pmt * inputs["corporate_tax_rate"]
net_cf = -annual_lease_pmt + tax_shield
# Terminal: Do we buy it out?
if year == inputs["loan_term_years"]:
# If we buyout, it's a cash outflow.
# Usually, we then own the asset, but for comparison we assume we pay the buyout and stop.
net_cf -= inputs["lease_buyout"]
cash_flows.append(net_cf)
npv = npf.npv(inputs["discount_rate_wacc"], cash_flows)
return npv, cash_flows
# --- 3. EXECUTION & REPORTING ---
buy_npv, buy_cfs = calculate_buy_npv(inputs)
lease_npv, lease_cfs = calculate_lease_npv(inputs)
print(f"--- DECISION SUMMARY ---")
print(f"Asset Cost: ${inputs['asset_cost']:,.0f}")
print(f"Discount Rate: {inputs['discount_rate_wacc']:.1%}")
print(f"Tax Rate: {inputs['corporate_tax_rate']:.1%}")
print("-" * 30)
print(f"NPV of Buying: ${buy_npv:,.2f}")
print(f"NPV of Leasing: ${lease_npv:,.2f}")
print("-" * 30)
nal = buy_npv - lease_npv # Net Advantage to Leasing
if nal > 0:
print(f"DECISION: LEASE. (Net Advantage: ${nal:,.2f})")
print("Explanation: The present value of leasing costs is lower than buying.")
else:
print(f"DECISION: BUY. (Net Advantage: ${-nal:,.2f})")
print("Explanation: The present value of buying costs is lower than leasing.")
# --- 4. SENSITIVITY ANALYSIS ---
# How does the decision change based on Discount Rate and Residual Value?
print("\n--- RUNNING SENSITIVITY ANALYSIS ---")
rates = np.linspace(0.02, 0.12, 5) # 2% to 12%
residuals = np.linspace(10000, 40000, 5) # 10k to 40k
results = []
for r in rates:
for res in residuals:
# Temporarily update inputs
temp_inputs = inputs.copy()
temp_inputs["discount_rate_wacc"] = r
temp_inputs["residual_value"] = res
b_npv, _ = calculate_buy_npv(temp_inputs)
l_npv, _ = calculate_lease_npv(temp_inputs)
# Store Savings (Buying Cost - Leasing Cost)
# If negative, Leasing is more expensive (Buy is better)
# If positive, Leasing is cheaper (Lease is better)
savings = b_npv - l_npv
results.append({
"Discount Rate": r,
"Residual Value": res,
"Net Advantage (Lease)": savings
})
df_sens = pd.DataFrame(results)
pivot_table = df_sens.pivot("Discount Rate", "Residual Value", "Net Advantage (Lease)")
# Plotting
plt.figure(figsize=(10, 6))
sns.heatmap(pivot_table, annot=True, fmt=".0f", cmap="RdYlGn", linewidths=.5)
plt.title("Sensitivity: Net Advantage to Leasing ($)\n(Green = Lease, Red = Buy)")
plt.ylabel("Discount Rate (WACC)")
plt.xlabel("Estimated Residual Value (Selling Price)")
plt.show()