Binomial Tree Valuation for Equity Options and Bonds

Medium · Statistics & Math · Data Scientist · Online Assessment

Problem Statement

Build a discrete-time valuation toolkit that prices equity options on a recombining binomial lattice and fixed-income instruments on a path-indexed short-rate tree under the absence of arbitrage.

Part 1 — Equity Options on a Recombining Binomial Lattice

Over each discrete step on a non-dividend-paying stock, the share price multiplies by either u (up move) or d (down move), while riskless cash earns the simple per-period rate r (so 1 unit grows to 1 + r). After t steps with ups upward moves (0 <= ups <= t), the stock sits at node (t, ups) with price s0 * (u ** ups) * (d ** (t - ups)).

Implement the following functions:

  • risk_neutral_prob(u: float, d: float, r: float) -> float: Return the single-step risk-neutral up weight q = (1 + r - d) / (u - d). Raise ValueError unless d < 1 + r < u, since violating that inequality creates a one-step arbitrage.
  • option_payoff(price: float, strike: float, kind: str) -> float: Return intrinsic payoff max(price - strike, 0.0) when kind == "call" and max(strike - price, 0.0) when kind == "put" (raising ValueError for any other kind).
  • price_european(s0: float, strike: float, u: float, d: float, r: float, steps: int, kind: str) -> float: Compute the t = 0 fair value of a European "call" or "put" expiring after steps periods by rolling payoffs backward from maturity (t = steps) to t = 0.
  • price_american(s0: float, strike: float, u: float, d: float, r: float, steps: int, kind: str) -> Tuple[float, List[Tuple[int, int]]]: Compute the t = 0 fair value of an American "call" or "put" and return (price_at_t0, early_nodes), where early_nodes lists every interior node (t, ups) (0 <= t < steps, sorted ascending) at which exercising immediately yields strictly more value than continuing for another step (beyond floating-point rounding noise on exact ties). Be ready to justify mathematically why early exercise never strictly helps a non-dividend American call when r >= 0.

Part 2 — Bonds and Yield to Maturity on a Short-Rate Tree

Interest rates evolve along a binary short-rate tree that need not recombine. A dictionary rates maps each move history string ("" at t = 0, "u" and "d" at t = 1, "uu", "ud", "du", "dd" at t = 2, and so forth) to the simple one-period rate locked in at that node, discounting cash flows from t + 1 back to t via 1 / (1 + r_node) with risk-neutral up probability q.

Implement the remaining two functions:

  • bond_price(rates: Dict[str, float], cash_flows: List[float], q: float = 0.5) -> float: Return the t = 0 arbitrage-free price of deterministic payments where cash_flows[i] is paid at time i + 1 across every state. This handles both zero-coupon bonds (all zeros before the final face payment) and coupon-bearing bonds (periodic coupons plus principal at maturity), consistent with replicating a coupon bond as a portfolio of zero-coupon bonds.
  • yield_to_maturity(price: float, cash_flows: List[float]) -> float: Return the constant per-period discount rate y > -1 satisfying sum(cash_flows[i] / (1 + y) ** (i + 1)) == price. Raise ValueError if price <= 0, cash_flows is empty, any entry is negative, or the total cash flow is zero.

Examples

Example 1

Input:

s0, strike, u, d, r, steps = 80.0, 80.0, 1.2, 0.7, 0.04, 2
q = risk_neutral_prob(u, d, r)
euro_call = price_european(s0, strike, u, d, r, steps, "call")
amer_put = price_american(s0, strike, u, d, r, steps, "put")
amer_call = price_american(s0, strike, u, d, r, steps, "call")

Output:

q         = 0.68
euro_call = 15.048520710059172
amer_put  = (9.959763313609464, [(1, 0)])
amer_call = (15.048520710059172, [])

Explanation: First, q = (1.04 - 0.7) / (1.2 - 0.7) = 0.68 (1 - q = 0.32). Terminal stock prices at t = 2 are 115.2, 67.2, and 39.2. For the European call, only (2, 2) pays 35.2, discounting to 0.68 * 35.2 / 1.04 = 23.0154 at (1, 1) and 0.68 * 23.0154 / 1.04 = 15.0485 at (0, 0). For the American put, terminal payoffs are 0.0, 12.8, and 40.8; at (1, 0) (S = 56.0), immediate exercise pays 24.0, strictly beating the continuation value (0.68 * 12.8 + 0.32 * 40.8) / 1.04 = 20.9231, while (1, 1) holds (3.9385 > 0), giving (0.68 * 3.9385 + 0.32 * 24.0) / 1.04 = 9.9598 at t = 0. The non-dividend American call never exercises early (early_nodes = []).

Example 2

Input:

rates = {
    "": 0.04,
    "u": 0.06, "d": 0.02,
    "uu": 0.08, "ud": 0.05, "du": 0.03, "dd": 0.01,
}
zero_price = bond_price(rates, [0.0, 1000.0], q=0.5)
coupon_price = bond_price(rates, [40.0, 1040.0], q=0.5)
ytm = yield_to_maturity(coupon_price, [40.0, 1040.0])

