python
import numpy as np
import numpy_financial as npf
import pandas as pd
import itertools
def lease_vs_buy(P, L, n, S, r, t):
"""
Lease vs Buy NPV Calculator.
Parameters:
- P: Purchase price of asset
- L: Annual lease payment (end of year)
- n: Lease/buy term in years
- S: Salvage value at end of term
- r: WACC (discount rate)
- t: Corporate tax rate
Returns:
Dict with NPVs, costs (positive), NAL (positive = lease better), recommendation.
Assumptions:
- Straight-line depreciation to zero book value.
- Lease payments fully deductible.
- Salvage value taxed at t (capital gain tax).
- All cash flows end-of-year except initial purchase (t=0).
- After-tax WACC used to discount after-tax cash flows.
"""
# Buy cash flows
dep = P / n # Annual straight-line depreciation to zero
tax_shield = dep * t
cf_buy = np.zeros(n + 1)
cf_buy[0] = -P # Initial outlay
cf_buy[1:n+1] = tax_shield # Annual tax shields
salvage_at = S * (1 - t) # After-tax salvage
cf_buy[n] += salvage_at
npv_buy = npf.npv(r, cf_buy) # Negative value
# Lease cash flows (after-tax)
lease_at = -L * (1 - t)
cf_lease = np.zeros(n + 1)
cf_lease[1:n+1] = lease_at # Annual after-tax outflows
npv_lease = npf.npv(r, cf_lease) # Negative value
# Costs (positive PV of net outflows)
cost_buy = -npv_buy
cost_lease = -npv_lease
# Net Advantage to Leasing (NAL): if positive, leasing is cheaper
nal = cost_buy - cost_lease
recommendation = 'LEASE' if nal > 0 else 'BUY'
return {
'NPV_Buy (net CF)': npv_buy,
'Cost_Buy (PV)': cost_buy,
'NPV_Lease (net CF)': npv_lease,
'Cost_Lease (PV)': cost_lease,
'NAL (positive=Lease better)': nal,
'Recommendation': recommendation
}
def sensitivity_analysis(base_inputs, var_names, var_ranges):
"""
Generate sensitivity table.
Example:
base_inputs = {'P': 1000000, 'L': 250000, 'n': 5, 'S': 100000, 'r': 0.08, 't': 0.30}
var_names = ['r', 't']
var_ranges = {'r': np.arange(0.05, 0.16, 0.01), 't': np.arange(0.20, 0.41, 0.05)}
Returns: DataFrame with sensitivity results.
"""
results = []
keys = list(base_inputs.keys())
vary_keys = list(var_ranges.keys())
for combo in itertools.product(*(var_ranges[k] for k in vary_keys)):
inputs = base_inputs.copy()
for k, v in zip(vary_keys, combo):
inputs[k] = v
result = lease_vs_buy(**inputs)
row = {**{k: inputs[k] for k in vary_keys}, **result}
results.append(row)
df = pd.DataFrame(results)
# Pivot for nicer view if 2 vars
if len(var_names) == 2:
pivot = df.pivot(index=var_names[1], columns=var_names[0], values='NAL (positive=Lease better)')
return df, pivot
return df, None
# =====================================
# EXAMPLE USAGE
# =====================================
# Default inputs (1M asset, 5yr term, reasonable lease payment)
base_inputs = {
'P': 1_000_000, # Purchase price
'L': 250_000, # Annual lease payment
'n': 5, # Years
'S': 100_000, # Salvage value
'r': 0.08, # WACC
't': 0.30 # Tax rate
}
print("=== BASE CASE ===")
base_result = lease_vs_buy(**base_inputs)
for k, v in base_result.items():
print(f"{k}: {v:,.0f}" if isinstance(v, (int, float)) else f"{k}: {v}")
print("\n=== SENSITIVITY: WACC & TAX RATE ===")
wacc_range = np.arange(0.05, 0.16, 0.01)
tax_range = np.arange(0.20, 0.41, 0.05)
sens_df, pivot_df = sensitivity_analysis(
base_inputs,
['r', 't'],
{'r': wacc_range, 't': tax_range}
)
print("\nFull Sensitivity Table (NAL):")
print(sens_df[['r', 't', 'NAL (positive=Lease better)', 'Recommendation']].round(0))
print("\nPivot Table (NAL: rows=TAX, cols=WACC):")
print(pivot_df.round(0))
print("\nRecommendation Heatmap Summary:")
print(sens_df[sens_df['NAL (positive=Lease better)'] > 0]['Recommendation'].value_counts())
Copy-paste and tweak! If you provide specific numbers, I'll run it. 🕵️♂️