Output:

zero_price   = 924.8982611912688
coupon_price = 1000.3557301004581
ytm          = 0.0398114442516343

Explanation: Discounting 1000 from t = 2 to t = 1 gives 1000 / 1.06 = 943.3962 at "u" and 1000 / 1.02 = 980.3922 at "d", then discounting their 50/50 average at r0 = 4% yields 924.8983 (the t = 2 rates apply to [2, 3] and do not affect t = 2 cash flows). Adding a 40 coupon at t = 1 and t = 2 equals 40 / 1.04 + 1.04 * 924.8983 = 1000.3557, corresponding to a flat per-period yield to maturity of 3.9811%.

Constraints

  • s0 > 0, strike >= 0, steps >= 0 (typically 0 <= steps <= 500; negative steps raises ValueError).
  • Valid stock trees satisfy 0 < d < 1 + r < u; any parameter triple violating d < 1 + r < u must raise ValueError.
  • kind is "call" or "put" (any other string raises ValueError).
  • rates contains every binary "u"/"d" path of length 0, 1, ..., len(cash_flows) - 1, with node rates r_node > -1 and 0 <= q <= 1.
  • In yield_to_maturity, valid inputs satisfy price > 0, len(cash_flows) >= 1, cash_flows[i] >= 0, and sum(cash_flows) > 0; invalid inputs raise ValueError.
  • Floating-point outputs are checked within 1e-9 relative/absolute tolerance.

Step-by-step walkthrough

  1. Map out the two trees and node conventions

    This problem uses two different two-period trees, and noticing how their nodes connect saves us from subtle indexing bugs:

    • Stock lattice (Part 1, recombining): starting from s0 = 80.0, an up-move multiplies by u = 1.2 and a down-move multiplies by d = 0.7. Because multiplication commutes (80 * 1.2 * 0.7 = 80 * 0.7 * 1.2 = 67.2), "up then down" and "down then up" merge into the exact same middle node! Every node is uniquely identified by (t, ups): t periods elapsed and ups up-moves (0 <= ups <= t), with stock price s0 * u^ups * d^(t - ups).
    • Short-rate tree (Part 2, non-recombining): in Example 2, "ud" sets a 5% rate while "du" sets a 3% rate, so the order of moves matters! We therefore key rate-tree nodes by their path string: "" at t = 0, "u" and "d" at t = 1, and "uu", "ud", "du", "dd" at t = 2.
    Part 1: Recombining Stock Lattice       Part 2: Non-Recombining Short-Rate Tree
    t=0        t=1        t=2               t=0         t=1          t=2
                         (2,2): 115.2                               "uu": 8%
              (1,1):  96.0                              "u": 6%
    (0,0): 80.0          (2,1):  67.2       "": 4%                  "ud": 5%
              (1,0):  56.0                              "d": 2%     "du": 3%
                         (2,0):  39.2                               "dd": 1%
    

    Crucial timing rule for Part 2: the interest rate at time t governs discounting from t + 1 back to t. Consequently, cash flows paid at t = 2 are discounted once by the t = 1 rates (6% or 2%) and once by the t = 0 rate (4%)—the t = 2 rates (8%, 5%, 3%, 1%) apply to [2, 3] and never touch a bond maturing at t = 2!

  2. Derive the risk-neutral probability q from replication

    Why doesn't option pricing need the real-world probability that the stock rises? Because over a single step from S to S * u or S * d, we can replicate any derivative paying Vu (if up) and Vd (if down) using Delta shares of stock plus B dollars in risk-free cash (which grows to B * (1 + r)):

    Up state:     Delta * S * u + B * (1 + r) = Vu
    Down state:   Delta * S * d + B * (1 + r) = Vd
    

    Subtract the second equation from the first to solve for Delta, then substitute back for B:

    Delta * S * (u - d) = Vu - Vd   ==>   Delta = (Vu - Vd) / (S * (u - d))
    B                   = (u * Vd - d * Vu) / ((u - d) * (1 + r))
    

    By no-arbitrage (no riskless profit from zero net investment), the option today must cost the exact same as its replicating portfolio V = Delta * S + B. Grouping terms behind Vu and Vd simplifies Delta * S + B into a discounted weighted average:

    V = ((Vu - Vd) / (u - d)) + ((u * Vd - d * Vu) / ((u - d) * (1 + r)))
      = (((1 + r - d) / (u - d)) * Vu + ((u - (1 + r)) / (u - d)) * Vd) / (1 + r)
      = (q * Vu + (1 - q) * Vd) / (1 + r),      where  q = (1 + r - d) / (u - d)
    

    For Example 1 (u = 1.20, d = 0.70, r = 0.04):

    q = (1.04 - 0.70) / (1.20 - 0.70) = 0.34 / 0.50 = 0.68,    1 - q = 0.32
    

    Notice 0 < q < 1 holds if and only if d < 1 + r < u. If 1 + r <= d, borrowing cash at r to buy stock beats cash in every state; if 1 + r >= u, shorting stock to hold cash beats the stock in every state. Our code checks d < 1 + r < u up front and raises ValueError on arbitrage trees.

    from typing import Dict, List, Tuple
    
    # Exercise must beat holding by more than float rounding noise to count as strictly optimal.
    TIE_TOLERANCE = 1e-9
    
    
    def risk_neutral_prob(u: float, d: float, r: float) -> float:
        gross_rf = 1.0 + r
        if not (d < gross_rf < u):
            raise ValueError(f"no-arbitrage needs d < 1 + r < u, got d={d}, 1+r={gross_rf}, u={u}")
        return (gross_rf - d) / (u - d)
    
    
    def option_payoff(price: float, strike: float, kind: str) -> float:
        if kind == "call":
            return max(price - strike, 0.0)
        if kind == "put":
            return max(strike - price, 0.0)
        raise ValueError(f"kind must be 'call' or 'put', got {kind!r}")
    
  3. Roll backward through the stock lattice for European and American options

    At expiration (t = steps), an option's value is known immediately: max(S - K, 0) for a call or max(K - S, 0) for a put. Backward induction computes those steps + 1 terminal payoffs first, then steps backward period by period (t = steps - 1, ..., 0):

    • European option (exercisable only at t = steps): each node's value is purely its continuation (hold) value (q * up_child + (1 - q) * down_child) / (1 + r).
    • American option (exercisable at any t <= steps): at every interior node (t, ups), the holder picks max(hold_value, exercise_value). We list (t, ups) as an optimal early-exercise node only when exercise_value > hold_value + 1e-9—strictly better than holding, ignoring tiny floating-point rounding noise on exact ties.

    Because row t only reads row t + 1, a single 1D list values[ups] (where values[ups + 1] is the up-child and values[ups] is the down-child) uses O(steps) memory.

    def stock_price(s0: float, u: float, d: float, t: int, ups: int) -> float:
        downs = t - ups
        return s0 * (u ** ups) * (d ** downs)
    
    
    def roll_back(s0: float, strike: float, u: float, d: float, r: float, steps: int, kind: str,
                  american: bool) -> Tuple[float, List[Tuple[int, int]]]:
        if steps < 0:
            raise ValueError(f"steps must be non-negative, got {steps}")
        q = risk_neutral_prob(u, d, r)
        discount_base = 1.0 + r
    
        # Phase 1: payoffs at maturity t = steps for ups = 0, 1, ..., steps.
        values: List[float] = []
        for ups in range(steps + 1):
            terminal_stock = stock_price(s0, u, d, steps, ups)
            values.append(option_payoff(terminal_stock, strike, kind))
    
        # Phase 2: step backward from t = steps - 1 down to t = 0.
        early_nodes: List[Tuple[int, int]] = []
        for t in range(steps - 1, -1, -1):
            prev_values: List[float] = []
            for ups in range(t + 1):
                up_child = values[ups + 1]
                down_child = values[ups]
                hold_value = (q * up_child + (1.0 - q) * down_child) / discount_base
                node_value = hold_value
    
                if american:
                    spot = stock_price(s0, u, d, t, ups)
                    exercise_value = option_payoff(spot, strike, kind)
                    if exercise_value > hold_value + TIE_TOLERANCE:
                        node_value = exercise_value
                        early_nodes.append((t, ups))
                prev_values.append(node_value)
            values = prev_values
    
        return values[0], sorted(early_nodes)
    
    
    def price_european(s0: float, strike: float, u: float, d: float, r: float, steps: int, kind: str) -> float:
        value, _ = roll_back(s0, strike, u, d, r, steps, kind, american=False)
        return value
    
    
    def price_american(s0: float, strike: float, u: float, d: float, r: float, steps: int,
                       kind: str) -> Tuple[float, List[Tuple[int, int]]]:
        return roll_back(s0, strike, u, d, r, steps, kind, american=True)
    
  4. Walk through Example 1: European call and American put

    With s0 = 80.0, strike = 80.0, u = 1.2, d = 0.7, r = 0.04, and q = 0.68:

    European call (max(S - 80, 0)):

    t = 2 payoffs:
      (2, 2) S = 115.20  ->  call = 35.20
      (2, 1) S =  67.20  ->  call =  0.00
      (2, 0) S =  39.20  ->  call =  0.00
    
    t = 1 roll-back:
      (1, 1) S =  96.00  ->  (0.68 * 35.20 + 0.32 * 0) / 1.04 = 23.936 / 1.04 = 23.0154
      (1, 0) S =  56.00  ->  (0.68 * 0     + 0.32 * 0) / 1.04 =  0.0000
    
    t = 0 roll-back:
      (0, 0) S =  80.00  ->  (0.68 * 23.0154 + 0.32 * 0) / 1.04 = 16.27648 / 1.0816 = 15.0485
    

    The European call price at t = 0 is 15.0485 (12716 / 845 ≈ 15.04852).

    American put (max(80 - S, 0)):

    t = 2 payoffs:
      (2, 2) S = 115.20  ->  put =  0.00
      (2, 1) S =  67.20  ->  put = 12.80
      (2, 0) S =  39.20  ->  put = 40.80
    
    t = 1 comparison (hold vs. exercise):
      (1, 1) S =  96.00  ->  hold = (0.32 * 12.80) / 1.04 = 3.9385,  exercise =  0.00  ->  3.9385
      (1, 0) S =  56.00  ->  hold = (0.68 * 12.80 + 0.32 * 40.80) / 1.04 = 20.9231,
                             exercise = 24.00                                          -> 24.0000 (EXERCISE!)
    
    t = 0 comparison (using V(1,0) = 24.00 from early exercise!):
      (0, 0) S =  80.00  ->  hold = (0.68 * 3.9385 + 0.32 * 24.00) / 1.04 = 9.9598, exercise = 0 -> 9.9598
    

    The American put price at t = 0 is 9.9598, and early exercise is optimal only at node (1, 0) (t = 1, down state S = 56.0). Why does exercising win at S = 56.0? Exercising immediately collects the 80.0 strike cash one period early, earning 80.0 * 0.04 = 3.20 (3.0769 in present value) of interest while the stock is already deep in the money (67.2 < 80 even if it bounces up next step!). Without early exercise, the European put costs only 9.0130, satisfying put-call parity C - P = 15.0485 - 9.0130 = 6.0355 = 80 - 80 / 1.04^2.

  5. Why a non-dividend American call is never exercised early

    Claim: When the stock pays no dividends and r >= 0, at every node with t < T (n = T - t >= 1 periods remaining), the call's continuation value satisfies:

    hold_t  >=  S_t - K / (1 + r)^n
    

    Proof by backward induction: 1. Base step (n = 0, at maturity T): V_T = max(S_T - K, 0) >= S_T - K. 2. Inductive step: Suppose V_{t+1} >= S_{t+1} - K / (1 + r)^(n - 1) holds at both child nodes S_t * u and S_t * d. Because q = (1 + r - d) / (u - d) was chosen precisely so that q * u + (1 - q) * d = 1 + r, we have:

    hold_t = (q * V_up + (1 - q) * V_down) / (1 + r)
          >= (q * (S_t * u - K / (1 + r)^(n - 1)) + (1 - q) * (S_t * d - K / (1 + r)^(n - 1))) / (1 + r)
           = S_t * ((q * u + (1 - q) * d) / (1 + r))  -  (q + 1 - q) * K / (1 + r)^n
           = S_t * ((1 + r) / (1 + r))                -  K / (1 + r)^n
           = S_t - K / (1 + r)^n
    

    Since the American call value at t + 1 is >= hold_{t+1}, the inequality carries all the way back to t = 0.

    Conclusion for r > 0: Because r > 0 and n >= 1, (1 + r)^n > 1, so K / (1 + r)^n < K, which means:

    hold_t  >=  S_t - K / (1 + r)^n  >  S_t - K
    
    • Whenever exercising pays a positive amount (S_t - K > 0), hold_t is strictly larger than S_t - K! (Check node (1, 1) in Example 1 where S = 96.0: hold = 23.0154 > 16.0 = 96.0 - 80.0.)
    • Whenever S_t <= K, exercising pays 0, while hold_t >= 0.

    Therefore, early exercise of a non-dividend-paying American call is never strictly optimal when r >= 0 (r > 0 makes holding strictly better; r = 0 at best ties), so the American call price equals the European call price (15.0485). Intuitively, exercising early hurts you twice with zero reward: you hand over the K strike cash early (forfeiting risk-free interest on K) and you throw away your downside insurance if S later drops below K (like dropping from 96.0 to 67.2), while missing no dividends.

  6. Price zero-coupon and coupon bonds on the short-rate tree

    On the short-rate tree, cash_flows[t] is paid at time t + 1 in both the "u" and "d" child states, and discounted back to time t using 1 + rates[path]. Because the rate tree may be non-recombining, a clean recursion on path visits each node cleanly:

    def bond_value_at(rates: Dict[str, float], cash_flows: List[float], q: float, path: str) -> float:
        t = len(path)
        if t == len(cash_flows):
            return 0.0
    
        next_payment = cash_flows[t]
        up_total = bond_value_at(rates, cash_flows, q, path + "u") + next_payment
        down_total = bond_value_at(rates, cash_flows, q, path + "d") + next_payment
    
        node_rate = rates[path]
        return (q * up_total + (1.0 - q) * down_total) / (1.0 + node_rate)
    
    
    def bond_price(rates: Dict[str, float], cash_flows: List[float], q: float = 0.5) -> float:
        return bond_value_at(rates, cash_flows, q, "")
    

    Tracing Example 2—a zero-coupon bond paying 1000 at t = 2 (cash_flows = [0.0, 1000.0], q = 0.5):

    t = 1 values (discounting 1000 from t = 2 back to t = 1):
      node "u" (r_u = 6%):  1000 / 1.06 = 943.396226
      node "d" (r_d = 2%):  1000 / 1.02 = 980.392157
    
    t = 0 price (discounting back to t = 0 at r0 = 4%):
      node ""  (r0  = 4%):  0.5 * (943.396226 + 980.392157) / 1.04
                          = 961.894192 / 1.04 = 924.898261
    

    The zero-coupon bond price is 924.8983. Notice that 924.8983 is slightly higher than 1000 / 1.04² = 924.5562: because the discount function 1 / (1 + r) is curved upward (convex), averaging 1 / 1.06 and 1 / 1.02 exceeds 1 / 1.04 (Jensen's inequality).

  7. Coupon bond replication and yield to maturity via bisection

    Now trace the 4% coupon bond in Example 2—face 1000 with coupon 40 at t = 1 and t = 2 (cash_flows = [40.0, 1040.0], q = 0.5):

    t = 1 total cash + continuation value:
      node "u" (6%):  (1040 / 1.06) + 40 =  981.132075 + 40 = 1021.132075
      node "d" (2%):  (1040 / 1.02) + 40 = 1019.607843 + 40 = 1059.607843
    
    t = 0 price (at r0 = 4%):
      node ""  (4%):  0.5 * (1021.132075 + 1059.607843) / 1.04 = 1000.355730
    

    The coupon bond price is 1000.3557.

    No-arbitrage replication principle: By the Law of One Price, two portfolios that pay identical cash flows in every state of the world must trade at the exact same price today—otherwise buying the cheaper one and short-selling the expensive one locks in risk-free profit. A [40, 1040] coupon bond is identical in every state to 40 units of a 1-period unit zero (1 / 1.04) plus 1040 units of a 2-period unit zero (0.924898261):

    40 * (1 / 1.04) + 1040 * 0.924898261 = 38.461538 + 961.894192 = 1000.355730  (exact match!)
    

    Yield to maturity (YTM) is the single flat per-period discount rate y that makes the present value of [40, 1040] equal its 1000.355730 price:

    40 / (1 + y) + 1040 / (1 + y)^2 = 1000.355730
    Let x = 1 / (1 + y):   1040 * x^2 + 40 * x - 1000.355730 = 0
    x = (-40 + sqrt(1600 + 4160 * 1000.355730)) / 2080 = 0.96171282   ==>   y = 1/x - 1 = 0.039811 (3.9811%)
    

    Its YTM is 3.981% per period—just below the 4% coupon rate because the bond trades slightly above par (1000.356 > 1000). For arbitrary maturities T, there is no quadratic shortcut, but because present_value(cash_flows, y) strictly decreases as y rises, bisection (binary search) brackets [low, high] and halves the interval 100 times to machine precision:

    def present_value(cash_flows: List[float], y: float) -> float:
        total = 0.0
        for i, cash in enumerate(cash_flows):
            period = i + 1
            total += cash / ((1.0 + y) ** period)
        return total
    
    
    def yield_to_maturity(price: float, cash_flows: List[float]) -> float:
        if price <= 0.0 or not cash_flows or any(c < 0.0 for c in cash_flows) or sum(cash_flows) == 0.0:
            raise ValueError("price must be positive and cash_flows non-negative with a positive sum")
    
        low = -0.5
        while present_value(cash_flows, low) < price:
            low = (low - 1.0) / 2.0
    
        high = 1.0
        while present_value(cash_flows, high) > price:
            high *= 2.0
    
        # Since present_value decreases as y rises, PV(mid) > price means the true yield lies above mid.
        for _ in range(100):
            mid = (low + high) / 2.0
            if present_value(cash_flows, mid) > price:
                low = mid
            else:
                high = mid
        return (low + high) / 2.0
    
  8. Complete solution

    from typing import Dict, List, Tuple
    
    # Exercise must beat holding by more than float rounding noise to count as strictly optimal.
    TIE_TOLERANCE = 1e-9
    
    
    def risk_neutral_prob(u: float, d: float, r: float) -> float:
        """Risk-neutral up probability q = (1 + r - d) / (u - d) for one period.
    
        u, d: gross up and down factors of the stock; r: simple risk-free rate per period.
        Raise ValueError unless d < 1 + r < u (otherwise the tree allows an arbitrage).
        """
        # If 1 + r <= d, borrowing cash to buy stock never loses money; if 1 + r >= u, shorting stock
        # to hold cash never loses money. Requiring d < 1 + r < u keeps 0 < q < 1.
        gross_rf = 1.0 + r
        if not (d < gross_rf < u):
            raise ValueError(f"no-arbitrage needs d < 1 + r < u, got d={d}, 1+r={gross_rf}, u={u}")
        return (gross_rf - d) / (u - d)
    
    
    def option_payoff(price: float, strike: float, kind: str) -> float:
        """max(price - strike, 0) for kind 'call', max(strike - price, 0) for kind 'put'."""
        if kind == "call":
            return max(price - strike, 0.0)
        if kind == "put":
            return max(strike - price, 0.0)
        raise ValueError(f"kind must be 'call' or 'put', got {kind!r}")
    
    
    def stock_price(s0: float, u: float, d: float, t: int, ups: int) -> float:
        """Stock price at recombining node (t, ups): ups up-moves and (t - ups) down-moves."""
        downs = t - ups
        return s0 * (u ** ups) * (d ** downs)
    
    
    def roll_back(s0: float, strike: float, u: float, d: float, r: float, steps: int, kind: str,
                  american: bool) -> Tuple[float, List[Tuple[int, int]]]:
        """Backward induction across the recombining tree; returns (t=0 price, early-exercise nodes)."""
        if steps < 0:
            raise ValueError(f"steps must be non-negative, got {steps}")
        q = risk_neutral_prob(u, d, r)
        discount_base = 1.0 + r
    
        # Phase 1 (terminal condition at maturity t = steps):
        # values[ups] stores the option value at node (t, ups) for ups = 0, 1, ..., t.
        values: List[float] = []
        for ups in range(steps + 1):
            terminal_stock = stock_price(s0, u, d, steps, ups)
            values.append(option_payoff(terminal_stock, strike, kind))
    
        # Phase 2 (step backward from t = steps - 1 down to t = 0):
        # early_nodes collects (t, ups) pairs where immediate exercise strictly beats holding.
        early_nodes: List[Tuple[int, int]] = []
        for t in range(steps - 1, -1, -1):
            prev_values: List[float] = []
            for ups in range(t + 1):
                # From (t, ups), an up-move leads to (t + 1, ups + 1) and a down-move to (t + 1, ups).
                up_child = values[ups + 1]
                down_child = values[ups]
                hold_value = (q * up_child + (1.0 - q) * down_child) / discount_base
                node_value = hold_value
    
                if american:
                    spot = stock_price(s0, u, d, t, ups)
                    exercise_value = option_payoff(spot, strike, kind)
                    # Use TIE_TOLERANCE so floating-point noise on exact ties (e.g. r = 0 calls) isn't flagged.
                    if exercise_value > hold_value + TIE_TOLERANCE:
                        node_value = exercise_value
                        early_nodes.append((t, ups))
                prev_values.append(node_value)
            values = prev_values
    
        return values[0], sorted(early_nodes)
    
    
    def price_european(s0: float, strike: float, u: float, d: float, r: float, steps: int, kind: str) -> float:
        """Price a European call or put by backward induction on a recombining binomial tree."""
        value, _ = roll_back(s0, strike, u, d, r, steps, kind, american=False)
        return value
    
    
    def price_american(s0: float, strike: float, u: float, d: float, r: float, steps: int,
                       kind: str) -> Tuple[float, List[Tuple[int, int]]]:
        """Price an American call or put and list the nodes where early exercise is optimal.
    
        A node (t, ups) is the state after t periods with ups up-moves; its stock price is
        s0 * u**ups * d**(t - ups). A node is listed (sorted ascending) when t < steps and
        exercising there is worth strictly more than holding the option one more period.
        """
        return roll_back(s0, strike, u, d, r, steps, kind, american=True)
    
    
    def bond_value_at(rates: Dict[str, float], cash_flows: List[float], q: float, path: str) -> float:
        """Ex-coupon bond value at the tree node reached by `path` (e.g. '', 'u', 'ud')."""
        t = len(path)
        # Once t reaches the final payment date len(cash_flows), no future cash flows remain.
        if t == len(cash_flows):
            return 0.0
    
        # At time t + 1, the holder receives cash_flows[t] PLUS the remaining value at that child node.
        next_payment = cash_flows[t]
        up_total = bond_value_at(rates, cash_flows, q, path + "u") + next_payment
        down_total = bond_value_at(rates, cash_flows, q, path + "d") + next_payment
    
        # Discount from t + 1 back to t using the one-period short rate locked in at `path`.
        node_rate = rates[path]
        return (q * up_total + (1.0 - q) * down_total) / (1.0 + node_rate)
    
    
    def bond_price(rates: Dict[str, float], cash_flows: List[float], q: float = 0.5) -> float:
        """Price fixed cash flows on a short-rate tree (recombining or not).
    
        rates maps a path of moves to the one-period rate set at that node:
        '' is t = 0, 'u' and 'd' are t = 1, 'ud' is up then down, and so on.
        The rate at a node discounts from that node's time to the next period.
        cash_flows[i] is paid at time i + 1 in every state; q is the risk-neutral up probability.
        """
        return bond_value_at(rates, cash_flows, q, "")
    
    
    def present_value(cash_flows: List[float], y: float) -> float:
        """Discount cash_flows[i], paid at time i + 1, at the flat per-period yield y."""
        total = 0.0
        for i, cash in enumerate(cash_flows):
            period = i + 1
            total += cash / ((1.0 + y) ** period)
        return total
    
    
    def yield_to_maturity(price: float, cash_flows: List[float]) -> float:
        """The flat per-period rate y with sum(cash_flows[i] / (1 + y)**(i + 1)) == price.
    
        Cash flows are non-negative with at least one positive, so the present value falls as y rises.
        """
        if price <= 0.0 or not cash_flows or any(c < 0.0 for c in cash_flows) or sum(cash_flows) == 0.0:
            raise ValueError("price must be positive and cash_flows non-negative with a positive sum")
    
        # Bracket the root on (-1, +inf): present_value -> +inf as y -> -1+ and -> 0 as y -> +inf.
        low = -0.5
        while present_value(cash_flows, low) < price:
            # Move (1 + low) halfway toward 0 so present value rises without ever hitting y = -1.
            low = (low - 1.0) / 2.0
    
        high = 1.0
        while present_value(cash_flows, high) > price:
            # Double high until the discounted present value drops at or below the target price.
            high *= 2.0
    
        # Bisect 100 times: since present_value decreases as y rises, PV(mid) > price means y* > mid.
        for _ in range(100):
            mid = (low + high) / 2.0
            if present_value(cash_flows, mid) > price:
                low = mid
            else:
                high = mid
        return (low + high) / 2.0
    
    
    if __name__ == "__main__":
        print("q =", risk_neutral_prob(1.2, 0.7, 0.04))
        print("European call =", price_european(80.0, 80.0, 1.2, 0.7, 0.04, 2, "call"))
        print("American put =", price_american(80.0, 80.0, 1.2, 0.7, 0.04, 2, "put"))
        tree = {"": 0.04, "u": 0.06, "d": 0.02, "uu": 0.08, "ud": 0.05, "du": 0.03, "dd": 0.01}
        coupon_bond = bond_price(tree, [40.0, 1040.0])
        print("zero =", bond_price(tree, [0.0, 1000.0]), "coupon bond =", coupon_bond)
        print("YTM =", yield_to_maturity(coupon_bond, [40.0, 1040.0]))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of no-arbitrage pricing like pricing a pre-packed fruit basket at a grocery store: if a basket always holds 2 apples and 1 melon, the basket must sell for the exact same total as 2 loose apples plus 1 loose melon—otherwise anyone could buy the cheaper side and sell the expensive side for instant risk-free profit (arbitrage). On a binomial tree (a discrete timeline where each period branches into just two possibilities, "up" or "down"), any option's two possible payoffs next period can be copied dollar-for-dollar by a synthetic basket of stock shares and risk-free cash. Algebraic rearrangement turns that basket's cost into a discounted expectation using a synthetic risk-neutral probability q (a pricing weight derived purely from u, d, and r so the stock's discounted average equals today's price), letting us start at expiration and work back to today one step at a time (backward induction).

Naive approaches fail in three ways: 1. Plugging in an investor's personal guess for the real-world probability of a stock rally produces different prices for optimists and pessimists, opening riskless arbitrage against the replicating portfolio. 2. Summing over all 2^n individual paths blows up exponentially (2^50 paths for 50 periods) instead of reusing the (n + 1)(n + 2) / 2 shared nodes of a recombining tree (where "up then down" lands on the same price as "down then up"). 3. Checking American early exercise (the right to exercise at any node before maturity, unlike a European option which can be exercised only at maturity) only at t = 0 misses intermediate crash nodes—such as S = 56.0 at t = 1 in Example 1—where exercising a put early raises its t = 0 value from 9.013 to 9.960.

Walk through a tiny 1-step concrete example (s0 = 80.0, u = 1.2 -> 96.0, d = 0.7 -> 56.0, r = 4%, call strike strike = 80.0 paying 16.0 if up and 0.0 if down): 1. Compute q = (1 + r - d) / (u - d) = (1.04 - 0.70) / (1.20 - 0.70) = 0.68. 2. Discount the q-weighted payoff back one period: (0.68 * 16.0 + 0.32 * 0.0) / 1.04 = 10.88 / 1.04 = 10.4615. 3. Check the replicating basket: buying Delta = (16.0 - 0.0) / (96.0 - 56.0) = 0.4 of a share (32.0 today) and borrowing 21.5385 at 4% (22.4 owed next period) leaves 0.4 * 96.0 - 22.4 = 16.0 if up and 0.4 * 56.0 - 22.4 = 0.0 if down, costing 32.0 - 21.5385 = 10.4615 today—an exact match! The exact same one-step discounting prices zero-coupon bonds (bonds paying a single face amount at maturity with no intermediate interest) and coupon bonds (bonds paying periodic interest coupons plus face value at maturity) on the Part 2 short-rate tree.

Complexity

  • European and American option pricing (roll_back): O(n²) time for n steps, because period t visits t + 1 nodes for t = n, n - 1, ..., 0, totaling (n + 1)(n + 2) / 2 constant-time node updates. Space is O(n) for the rolling 1D values list (plus up to O(n²) output entries if a large fraction of nodes trigger early exercise).
  • Bond pricing on a non-recombining rate tree (bond_price): O(T * 2^T) time for T = len(cash_flows) periods, because a non-recombining binary tree of depth T contains 2^(T + 1) - 1 nodes and constructs a path string of length up to T at each recursive call. Call-stack space is O(T²) (T active stack frames, each holding a path string of length <= T), in addition to the O(2^T) rates dictionary passed in.
  • Yield to maturity (yield_to_maturity): O(T * (B + 100)) = O(T) time and O(1) auxiliary space, where B is the tiny logarithmic number of bracket-expansion steps and each of the 100 bisection steps (repeatedly halving an interval [low, high] where a continuous function crosses the target) evaluates present_value across T cash flows.

Edge cases

  • Arbitrage-allowing tree parameters (d >= 1 + r or u <= 1 + r): q falls outside (0, 1), so risk_neutral_prob raises ValueError rather than returning bogus negative or > 1 weights.
  • Floating-point ties on early exercise (r = 0): when r = 0, an in-the-money non-dividend call has mathematical continuation value S_t - K, equal to immediate exercise. Requiring exercise_value > hold_value + 1e-9 prevents rounding dust like 1e-15 from falsely flagging early exercise.
  • Zero-step options (steps = 0): the backward loop executes zero iterations and returns today's intrinsic payoff with early_nodes = [].
  • Unused terminal short rates (t = 2 rates for a t = 2 bond): in Example 2, a bond maturing at t = 2 depends only on r0 ("") and r1 ("u", "d"); changing "uu", "ud", "du", "dd" leaves its price (924.898) untouched, whereas a t = 3 bond (888.103) does discount through them.
  • Path-dependent short rates ("ud" vs. "du"): "ud" (5%) and "du" (3%) differ, so collapsing states to (t, ups) would misprice 3-period bonds.
  • Extreme or invalid bond prices in yield_to_maturity: non-positive prices (price <= 0) raise ValueError, while valid deep-discount (y > 1000%) or ultra-high-premium (-1 < y < -99%) prices are handled automatically by expanding low toward -1 and doubling high before bisecting.

Common mistakes

  • Using subjective real-world probabilities instead of q: real-world drift cancels out when forming the hedged replicating portfolio; only q = (1 + r - d) / (u - d) prevents arbitrage.
  • Checking American exercise only at t = 0 or using European child values: early exercise at (1, 0) boosts V(1, 0) from 20.923 to 24.000, which must propagate backward into V(0, 0) = 9.960.
  • Reporting 0 == 0 out-of-the-money nodes as "early exercise optimal": exercising for 0 when holding is also 0 (or tying at r = 0) is indifference, not strict optimality.
  • Discounting t = 2 bond cash flows by the t = 2 short rates: rates["uu"] is the rate over [2, 3], not [1, 2]; applying it double-discounts or shifts rates by one period.
  • Replacing random rates [6%, 2%] with their 4% average: discounting 1000 / 1.04² = 924.556 ignores the +0.342 convexity gain (0.5 * (1/1.06 + 1/1.02) > 1/1.04).
  • Flipping the bisection direction in yield_to_maturity: bond price moves inversely with yield (present_value drops when y rises), so present_value(mid) > price means the yield is still too low (low = mid), not too high!

Follow-up questions

  • Under what market conditions can exercising an American call early actually be optimal? Two classic cases break the hold_t > S_t - K proof: (1) dividends—right before an ex-dividend date, the stock price drops by the dividend amount while an unexercised call receives nothing, so exercising early just before a large dividend can capture more cash than the lost interest on K; and (2) negative interest rates (r < 0)—when cash shrinks over time (1 + r < 1), K / (1 + r)^n > K, so paying the strike K now is actually cheaper in present-value terms than paying K later!
  • How do practitioners calibrate the up and down multipliers u and d over short time steps dt? The standard Cox-Ross-Rubinstein (CRR) calibration sets u = exp(sigma * sqrt(dt)) and d = 1 / u = exp(-sigma * sqrt(dt)), where sigma is annualized return volatility, matching the stock's variance sigma² * dt over each tiny step while keeping u * d = 1 centered at s0. As steps -> infinity (dt = T / steps -> 0), the binomial European call price converges smoothly to the continuous-time Black-Scholes formula.
  • How are short-rate trees calibrated to market data, and how would you modify backward induction to price a callable bond? Desks calibrate the node rates at each time slice (using models like Ho-Lee or Black-Derman-Toy) so that bond_price reproduces today's observed market prices of liquid zero-coupon bonds across all maturities. Once calibrated, pricing a callable bond (where the issuer has the right to buy back the bond early at a fixed call price C, say 1020) changes just one line of the backward roll-back: at each callable node before maturity, replace ex_coupon_value with min(ex_coupon_value, call_price), because a rational issuer calls the bond whenever keeping the debt outstanding costs them more than C.

Follow-up questions

Similar questions

More Citibank interview questions

All 2 Citibank questions →