Integral Calculus & Differential Equations in Finance

Michael BrenndoerferOctober 28, 202555 min read

Covers continuous compounding, present value calculations, and differential equations. Essential tools for derivative pricing and financial modeling.

Quantitative FinanceAll chapters
Part 1 of 15Mathematical Foundations
Part 1 of 15Mathematical Foundations
Chapter 7Integral Calculus and Differential Equations › Integral Calculus and Differential Equations
Reading the full chapter · 14 sections · 55 min14 sections · 55 min

Book contents

All 14 sections · 55 min read

Integral Calculus and Differential Equations › Integral Calculus and Differential EquationsFull chapter · Sections in this chapter1 / 14 ↓
Track your reading progress

Sign in to mark sections as read and track your learning journey

Sign in →
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Integral Calculus and Differential Equations

A deposit schedule tells you how quickly money enters an account, but how much arrives over five years? A changing discount curve creates the reverse problem: what is a future cash flow worth today? Integrals turn specified rates into accumulated amounts, while differential equations describe how balances evolve under those rates.

These tools support many continuous-time finance models. For a time-varying instantaneous continuously compounded rate, integrating the rate and exponentiating gives the gross accumulation factor. Differential equations describe models in which asset prices drift and diffuse over time. The Black-Scholes framework, developed later in the book, includes a partial differential equation for an option's model value.

This chapter develops integral calculus and differential equations through financial applications. You will compute accumulated cash flows and continuously compounded growth factors, then model continuous growth, decay, and mean reversion.

The Definite Integral as Accumulation

The definite integral of a rate gives its net accumulated change over an interval. If you know the flow rate through a pipe, integrating it gives the volume that passed through. Similarly, if f(t)f(t) is a financial rate of change in dollars per year, ∫abf(t) dt\int_a^b f(t)\,dt gives the change in dollars. Integrating a balance itself would instead have units of dollar-years, not dollars.

Geometrically, the definite integral equals the signed area under the curve f(t)f(t) between t=at = a and t=bt = b. Areas above the horizontal axis contribute positively, while areas below contribute negatively. This interpretation has direct financial meaning. If f(t)f(t) represents a continuous cash flow rate, the integral gives the total cash accumulated over the period. Positive net flows increase the tracked account's cash balance, while negative flows decrease it. Transfers between your own accounts or loan repayments need not change total net worth by the same amount.

The challenge, of course, is computing these areas precisely when the curve is not a simple geometric shape. This is where the formal definition through Riemann sums becomes essential, and gives a rigorous foundation for calculating accumulated quantities even when the rate of change follows complex patterns.

Definite Integral

For a Riemann-integrable function f(t)f(t) on [a,b][a,b], with a<ba<b, the definite integral is the common limit of its tagged sums. Every continuous function on this closed interval meets this condition:

∫abf(t) dt=lim⁡n→∞∑i=1nf(ti∗)Δt\int_a^b f(t) \, dt = \lim_{n \to \infty} \sum_{i=1}^{n} f(t_i^*) \Delta t

where:

  • [a,b][a, b]: the interval of integration
  • nn: number of subintervals (approaches infinity in the limit)
  • Δt=(b−a)/n\Delta t = (b-a)/n: width of each subinterval
  • ti∗t_i^*: a sample point in the ii-th subinterval
  • f(ti∗)f(t_i^*): value of ff at a sample point in the ii-th subinterval
  • f(ti∗)Δtf(t_i^*)\Delta t: signed area of the approximating rectangle, approximating the integral over the ii-th subinterval

The sum adds these signed rectangle areas. As n→∞n\to\infty, their widths tend to zero and, for a Riemann-integrable function, the sums converge to the same integral regardless of the sample points chosen.

The intuition behind Riemann sums is straightforward: we approximate a complex shape using familiar ones. Just as ancient mathematicians approximated the area of a circle by inscribing polygons with ever more sides, we approximate the area under a curve by filling it with thin rectangles. Each rectangle has width Δt\Delta t and height determined by the function value at some point within that slice. The product f(ti∗)Δtf(t_i^*) \Delta t gives the area of each rectangle, and summing all rectangles approximates the total area. As we use more rectangles (larger nn), each rectangle becomes narrower (Δt\Delta t shrinks), and the sums converge for a Riemann-integrable function, though successive errors need not decrease monotonically.

Out[3]:
Visualization
Five midpoint rectangles approximate a curved deposit-rate function; the panel reports the approximation and signed error.
Midpoint Riemann sum with n=5 rectangles and its signed error.
Ten midpoint rectangles approximate the same curved function with a smaller absolute error.
Midpoint Riemann sum with n=10 rectangles and its signed error.
Twenty midpoint rectangles approximate the same curved function with a still smaller absolute error.
Midpoint Riemann sum with n=20 rectangles and its signed error.

For a continuous ff on [a,b][a,b], the Fundamental Theorem of Calculus connects differentiation and integration: differentiating the accumulation function ∫atf(s) ds\int_a^t f(s)\,ds recovers f(t)f(t). Integrating a derivative instead recovers the original function's change; an indefinite antiderivative is determined only up to an additive constant. If F′(t)=f(t)F'(t)=f(t), then:

∫abf(t) dt=F(b)−F(a)\int_a^b f(t) \, dt = F(b) - F(a)

This theorem turns the problem of computing integrals into finding antiderivatives, which is often more tractable than evaluating limits of sums directly. Rather than computing an infinite limit of rectangle sums, we can simply find a function whose derivative equals our integrand, then evaluate the difference at the endpoints. This is why antiderivative tables and integration techniques are so useful: they provide shortcuts to what would otherwise require tedious limiting arguments.

A Financial Interpretation

Consider a savings account with a time-varying deposit rate d(t)d(t) measured in dollars per year. This rate might change because your income grows over time, or because you commit to increasing your contributions annually. Over a small time interval Δt\Delta t, you deposit approximately d(t)⋅Δtd(t) \cdot \Delta t dollars, the rate times the duration. To find the total amount deposited from time 00 to time TT, we must sum all these infinitesimal contributions, which is precisely what the integral computes:

Total Deposits=∫0Td(t) dt\text{Total Deposits} = \int_0^T d(t) \, dt

If d(t)=1000+100td(t)=1000+100t dollars per year, with tt in years, the deposit rate increases continuously by $100 per year for each elapsed year. Over five years:

∫05(1000+100t) dt=[1000t+50t2]05=5000+1250=6250\int_0^5 (1000 + 100t) \, dt = \left[ 1000t + 50t^2 \right]_0^5 = 5000 + 1250 = 6250

You would deposit a total of $6,250 over the five-year period. Notice how the antiderivative 1000t+50t21000t + 50t^2 captures both the base contribution (1000t1000t) and the cumulative effect of the increasing contributions (50t250t^2). The Fundamental Theorem lets us compute this by simple evaluation rather than summing five years of daily deposits.

In[4]:
Code
from scipy import integrate


# Define the deposit rate function
def deposit_rate(t):
    return 1000 + 100 * t


# Compute the integral numerically
total_deposits, error = integrate.quad(deposit_rate, 0, 5)
Out[5]:
Console
Total deposits over 5 years: $6,250.00
Numerical integration error estimate: $6.94e-11

The numerical result confirms our analytical calculation. The scipy.integrate.quad function uses adaptive QUADPACK routines and returns an error estimate. Requested tolerances and the subdivision limit constrain the algorithm. Integrand behavior and problem conditioning also matter, as does floating-point arithmetic.

Continuous Compounding and the Exponential Function

Continuous compounding is an important application of integral calculus in finance. Interest accrual, compounding, and scheduled crediting depend on the contract. Continuous compounding supplies a mathematical convention for the models below.

Discrete compounding at a constant nominal annual rate rr, nn times per year for tt years, gives the following value at compounding dates, where ntnt is an integer:

FV=PV⋅(1+rn)n⋅tFV = PV \cdot \left(1 + \frac{r}{n}\right)^{n \cdot t}

Each completed period credits interest at rate r/nr/n. The comparison below fixes this nominal quote as frequency changes; between credit dates, its curves use fractional-power interpolation, not continuous crediting. As the compounding frequency nn increases, moving from annual to quarterly to daily to hourly, this expression approaches a limit. Taking n→∞n \to \infty yields continuous compounding:

FV=PV⋅ertFV = PV \cdot e^{rt}

where:

  • FVFV: future value of the investment
  • PVPV: present value (initial investment)
  • e≈2.71828e \approx 2.71828: Euler's number, the base of natural logarithms
  • rr: continuously compounded annual rate in erte^{rt}; the preceding discrete formula uses the same number as a nominal annual quote, not an effective annual return
  • tt: time in years

The exponential appears because the balance changes in proportion to its current value at a constant rate. A positive rate produces growth, zero rate leaves the balance constant, and a negative rate produces decay. The continuous formula is a limit of multiplicative discrete factors, not literal infinitely frequent contractual payments.

Every solution of y′=kyy'=ky with constant kk has the form y(t)=Aekty(t)=A e^{kt}. An initial value fixes AA; in particular, ete^t solves y′=yy'=y with y(0)=1y(0)=1.

Deriving Continuous Compounding from an Integral

Let's derive the formula for a positive initial balance V0V_0 and constant continuously compounded rate rr. The balance V(t)V(t) changes at rate rr times its current value, growing for r>0r>0 and shrinking for r<0r<0:

dVdt=rV(t)\frac{dV}{dt} = rV(t)

where:

  • V(t)V(t): account value at time tt
  • dVdt\frac{dV}{dt}: instantaneous rate of change of account value
  • rr: continuous interest rate
  • r⋅V(t)r \cdot V(t): interest earned per unit time, proportional to current balance

Solving this differential equation gives an exponential family; the initial balance selects one path. On the positive-balance branch, separation of variables moves the VV and tt terms to opposite sides:

dVV=r dt\frac{dV}{V} = r \, dt

Integrating both sides:

∫dVV=∫r dt\int \frac{dV}{V} = \int r \, dt ln⁡∣V∣=rt+C\ln|V| = rt + C

Here CC is the integration constant. Because we assumed a positive balance, exponentiating ln⁡∣V∣\ln|V| gives VV, rather than −V-V:

V(t)=ert+C=eC⋅ertV(t) = e^{rt + C} = e^C \cdot e^{rt}

Setting t=0t = 0 and letting V(0)=V0V(0) = V_0 be the initial value:

V0=eC⋅e0=eCV_0 = e^C \cdot e^0 = e^C

Therefore, eC=V0e^C = V_0, and the solution is:

V(t)=V0⋅ertV(t) = V_0 \cdot e^{rt}

The final formula also solves the ODE directly for zero or negative initial values; V0=0V_0=0 gives the separate equilibrium V(t)=0V(t)=0. With a time-varying deterministic coefficient, y′=k(t)yy'=k(t)y instead gives y(t)=y(0)exp⁡(∫0tk(s) ds)y(t)=y(0)\exp(\int_0^t k(s)\,ds). Random shocks require a stochastic model rather than this ODE alone.

In[6]:
Code
import numpy as np

# Compare discrete vs continuous compounding
principal = 1000
rate = 0.05  # 5% annual rate
years = np.linspace(0, 20, 100)

# Continuous compounding
continuous_value = principal * np.exp(rate * years)

# Discrete compounding at various frequencies
annual_value = principal * (1 + rate) ** years
quarterly_value = principal * (1 + rate / 4) ** (4 * years)
monthly_value = principal * (1 + rate / 12) ** (12 * years)
daily_value = principal * (1 + rate / 365) ** (365 * years)
Out[7]:
Visualization
Line chart showing investment value over 20 years under annual, quarterly, monthly, daily, and continuous compounding.
Comparison of investment growth under different compounding frequencies. Continuous compounding provides the highest return, though the difference from daily compounding is negligible.

The plot demonstrates that as compounding frequency increases, the investment value approaches the continuous compounding limit. After 20 years at 5% interest, the final values illustrate the practical differences:

Out[8]:
Console
After 20 years at 5% annual rate:
  Annual compounding:     $2,653.30
  Quarterly compounding:  $2,701.48
  Monthly compounding:    $2,712.64
  Daily compounding:      $2,718.10
  Continuous compounding: $2,718.28

While the difference between daily and continuous compounding is small (about $0.19 on a $1,000 investment over 20 years), continuous compounding provides mathematical elegance that simplifies many calculations in quantitative finance.

Integration Techniques for Finance

The following examples use several integration techniques. They are useful when a model lacks a convenient antiderivative. We begin with substitutions and products before turning to numerical integration.

Integration by Substitution

Integration by substitution reverses the chain rule of differentiation, allowing us to simplify integrals by changing variables. The core insight is that a complex integrand might become simple under the right transformation. If g(t)g(t) is a differentiable function and ff is continuous, then:

∫f(g(t))⋅g′(t) dt=∫f(u) du\int f(g(t)) \cdot g'(t) \, dt = \int f(u) \, du

where u=g(t)u = g(t).

The power of substitution lies in recognizing when an integrand contains a function and its derivative: the signature of the chain rule applied in reverse. When we spot this pattern, we can simplify the integral by treating the inner function as a new variable.

Consider pricing a bond with continuous coupon payments where the coupon rate decays exponentially. This structure might arise when modeling a company whose cash flows are expected to decline over time. If the coupon rate at time tt is C(t)=C0e−αtC(t) = C_0 e^{-\alpha t} and the discount factor is D(t)=e−rtD(t) = e^{-rt}, we need to compute the present value of this decaying stream of payments:

PV=∫0TC0e−αt⋅e−rt dtPV = \int_0^T C_0 e^{-\alpha t} \cdot e^{-rt} \, dt

where:

  • C0C_0: initial coupon cash-flow rate at t=0t=0, in currency per year
  • α\alpha: decay rate of the coupon (how fast it decreases)
  • rr: risk-free discount rate
  • TT: maturity time

The present value of coupons from 00 to TT is:

PV=∫0TC0e−αt⋅e−rt dt=C0∫0Te−(r+α)t dtPV = \int_0^T C_0 e^{-\alpha t} \cdot e^{-rt} \, dt = C_0 \int_0^T e^{-(r+\alpha)t} \, dt

Here we used ea⋅eb=ea+be^a \cdot e^b=e^{a+b} to combine the exponentials. When r+α≠0r+\alpha\ne0, substitution with u=−(r+α)tu=-(r+\alpha)t gives the first branch below. At r+α=0r+\alpha=0, the integrand is the constant C0C_0:

PV={C0r+α(1−e−(r+α)T),r+α≠0,C0T,r+α=0.PV=\begin{cases}\dfrac{C_0}{r+\alpha}\left(1-e^{-(r+\alpha)T}\right),&r+\alpha\ne0,\\[6pt]C_0T,&r+\alpha=0.\end{cases}

For the usual nonnegative discount and decay rates, r+αr+\alpha combines the two forces that reduce future coupon value. For C0>0C_0>0, the finite perpetuity limit C0/(r+α)C_0/(r+\alpha) exists only when r+α>0r+\alpha>0. At equality the value grows linearly as C0TC_0T; when r+α<0r+\alpha<0, it grows exponentially rather than converging. A zero stream has value zero for every rate.

Integration by Parts

Integration by parts reverses the product rule, enabling us to integrate products of functions by transferring the derivative from one factor to another. This technique is especially valuable when one function becomes simpler upon differentiation while the other has a known antiderivative. For continuously differentiable functions u(t)u(t) and v(t)v(t):

∫u dv=uv−∫v du\int u \, dv = uv - \int v \, du

where:

  • uu: a function chosen to simplify when differentiated
  • vv: an antiderivative of the factor represented by dvdv, so dv=v′(t) dtdv=v'(t)\,dt
  • dvdv: the differential of vv
  • dudu: the differential of uu

The strategy is to choose uu and dvdv so that ∫v du\int v \, du is simpler than the original integral. A useful mnemonic for choosing uu is LIATE (Logarithmic, Inverse trigonometric, Algebraic, Trigonometric, Exponential), which suggests the order of preference for what to differentiate.

This technique is important when integrating products, especially in option pricing where payoffs multiply probability densities. When computing expected values, we often encounter integrals of the form ∫x⋅f(x) dx\int x \cdot f(x) \, dx, where f(x)f(x) is some probability density.

For an option-pricing application, let FF and pp be the CDF and density of a nonnegative terminal price STS_T. Provided the expectation is finite and (s−K)[1−F(s)]→0(s-K)[1-F(s)]\to0 as s→∞s\to\infty, integration by parts turns a call's expected payoff into a tail-probability integral. Choose

u=s−K,dv=p(s) ds,du=ds,v=F(s)−1.u=s-K,\qquad dv=p(s)\,ds,\qquad du=ds,\qquad v=F(s)-1.

Then the boundary term is explicit:

E[(ST−K)+]=∫K∞(s−K)p(s) ds=[(s−K)(F(s)−1)]K∞+∫K∞[1−F(s)] ds=∫K∞[1−F(s)] ds.\begin{aligned} E[(S_T-K)^+] &=\int_K^\infty (s-K)p(s)\,ds\\ &=\left[(s-K)(F(s)-1)\right]_K^\infty +\int_K^\infty [1-F(s)]\,ds\\ &=\int_K^\infty [1-F(s)]\,ds. \end{aligned}

Consider computing the expected payoff of a call option under a uniform distribution (a simplified model for illustration). If the stock price STS_T at expiration is uniformly distributed on [80,120][80, 120] with strike K=100K = 100, the expected payoff is:

E[max⁡(ST−K,0)]=∫100120(ST−100)⋅140 dSTE[\max(S_T - K, 0)] = \int_{100}^{120} (S_T - 100) \cdot \frac{1}{40} \, dS_T

Direct integration gives the same value as integrating the uniform survival function (120−s)/40(120-s)/40 from 100 to 120:

=140[(ST−100)22]100120=140⋅4002=5= \frac{1}{40} \left[ \frac{(S_T - 100)^2}{2} \right]_{100}^{120} = \frac{1}{40} \cdot \frac{400}{2} = 5
In[9]:
Code
from scipy import integrate


# Expected call option payoff under uniform distribution
def call_payoff_density(s, strike=100, lower=80, upper=120):
    """Payoff times probability density for uniform distribution."""
    if not np.isfinite([lower, upper, strike]).all() or upper <= lower:
        raise ValueError("Require finite bounds and strike, with upper > lower")
    if s < lower or s < strike or s > upper:
        return 0
    return (s - strike) * (1 / (upper - lower))


expected_payoff, _ = integrate.quad(call_payoff_density, 80, 120)
Out[10]:
Console
Expected call option payoff: $5.00
Out[11]:
Visualization
Plot of the probability-weighted call payoff, shaded between stock prices 100 and 120; the shaded area integrates to an expected payoff of 5 dollars.
Expected call option payoff under a uniform distribution. The shaded area represents the probability-weighted payoff that integrates to the expected value of $5.

The Gaussian Integral

The Gaussian integral is fundamental to quantitative finance because normal distributions appear throughout risk modeling and option pricing. Some mean-variance analyses assume normal arithmetic returns; the mean-variance criterion itself uses means and covariances rather than requiring normality. Under Black-Scholes, continuously compounded (log) returns are normal and terminal prices are lognormal; other option models need not use normal returns. In each normal-model setting, we encounter integrals involving the exponential of a quadratic. The basic Gaussian integral states:

∫−∞∞e−x2 dx=π\int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}

For this particular unnormalized Gaussian, the area is π\sqrt{\pi}; changing its height or width changes that area. One derivation squares the integral and integrates e−(x2+y2)e^{-(x^2+y^2)} over the plane. Polar coordinates give 2π∫0∞ρe−ρ2 dρ=π2\pi\int_0^\infty \rho e^{-\rho^2}\,d\rho=\pi, so the positive original integral is π\sqrt{\pi}.

More generally, for the standard normal density:

∫−∞∞12πe−x2/2 dx=1\int_{-\infty}^{\infty} \frac{1}{\sqrt{2\pi}} e^{-x^2/2} \, dx = 1

This integral equals 1 because it represents the total probability under the standard normal density. A probability density, when one exists, integrates to 1. Discrete probability masses are normalized by summation; more generally, a probability measure assigns total mass 1 to its sample space. The factor 1/2π1/\sqrt{2\pi} is precisely the normalization constant that ensures this property.

The cumulative distribution function of the standard normal:

Φ(z)=∫−∞z12πe−t2/2 dt\Phi(z) = \int_{-\infty}^{z} \frac{1}{\sqrt{2\pi}} e^{-t^2/2} \, dt

where:

  • Φ(z)\Phi(z): cumulative distribution function (CDF) of the standard normal distribution
  • zz: upper limit of integration, representing the number of standard deviations
  • tt: dummy variable of integration
  • 12πe−t2/2\frac{1}{\sqrt{2\pi}} e^{-t^2/2}: the standard normal probability density function

has no expression in elementary functions. It can be written with the special function erf⁡\operatorname{erf} as Φ(z)=12[1+erf⁡(z/2)]\Phi(z)=\tfrac12[1+\operatorname{erf}(z/\sqrt2)] and is evaluated numerically in practice. It appears directly in the Black-Scholes formula for option pricing, where call and put prices are expressed in terms of Φ(d1)\Phi(d_1) and Φ(d2)\Phi(d_2).

Out[12]:
Visualization
Standard normal PDF with shaded tail regions.
Standard normal PDF showing key probability thresholds used in risk management.
S-shaped CDF curve.
Standard normal CDF showing cumulative probabilities.
Out[14]:
Console
Standard Normal CDF Values:
------------------------------
  Φ(-2) = 0.022750
  Φ(-1) = 0.158655
  Φ( 0) = 0.500000
  Φ( 1) = 0.841345
  Φ( 2) = 0.977250

The value Φ(−2)≈0.023\Phi(-2) \approx 0.023 means that a standard normal variable falls below −2-2 with probability about 2.3%. Under a model in which a return is normal and has been standardized by subtracting its mean and dividing by its standard deviation, this is the model probability of a return more than two standard deviations below its mean.

Present Value and the Yield Curve

An important application of integration in finance is computing present values when interest rates vary over time. In the real world, interest rates are not constant. Short-term rates typically differ from long-term rates, creating a term structure that may be quoted as par yields, zero or spot rates, forward rates, or discount factors. The integration formula below applies directly to the instantaneous forward curve. A continuously compounded zero rate maps directly to a discount factor, while par yields must first be transformed into zero rates or forward rates.

A specified instantaneous forward curve determines the discount factors used in these cash-flow models. Slope alone does not determine a discount factor: the upward-sloping forward curve and flat curve below have identical ten-year discount factors, even though they differ at other maturities. The integral uses the full curve up to the chosen maturity.

Continuous Discounting with Time-Varying Rates

For a time-zero term structure, let f(0,t)f(0,t) denote the instantaneous forward rate for maturity tt. We can no longer apply e−rTe^{-rT} with one constant rate. Instead, the discount factor from time 00 to time TT integrates the forward curve across maturities:

D(0,T)=exp⁡(−∫0Tf(0,s) ds)D(0, T) = \exp\left( -\int_0^T f(0,s) \, ds \right)

where:

  • D(0,T)D(0, T): discount factor from time 00 to time TT
  • f(0,s)f(0,s): time-zero instantaneous forward rate for maturity ss
  • ss: dummy variable indexing maturity
  • ∫0Tf(0,s) ds\int_0^T f(0,s) \, ds: accumulated continuously compounded forward rates through maturity TT

The corresponding continuously compounded TT-maturity spot, or zero, rate is the maturity average

R(0,T)=−log⁡D(0,T)T=1T∫0Tf(0,s) ds.R(0,T)=-\frac{\log D(0,T)}{T}=\frac{1}{T}\int_0^T f(0,s)\,ds.

Thus an instantaneous forward rate, a maturity-specific spot rate, and a future short rate are distinct objects. The same exponential formula can integrate a deterministic future short-rate path, but such a path is a model assumption rather than the observed time-zero spot curve.

Discount Factor

The discount factor D(0,T)D(0, T) represents the present value of $1 to be received at time TT. For T>0T>0, a positive accumulated forward rate gives D(0,T)<1D(0,T)<1. At time zero the factor is one; negative accumulated rates can produce a factor above one.

Consider a time-zero instantaneous forward curve that starts at 3% and increases linearly to 5% at a 10-year maturity:

f(0,t)=0.03+0.002tf(0,t) = 0.03 + 0.002t

This is an illustrative upward-sloping term structure, not a causal account of why the curve slopes upward. The discount factor for a 10-year cash flow is:

D(0,10)=exp⁡(−∫010(0.03+0.002t) dt)D(0, 10) = \exp\left( -\int_0^{10} (0.03 + 0.002t) \, dt \right)

Computing the integral:

∫010(0.03+0.002t) dt=[0.03t+0.001t2]010=0.3+0.1=0.4\int_0^{10} (0.03 + 0.002t) \, dt = \left[ 0.03t + 0.001t^2 \right]_0^{10} = 0.3 + 0.1 = 0.4

Therefore:

D(0,10)=e−0.4≈0.6703D(0, 10) = e^{-0.4} \approx 0.6703

A cash flow of $1,000 in ten years has a present value of approximately $670.32. Its maturity-specific zero rate is R(0,10)=10−1∫010f(0,s) ds=4%R(0,10)=10^{-1}\int_0^{10}f(0,s)\,ds=4\%, so the flat-4% factor agrees exactly at this maturity: e−R(0,10)10=e−0.4e^{-R(0,10)10}=e^{-0.4}. This identity holds for any integrable forward curve; linearity makes the average easy to calculate. One maturity average does not determine discount factors at other maturities.

In[15]:
Code
import numpy as np
from scipy import integrate


def instantaneous_forward(t):
    """Time-zero forward curve: f(0,t) = 3% + 0.2% per year."""
    return 0.03 + 0.002 * t


def discount_factor(T):
    """Compute discount factor from 0 to T under time-varying rates."""
    integral, _ = integrate.quad(instantaneous_forward, 0, T)
    return np.exp(-integral)


# Calculate discount factors for various maturities
maturities = np.array([1, 2, 5, 10, 20, 30])
discount_factors = np.array([discount_factor(T) for T in maturities])
Out[16]:
Console
Discount Factors Under Upward-Sloping Yield Curve:
---------------------------------------------
Maturity (years)     Discount Factor PV of $1000    
---------------------------------------------
1                    0.969476        $969.48        
2                    0.938005        $938.00        
5                    0.839457        $839.46        
10                   0.670320        $670.32        
20                   0.367879        $367.88        
30                   0.165299        $165.30

The discount factors decrease with maturity because the accumulated rate increases. Relative to a flat 4% curve, the time-varying factor is higher for 0<T<100<T<10, equal at T=10T=10, and lower for T>10T>10; a global claim that its decline always accelerates would be incorrect.

Out[17]:
Visualization
Linear instantaneous forward curve increasing from 3% to 9%, with the zero rate increasing from 3% to 6%.
The instantaneous forward curve f(0,t) and its maturity-dependent zero-rate curve R(0,T).
Discount factors under f(0,t) = 3% + 0.2% times t and a flat 4% rate, crossing at the 10-year maturity.
Compared with a flat 4% curve, the time-varying discount factor is higher for maturities between 0 and 10 years, equal at 10 years, and lower after 10 years.

Pricing a Bond with Continuous Coupons

Consider a bond paying continuous coupon at rate cc per year on a principal of PP, maturing at time TT. Coupon bonds normally pay on discrete dates. A continuous-coupon stream is a simplifying model and can approximate a sufficiently frequent payment schedule when the coupon timing and discount curve are smooth. The present value combines the stream of coupons and the principal repayment:

PV=∫0Tc⋅P⋅D(0,t) dt+P⋅D(0,T)PV = \int_0^T c \cdot P \cdot D(0, t) \, dt + P \cdot D(0, T)

where:

  • PVPV: present value of the bond
  • cc: continuous coupon rate (per year)
  • PP: principal (face value)
  • TT: maturity time
  • D(0,t)D(0, t): discount factor from time 00 to time tt

The first term captures the present value of all coupon payments: at each instant tt, the bond pays c⋅Pc \cdot P per year, and this payment is discounted back to today using D(0,t)D(0, t). The second term is the present value of the principal repayment at maturity.

With our upward-sloping instantaneous forward curve:

In[18]:
Code
def bond_price(principal, coupon_rate, maturity):
    """Price a bond with continuous coupons under time-varying rates."""

    # Present value of coupon stream
    def coupon_pv_integrand(t):
        return coupon_rate * principal * discount_factor(t)

    coupon_pv, _ = integrate.quad(coupon_pv_integrand, 0, maturity)

    # Present value of principal
    principal_pv = principal * discount_factor(maturity)

    return coupon_pv + principal_pv


# Price a 10-year bond with 4% coupon
principal = 1000
coupon_rate = 0.04
maturity = 10

price = bond_price(principal, coupon_rate, maturity)
Out[19]:
Console
Bond Parameters:
  Principal: $1,000
  Coupon rate: 4.0%
  Maturity: 10 years

Bond Price: $1,005.54
  Coupon PV: $335.22
  Principal PV: $670.32

The bond is slightly above par, at about $1,005.54. Its cumulative average forward rate R(0,t)=0.03+0.001tR(0,t)=0.03+0.001t is below 4% for every 0<t<100<t<10, equaling 4% at maturity. Thus each earlier coupon has a larger discount factor than under the flat-4% continuous-coupon bond, while principal has the same factor. The instantaneous forward itself is below 4% only during the first five years.

Ordinary Differential Equations in Finance

Differential equations describe relationships between quantities and their rates of change. Algebraic equations relate values directly, while differential equations relate a function to its derivatives and state the rules its path must satisfy. In finance, they model how portfolios, prices, and economic variables evolve over time, capturing the dynamic nature of markets and economies.

Differential equations encode rules of change that, when solved, reveal the trajectory of a system. If we know that interest rates revert toward a long-term mean, or that a portfolio grows proportionally to its value plus deposits, we can express these dynamics as differential equations and solve for the resulting paths.

First-Order Linear ODEs

A first-order linear ordinary differential equation has the form:

dydt+P(t)y=Q(t)\frac{dy}{dt} + P(t) y = Q(t)

The term "first-order" means the equation involves only the first derivative of yy, not higher derivatives. "Linear" means yy and its derivative appear only to the first power and are not multiplied together. On an interval where PP and QQ are continuous (or satisfy suitable integrability conditions), an integrating factor gives the general solution.

The general solution uses an integrating factor μ(t)=e∫P(t)dt\mu(t) = e^{\int P(t) dt}:

y(t)=1μ(t)[∫μ(t)Q(t) dt+C]y(t) = \frac{1}{\mu(t)} \left[ \int \mu(t) Q(t) \, dt + C \right]

where:

  • y(t)y(t): the unknown function we are solving for
  • P(t)P(t): coefficient function multiplying yy
  • Q(t)Q(t): forcing function (the non-homogeneous term)
  • μ(t)=e∫P(t)dt\mu(t) = e^{\int P(t) dt}: integrating factor that makes the left side a perfect derivative
  • CC: constant of integration, determined by initial conditions

The integrating factor works because multiplying by μ(t)\mu(t) converts the left side into ddt[μ(t)y]\frac{d}{dt}[\mu(t) y], allowing direct integration. This technique appears frequently in differential equations. By multiplying through by just the right function, we transform a seemingly intractable equation into one we can solve by straightforward integration.

Example: Portfolio Growth with Continuous Deposits

Suppose you have a portfolio earning continuous return rr and you make continuous deposits at rate DD per year. This models a retirement account where you contribute regularly while earning investment returns. The portfolio value V(t)V(t) satisfies:

dVdt=rV+D\frac{dV}{dt} = rV + D

This equation says: the rate of change of your portfolio equals the investment return (rVrV, proportional to what you have) plus your deposits (DD, a constant flow). This is a first-order linear ODE with P(t)=−rP(t) = -r and Q(t)=DQ(t) = D. The integrating factor is μ(t)=e−rt\mu(t) = e^{-rt}.

Multiplying both sides by μ(t)\mu(t):

e−rtdVdt−re−rtV=De−rte^{-rt} \frac{dV}{dt} - r e^{-rt} V = D e^{-rt}

The left side is the derivative of e−rtVe^{-rt} V:

ddt(e−rtV)=De−rt\frac{d}{dt}\left( e^{-rt} V \right) = D e^{-rt}

This is the key insight: what looked like two separate terms is a single derivative. For r≠0r \ne 0, we can integrate directly:

e−rtV=−Dre−rt+Ce^{-rt} V = -\frac{D}{r} e^{-rt} + C V(t)=Cert−DrV(t) = Ce^{rt} - \frac{D}{r}

With initial condition V(0)=V0V(0) = V_0:

V0=C−Dr  ⟹  C=V0+DrV_0 = C - \frac{D}{r} \implies C = V_0 + \frac{D}{r}

For r≠0r \ne 0, the solution is:

V(t)=(V0+Dr)ert−Dr=V0ert+Dr(ert−1)V(t) = \left( V_0 + \frac{D}{r} \right) e^{rt} - \frac{D}{r} = V_0 e^{rt} + \frac{D}{r}\left( e^{rt} - 1 \right)

The first term represents growth of the initial investment, while the second represents accumulated deposits with their earned interest. This decomposition is intuitive. Your wealth at any time is the sum of what your original stake has grown to, plus what your contributions have accumulated.

For r>0r>0, D/rD/r is the time-zero value of a perpetual continuous cash-flow rate DD discounted continuously at rate rr. In the finite-horizon accumulation formula, the stable term is D expm1⁡(rt)/rD\,\operatorname{expm1}(rt)/r. Its continuous limit at r=0r=0 is DtDt, so the zero-rate solution is V(t)=V0+DtV(t)=V_0+Dt rather than a division by zero.

In[20]:
Code
import numpy as np


def portfolio_value(t, V0, r, D):
    """Analytical solution for portfolio with continuous deposits."""
    return V0 + D * t if r == 0 else V0 * np.exp(r * t) + D * np.expm1(r * t) / r


# Parameters
V0 = 10000  # Initial investment
r = 0.07  # 7% annual return
D = 6000  # $6,000 annual deposits

t = np.linspace(0, 30, 300)
V = portfolio_value(t, V0, r, D)

# Components
growth_component = V0 * np.exp(r * t)
deposit_component = portfolio_value(t, 0, r, D)
Out[21]:
Visualization
Stacked area chart showing portfolio value split between initial investment growth and deposit accumulation over 30 years.
Portfolio growth over 30 years from the initial investment and continuous deposits. For these parameters, repeated deposits and their accumulated interest form the larger component; both components earn the same return.
Out[22]:
Console
After 30 years:
  Initial investment: $10,000
  Total deposits: $180,000
  Final portfolio value: $695,904.83
  Investment gain: $505,904.83

The power of compounding is evident: starting with $10,000 and depositing $6,000 per year, the portfolio grows to over $600,000 after 30 years, with investment gains far exceeding the total contributions.

Numerical Solution of ODEs

Numerical methods can compute trajectories when a convenient known closed form is unavailable. Time-varying coefficients and nonlinearity do not automatically prevent analytical solutions. The examples below also use numerical evaluation when a benchmark formula is known. The SciPy function odeint wraps LSODA and uses requested local-error tolerances; success does not guarantee a chosen global error. SciPy recommends solve_ivp for new code.

Example: Mean-Reverting Interest Rates

The constant-parameter Vasicek model is the stochastic differential equation drt=κ(θ−rt)dt+σrdWtdr_t=\kappa(\theta-r_t)dt+\sigma_r dW_t. Assume κ>0\kappa>0 for mean reversion. The ODE below retains only its drift and also governs the conditional mean m(t)=E[rt∣r0]m(t)=\mathbb{E}[r_t\mid r_0]:

dmdt=κ(θ−m)\frac{dm}{dt} = \kappa(\theta - m)

where:

  • mm: deterministic drift trajectory, equivalently the conditional mean rate at time tt
  • κ>0\kappa>0: speed of mean reversion (larger positive values mean faster reversion)
  • θ\theta: long-term mean interest rate
  • σr\sigma_r: short-rate volatility in the full SDE; dWtdW_t is a Brownian increment

Mean reversion is a modeling assumption, not a claim that central banks or arbitrage impose hard bounds. In the drift ODE, m>θm>\theta gives a negative derivative and m<θm<\theta gives a positive derivative; larger κ\kappa means faster convergence of the conditional mean. For positive elapsed time and nonzero volatility, the constant-parameter Vasicek rate has a nondegenerate Gaussian law with support on the entire real line. At time zero or zero volatility, its conditional law is degenerate instead.

This conditional-mean ODE has the analytical solution m(t)=θ+(r0−θ)e−κtm(t)=\theta+(r_0-\theta)e^{-\kappa t}, but we solve it numerically to demonstrate the technique:

In[23]:
Code
import numpy as np
from scipy.integrate import odeint


def vasicek_drift(r, t, kappa, theta):
    """Drift term of Vasicek model (deterministic part)."""
    return kappa * (theta - r)


# Model parameters
kappa = 0.5  # Mean reversion speed
theta = 0.05  # Long-term mean (5%)

# Solve for different starting rates
t = np.linspace(0, 10, 100)
r0_values = [0.02, 0.05, 0.08]  # Starting rates

solutions = {}
for r0 in r0_values:
    solutions[r0] = odeint(vasicek_drift, r0, t, args=(kappa, theta)).flatten()
Out[24]:
Visualization
Three deterministic Vasicek drift or conditional-mean trajectories approaching 5% from initial rates of 2%, 5%, and 8%; these are not simulated stochastic paths.
Deterministic solutions of the Vasicek drift ODE, equivalently conditional-mean trajectories of the constant-parameter Vasicek SDE. Starting means above or below 5% approach 5% over time.

The mean reversion parameter κ=0.5\kappa = 0.5 implies a half-life of ln⁡(2)/κ≈1.4\ln(2)/\kappa \approx 1.4 years: after about 1.4 years, the conditional mean's deviation has halved, not every individual stochastic path's deviation.

Out[25]:
Console
Mean reversion speed (kappa): 0.5
Long-term mean (theta): 5.0%
Half-life of deviation: 1.39 years

Separation of Variables and Financial Models

For y′=h(t)g(y)y'=h(t)g(y), separation writes dy/g(y)=h(t) dtdy/g(y)=h(t)\,dt on intervals where g(y)≠0g(y)\ne0. Integrating that branch does not recover excluded equilibrium solutions, which must be checked in the original equation.

Geometric Brownian Motion (Deterministic Part)

The deterministic component of the geometric Brownian motion model for stock prices is:

dSdt=μS\frac{dS}{dt} = \mu S

where:

  • SS: stock price at time tt
  • μ\mu: drift rate (expected return per unit time)
  • dSdt\frac{dS}{dt}: rate of change of stock price

For the positive-price branch S0>0S_0>0, the proportionality to SS means percentage changes are constant: a $100 stock and a $200 stock both grow at the same percentage rate μ\mu. Percentage returns make changes comparable across scales, while dollar profit and loss still matter for position sizing, liabilities, and risk limits. A $10 gain on a $100 stock is a 10% return, whereas the same dollar gain on a $1,000 stock is a 1% return. Separating variables:

dSS=μ dt\frac{dS}{S} = \mu \, dt

Integrating:

ln⁡S=μt+C\ln S = \mu t + C S(t)=S0eμtS(t) = S_0 e^{\mu t}

Under the geometric Brownian motion convention dSt=μStdt+σStdWtdS_t=\mu S_tdt+\sigma S_tdW_t, this deterministic solution equals the conditional mean E[St∣S0]=S0eμt\mathbb{E}[S_t\mid S_0]=S_0e^{\mu t}. It is not a path that individual prices oscillate or mean-revert around. Log-price variance is σ2t\sigma^2t, and variance relative to the squared mean is eσ2t−1e^{\sigma^2t}-1, so these measures increase for nonzero σ\sigma. Absolute price variance need not increase for negative μ\mu. Deviations do not experience a restoring force.

Out[26]:
Visualization
Three exponential GBM conditional-mean curves from an initial price of 100; stochastic paths disperse rather than oscillate around these curves.
Deterministic ODE solutions for drift rates of 5%, 10%, and 15%. Under the GBM drift convention, each curve is the conditional mean E[S_t | S_0], not a mean-reversion path for individual prices.

Decay Models: Asset Depreciation

Many vehicles and pieces of equipment lose economic value with age and use, although some physical assets can appreciate. A simple depreciation model assumes value declines in proportion to its current level:

dVdt=−δV\frac{dV}{dt} = -\delta V

where:

  • VV: asset value at time tt
  • δ\delta: constant continuous decay rate, in inverse years; its finite one-year loss fraction is 1−e−δ1-e^{-\delta}
  • −δV-\delta V: negative because value decreases over time

Assets sharing a proportional decay rate lose the same percentage over a fixed interval, while a larger starting value gives a larger dollar loss. A discrete 15% annual loss removes $4,500 from $30,000 or $2,250 from $15,000. In the continuous model that annual loss corresponds to δ=−ln⁡(0.85)≈0.16252\delta=-\ln(0.85)\approx0.16252 per year, not δ=0.15\delta=0.15. The latter gives a one-year loss of about 13.93%. The continuous ODE has solution:

V(t)=V0e−δtV(t) = V_0 e^{-\delta t}

where V0V_0 is the initial asset value at t=0t = 0.

For V0>0V_0>0 and δ>0\delta>0, the asset value decays exponentially, with half-life t1/2=ln⁡(2)/δt_{1/2} = \ln(2)/\delta. The half-life formula follows directly from solving V0e−δt1/2=V0/2V_0 e^{-\delta t_{1/2}} = V_0/2, which gives e−δt1/2=1/2e^{-\delta t_{1/2}} = 1/2 and thus t1/2=ln⁡(2)/δt_{1/2} = \ln(2)/\delta. Zero value is a separate equilibrium; zero decay has no finite halving time. The following rates are illustrative continuous parameters, not estimated asset-class depreciation rates.

In[27]:
Code
import numpy as np

# Compare depreciation rates
V0 = 100000  # Initial asset value ($100,000)
depreciation_rates = {
    "Equipment (20%/year)": 0.20,
    "Vehicle (15%/year)": 0.15,
    "Building (3%/year)": 0.03,
}

t = np.linspace(0, 30, 300)

asset_values = {}
for name, delta in depreciation_rates.items():
    asset_values[name] = V0 * np.exp(-delta * t)
Out[28]:
Visualization
Line chart showing exponential decay of asset values over 30 years for equipment, vehicles, and buildings.
Illustrative continuous depreciation at the assumed rates in the legend. Under these parameters, equipment declines fastest and buildings retain value longest; this is not an empirical asset-class comparison.
Out[29]:
Console
Asset Values After 10 Years:
--------------------------------------------------
Equipment (20%/year):
  Value: $13,533.53  Half-life: 3.5 years
Vehicle (15%/year):
  Value: $22,313.02  Half-life: 4.6 years
Building (3%/year):
  Value: $74,081.82  Half-life: 23.1 years

The Logistic Equation: Bounded Growth

A fixed carrying capacity can be a useful assumption when modeling adoption in a finite market. The logistic equation reduces proportional growth as adoption approaches that capacity; it does not identify an empirical competition or resource mechanism by itself:

dPdt=rP(1−PK)\frac{dP}{dt} = rP\left(1 - \frac{P}{K}\right)

where:

  • PP: the quantity being modeled (population, market share, number or fraction of adopters)
  • tt: time
  • rr: intrinsic growth rate (growth rate when PP is small)
  • KK: carrying capacity (maximum sustainable value)
  • (1−P/K)(1 - P/K): saturation factor that approaches zero as PP approaches KK

For r>0r>0 and 0<P<K0<P<K, the proportional rate P′/P=r(1−P/K)P'/P=r(1-P/K) falls as PP rises. Absolute growth P′=rP(1−P/K)P'=rP(1-P/K) instead increases up to K/2K/2 and decreases afterward. At P=KP=K, growth is zero.

Logistic Growth

When PP is small relative to KK, the model is close to exponential growth. Proportional growth decreases as PP increases, while absolute growth peaks at K/2K/2 and tends to zero near capacity.

Assume K>0K>0, r>0r>0, and 0<P0<K0<P_0<K for an increasing path. A future accelerating-then-decelerating S-shaped segment additionally requires P0<K/2P_0<K/2. If P0≥K/2P_0\ge K/2, the future starts at or beyond the inflection. P0=0P_0=0 is an equilibrium, while P0>KP_0>K decreases toward KK from above.

Under 0<P0<K0<P_0<K, the logistic equation has the analytical solution:

P(t)=K1+(K−P0P0)e−rtP(t) = \frac{K}{1 + \left(\frac{K - P_0}{P_0}\right)e^{-rt}}

where:

  • P(t)P(t): quantity at time tt
  • P0P_0: initial quantity at t=0t = 0
  • KK: carrying capacity
  • rr: intrinsic growth rate
  • (K−P0)/P0(K - P_0)/P_0: ratio determining how far the initial value is from capacity

The full logistic solution is sigmoid on a linear vertical scale. The example starts at P0=0.01KP_0=0.01K, so its future includes both sides of the inflection. Its comparison figure uses a logarithmic vertical axis to retain the unmodified exponential curve; that geometry is not the ordinary-scale S shape. As t→∞t\to\infty, the exponential term tends to zero and P(t)P(t) approaches KK.

An S-shaped curve can model technology adoption, market penetration, or the spread of a financial product when a fixed carrying capacity is a reasonable assumption. In that model, early adoption is close to exponential, the pool of potential new adopters shrinks, and adoption approaches the specified capacity. The curve is a modeling choice, not a historical claim that every product follows a logistic path.

In[30]:
Code
import numpy as np


def logistic_growth(t, P0, r, K):
    """Analytical solution to the logistic equation."""
    if not np.isfinite([K, r, P0]).all() or K <= 0 or r <= 0 or not 0 < P0 < K:
        raise ValueError("Require K > 0, r > 0, and 0 < P0 < K")
    return K / (1 + ((K - P0) / P0) * np.exp(-r * t))


# Model market adoption of a new financial product
P0 = 1000  # Initial adopters
K = 100000  # Market capacity (100,000 potential customers)
r = 0.5  # Growth rate

t = np.linspace(0, 20, 200)
P = logistic_growth(t, P0, r, K)

# Compare with exponential growth
P_exponential = P0 * np.exp(r * t)
Out[31]:
Visualization
Line chart on a logarithmic vertical axis comparing a logistic curve that levels near 100,000 adopters with an exponential curve that continues above it.
Logistic versus exponential growth on a logarithmic vertical scale. Logistic growth approaches market capacity, whereas the unmodified exponential curve continues increasing.

The displayed model starts with nearly exponential proportional growth. Absolute adoption rises to its maximum at P=K/2P=K/2 and then falls. For 0<P0<K/20<P_0<K/2, that future inflection occurs at:

Out[32]:
Console
Market adoption analysis:
  Initial adopters: 1,000
  Market capacity: 100,000
  Inflection point: 50,000.0 adopters at t = 9.2 years
  Time to reach 50% capacity: 9.2 years
  Time to reach 90% capacity: 13.6 years
Out[33]:
Visualization
Plot showing the logistic growth rate dP/dt as a function of P, with maximum at K/2.
Growth rate in the logistic model peaks at the inflection point (P = K/2) and declines toward zero as the market saturates.

Connecting to Continuous-Time Finance

The mathematical tools developed in this chapter form the foundation for continuous-time financial models. This section previews how these concepts connect to more advanced topics.

The Black-Scholes PDE

Under the stated Black-Scholes-Merton assumptions, a sufficiently smooth European option value satisfies this PDE before expiration. The model assumes a tradable non-dividend-paying underlying, constant risk-free rate and volatility, frictionless replication, and no arbitrage. For an American option, this equality describes its continuation region, not its exercise region:

∂V∂t+12σ2S2∂2V∂S2+rS∂V∂S−rV=0\frac{\partial V}{\partial t} + \frac{1}{2}\sigma^2 S^2 \frac{\partial^2 V}{\partial S^2} + rS\frac{\partial V}{\partial S} - rV = 0

where:

  • VV: option value (function of SS and tt)
  • tt: time
  • SS: underlying asset price
  • σ\sigma: volatility of the underlying asset
  • rr: risk-free interest rate
  • ∂V∂t\frac{\partial V}{\partial t}: rate of change of option value with respect to time (theta)
  • ∂V∂S\frac{\partial V}{\partial S}: rate of change of option value with respect to asset price (delta)
  • ∂2V∂S2\frac{\partial^2 V}{\partial S^2}: second derivative with respect to asset price (gamma)

This PDE combines ideas from this chapter.

The partial derivatives describe how option value VV changes with time tt and stock price SS. Unlike ordinary differential equations where we have one independent variable, here VV depends on both tt and SS, requiring partial derivatives to capture how VV responds to changes in each variable separately.

The equation structure resembles a diffusion equation with drift. The term involving the second derivative (12σ2S2∂2V/∂S2\frac12\sigma^2 S^2 \partial^2 V / \partial S^2) captures how uncertainty diffuses through the option value. The first derivative term (rS∂V/∂SrS \partial V / \partial S) captures drift.

Solving the PDE requires a terminal payoff condition, any applicable spatial boundary conditions, and an analytical transformation or a numerical PDE method. The expiration payoff supplies the terminal condition; integration alone is not a universal procedure for working backward to today's price.

The derivation and solution of this equation will be covered in detail in later chapters, and recognizing its structure as a differential equation prepares you for what follows.

Stochastic Differential Equations

Financial models include randomness. A stochastic differential equation (SDE) generalizes the ODEs in this chapter by adding a random component:

dS=μS dt+σS dWdS = \mu S \, dt + \sigma S \, dW

where:

  • dSdS: infinitesimal change in asset price
  • SS: current asset price
  • μ\mu: drift rate (expected return)
  • σ\sigma: diffusion volatility; over an interval of length Δt\Delta t, the conditional standard deviation of the log return is σΔt\sigma\sqrt{\Delta t} in this model
  • dtdt: infinitesimal time increment
  • dWdW: increment of a Wiener process (Brownian motion)
  • μS dt\mu S \, dt: deterministic drift component
  • σS dW\sigma S \, dW: random diffusion component

The first term (μS dt\mu S \, dt) is the deterministic drift we analyzed earlier in this chapter, representing the expected growth of the stock price over time. The second term (σS dW\sigma S \, dW) adds random fluctuations driven by a Wiener process WW, which is a mathematical model of Brownian motion. These random shocks cause the stock price to fluctuate unpredictably while maintaining an overall drift. Solving SDEs requires stochastic calculus, which extends the integration techniques from this chapter to handle these random components.

Present Value as an Expectation

In an arbitrage-free complete model admitting a risk-neutral measure Q\mathbb{Q}, an integrable European payoff f(ST)f(S_T) with constant deterministic short rate rr has time-zero value:

V0=e−rTEQ[f(ST)]V_0 = e^{-rT} \mathbb{E}^{\mathbb{Q}}[f(S_T)]

If the terminal stock price has a density pQp_{\mathbb Q} on positive prices, the expectation becomes the following density integral. Discrete terminal models instead use weighted sums; in general, integrate against the terminal probability law:

V0=e−rT∫0∞f(s)⋅pQ(s) dsV_0 = e^{-rT} \int_{0}^{\infty} f(s) \cdot p_{\mathbb{Q}}(s) \, ds

where:

  • VV: present value of the derivative
  • rr: risk-free interest rate
  • TT: time to expiration
  • e−rTe^{-rT}: discount factor
  • f(s)f(s): payoff function (e.g., max⁡(s−K,0)\max(s - K, 0) for a call option)
  • ss: possible terminal stock price
  • pQ(s)p_{\mathbb{Q}}(s): risk-neutral density of the positive terminal stock price under the specified model
  • ∫0∞f(s)⋅pQ(s) ds\int_{0}^{\infty} f(s) \cdot p_{\mathbb{Q}}(s) \, ds: risk-neutral expected terminal payoff, assumed finite

Under the Black-Scholes assumptions for a non-dividend-paying stock and a European call, the payoff max⁡(ST−K,0)\max(S_T-K,0) and its risk-neutral lognormal density make this terminal-state integral analytically tractable. Path-dependent claims instead require expectations of path functionals, and incomplete models may not select a unique risk-neutral price without additional assumptions.

Numerical Integration Methods

Many complex, path-dependent, or high-dimensional pricing and risk problems require numerical integration or simulation because a convenient closed form is unavailable. The appropriate method depends on the payoff, state dimension, model dynamics, and accuracy target.

Quadrature Methods

Numerical integration approximates definite integrals using weighted sums of function values.

∫abf(x) dx≈∑i=1nwif(xi)\int_a^b f(x) \, dx \approx \sum_{i=1}^{n} w_i f(x_i)

where:

  • a,ba, b: integration bounds
  • f(x)f(x): the function being integrated
  • nn: number of evaluation points
  • xix_i: nodes (evaluation points) within [a,b][a, b]
  • wiw_i: weights determining the contribution of each function value

The idea is to sample the function at carefully chosen points and combine these samples with appropriate weights. Different methods choose different nodes xix_i and weights wiw_i:

  • The displayed composite trapezoidal rule uses equally spaced nodes and piecewise-linear interpolation; supplied coordinates also allow nonuniform nodes.
  • Simpson's rule uses quadratic interpolation over pairs of subintervals.
  • Gaussian quadrature chooses nodes and weights so that an nn-node rule integrates polynomials through degree 2n−12n-1 exactly under its specified weight function.
In[34]:
Code
import numpy as np
from scipy import integrate


# Compare integration methods on the same truncated lognormal expectation
def option_density(s, S0=100, r=0.05, sigma=0.2, T=1):
    """Log-normal density for stock price under GBM."""
    if s <= 0:
        return 0
    mu = np.log(S0) + (r - 0.5 * sigma**2) * T
    var = sigma**2 * T
    return np.exp(-((np.log(s) - mu) ** 2) / (2 * var)) / (s * np.sqrt(2 * np.pi * var))


# All numerical methods integrate over [0, upper_bound]. The analytic benchmark
# is the untruncated GBM expectation, so reported errors also include the tiny
# omitted tail beyond the upper bound.
S0, r, T = 100, 0.05, 1
upper_bound = 500.0
analytical_expected = S0 * np.exp(r * T)


def expectation_integrand(s):
    return s * option_density(s)


n_grid = 4001
grid = np.linspace(0, upper_bound, n_grid)
grid_values = np.array([expectation_integrand(s) for s in grid])
trapezoid_estimate = np.trapezoid(grid_values, grid)
simpson_estimate = integrate.simpson(grid_values, x=grid)

n_gauss = 64
gauss_nodes, gauss_weights = np.polynomial.legendre.leggauss(n_gauss)
mapped_nodes = 0.5 * upper_bound * (gauss_nodes + 1)
gauss_estimate = (
    0.5
    * upper_bound
    * np.sum(gauss_weights * np.array([expectation_integrand(s) for s in mapped_nodes]))
)

adaptive_estimate, adaptive_error, adaptive_info = integrate.quad(
    expectation_integrand, 0, upper_bound, full_output=True
)

quadrature_results = [
    ("Trapezoid", trapezoid_estimate, n_grid),
    ("Simpson", simpson_estimate, n_grid),
    ("Gauss-Legendre", gauss_estimate, n_gauss),
    ("Adaptive quad", adaptive_estimate, adaptive_info["neval"]),
]
Out[35]:
Console
Expected stock price integrated on [0, 500]
Analytic untruncated benchmark: $105.12710964

Method                   Estimate     Abs. error  Evaluations
--------------------------------------------------------------
Trapezoid          $105.12710964 $   6.395e-13         4001
Simpson            $105.12710964 $   6.537e-13         4001
Gauss-Legendre     $105.12710964 $   6.963e-13           64
Adaptive quad      $105.12710964 $   6.679e-13          147

Adaptive quad error estimate on the truncated integral: 2.66e-07

Monte Carlo Integration

For high-dimensional integrals involving multiple assets or path-dependent options, Monte Carlo integration is often a practical and scalable approach.

∫f(x)p(x) dx≈1N∑i=1Nf(Xi)\int f(x) p(x) \, dx \approx \frac{1}{N} \sum_{i=1}^{N} f(X_i)

where:

  • f(x)f(x): the function being integrated (e.g., option payoff)
  • p(x)p(x): probability density function
  • NN: number of random samples
  • XiX_i: independent random samples drawn from distribution p(x)p(x)
  • 1N∑i=1Nf(Xi)\frac{1}{N} \sum_{i=1}^{N} f(X_i): sample average approximating the expected value

Under the Law of Large Numbers conditions, the sample average converges to the expected value. Drawing from p(x)p(x) represents each region according to its probability mass. Accuracy depends on the variance of f(X)f(X), not density alone; for rare but influential tail payoffs, a different sampling density qq can reduce variance only with the corresponding likelihood-ratio weights p(X)/q(X)p(X)/q(X) and coverage wherever the original weighted payoff is nonzero. Changing the sampling density alone changes the target expectation.

In[36]:
Code
import numpy as np

# Monte Carlo integration for expected call payoff
S0, K, r, sigma, T = 100, 100, 0.05, 0.2, 1
n_simulations = 100000

# Generate log-normal terminal prices
Z = np.random.standard_normal(n_simulations)
ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)

# Calculate call payoffs and present value
payoffs = np.maximum(ST - K, 0)
mc_price = np.exp(-r * T) * np.mean(payoffs)
mc_std_error = np.exp(-r * T) * np.std(payoffs, ddof=1) / np.sqrt(n_simulations)
Out[37]:
Console
European Call Option Pricing:
  Parameters: S0=$100, K=$100, r=5.0%, sigma=20.0%, T=1 year

Monte Carlo (100,000 simulations):
  Price: $10.4739
  Std Error: $0.0466

Black-Scholes Analytical:
  Price: $10.4506

Difference: $0.0233
Out[38]:
Visualization
Nested-sample Monte Carlo call-price estimates with pointwise normal-approximation intervals and the Black-Scholes benchmark.
Nested-sample Monte Carlo estimates for the displayed European call. For independent finite-variance payoffs, the estimator's standard error and asymptotic RMSE scale as 1/√N; the band is a pointwise normal-approximation interval.

For independent samples with finite payoff variance, the Monte Carlo sample mean has standard error O(N−1/2)O(N^{-1/2}) and, when unbiased, RMSE of the same order. Quadrupling NN therefore halves those asymptotic measures, not necessarily the realized absolute error in one run. Monte Carlo remains useful for complex and path-dependent payoffs without closed forms.

Limitations and Practical Considerations

The framework of calculus and differential equations has important limitations in financial applications.

Model Risk

Differential equations encode idealized dynamics. A smooth model omits regime changes, jumps, or structural breaks unless those features are added explicitly, so its solutions are model outputs rather than market facts. Continuous compounding idealizes a balance evolving under a continuous force of interest; contractual crediting conventions can differ from that idealization.

Numerical Precision

Numerical integration introduces approximation error, and nested procedures can propagate it. A terminal-state payoff depends on the terminal distribution; a path-dependent payoff is instead an expectation of a functional of the entire path and may require time discretization or path-space integration. Relative error can be sensitive when the target value is very small, but amplification depends on the method and problem. Production systems therefore require stability, convergence, and error checks; scipy.integrate.quad can still struggle with ill-behaved integrands.

Computational Tractability

Some problems are analytically solvable but computationally expensive. Others lack a convenient known closed form and are evaluated numerically. The trade-off between analytical solutions and numerical methods depends on the application.

  • Real-time pricing demands sufficiently fast, validated methods, whether analytical or numerical
  • Non-real-time risk workflows can trade latency for broader scenario or payoff coverage when their service-level requirements allow it
  • Validation work can compare a numerical method with an analytical benchmark when both are available

Understanding which tools apply when, and their computational costs, is as important as the mathematics itself.

Summary

This chapter developed integral calculus and differential equations as tools for quantitative finance. The key concepts and their financial applications include:

Integral Calculus:

  • The definite integral accumulates cash-flow rates and instantaneous continuously compounded rates; the latter produce log gross returns that must be exponentiated to obtain gross return factors
  • Under the Fundamental Theorem's hypotheses, a known antiderivative gives the definite integral by endpoint subtraction
  • Integration techniques (substitution, parts) appear throughout derivative pricing and risk calculations

Continuous Compounding:

  • The limit of discrete compounding leads to the continuous formula V(t)=V0ertV(t) = V_0 e^{rt}
  • This formula arises as the solution to the differential equation dV/dt=rVdV/dt = rV
  • Time-varying discounting integrates the instantaneous forward curve: D(0,T)=e−∫0Tf(0,s)dsD(0,T) = e^{-\int_0^T f(0,s) ds}. A continuously compounded zero rate instead gives D(0,T)=e−R(0,T)TD(0,T)=e^{-R(0,T)T}, while par yields must first be transformed into zero rates or forward rates

Differential Equations:

  • First-order linear ODEs model portfolio growth, the drift or conditional mean in a mean-reverting model, and asset depreciation
  • Separation of variables solves many fundamental financial models
  • Logistic equations capture bounded growth in market adoption and saturation
  • Tolerance-controlled numerical methods can approximate equations without closed-form solutions, subject to solver and floating-point limits

Connection to Advanced Topics:

These foundations support continuous-time finance models used in quantitative practice. The next chapter develops numerical methods and algorithms for financial problems; later stochastic-process and derivatives chapters add randomness and pricing applications.

Key Parameters

The key parameters for integral calculus and differential equations in finance are:

  • r: Interest rate or discount rate. Appears in continuous compounding erte^{rt} and determines how future cash flows are discounted to present value.
  • T: Time horizon or maturity. At a fixed nonzero rate, a longer horizon increases the magnitude of compounding or discounting relative to the starting value; changing-sign rates can offset one another.
  • κ (kappa): Positive mean reversion speed (κ>0\kappa>0) in models like Vasicek. Higher positive values mean faster reversion to the long-term mean, with half-life ln⁡(2)/κ\ln(2)/\kappa.
  • θ (theta): Long-term mean in models such as Vasicek. The conditional mean reverts toward this level; individual stochastic paths are not forced to converge to it.
  • δ (delta): Continuous depreciation or decay rate. Positive decay and positive initial value give half-life ln⁡(2)/δ\ln(2)/\delta; the effective annual loss is 1−e−δ1-e^{-\delta}.
  • K: Logistic limiting capacity. It bounds an increasing path started below KK; a path started above it decreases toward it.
  • μ (mu): Drift rate in growth models. Represents the expected rate of return or growth per unit time.
  • σ (sigma): Volatility parameter. Measures the magnitude of random fluctuations in stochastic models.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about integral calculus and differential equations in finance.

Integral Calculus and Differential Equations

Question 1 of 80 of 8 completed
What is the continuous compounding formula for the future value of an investment with principal V0V_0, constant continuously compounded annual rate rr, and time tt in years?
Track your reading progress

Sign in to mark sections as read and track your learning journey

Sign in →
Keep the thread going

Continue reading

Book contents
A different angle
All writing
Quantitative Finance · Vol. 1

Data Handling & Visualization: Python for Quant Finance

Covers financial data handling with pandas, NumPy, and Numba. Topics include time series operations, return calculations, and visualization for quant finance.

41 min read
Quantitative Finance · Vol. 1

Numerical Methods in Finance: Algorithms for Pricing & Risk

Covers root-finding, interpolation, and numerical integration for finance. Compute implied volatility, build yield curves, and price derivatives.

63 min read
Quantitative Finance · Vol. 1

Differential Calculus for Quantitative Finance

Covers derivatives, gradients, and optimization techniques essential for quantitative finance. Topics include Greeks, portfolio optimization.

76 min read
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2025integralcalculus, author = {Michael Brenndoerfer}, title = {Integral Calculus & Differential Equations in Finance}, year = {2025}, url = {https://mbrenndoerfer.com/writing/integral-calculus-differential-equations-quantitative-finance}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-10-21} }
APAAcademic
Michael Brenndoerfer (2025). Integral Calculus & Differential Equations in Finance. Retrieved from https://mbrenndoerfer.com/writing/integral-calculus-differential-equations-quantitative-finance
MLAAcademic
Michael Brenndoerfer. "Integral Calculus & Differential Equations in Finance." 2026. Web. October 21, 2026. <https://mbrenndoerfer.com/writing/integral-calculus-differential-equations-quantitative-finance>.
CHICAGOAcademic
Michael Brenndoerfer. "Integral Calculus & Differential Equations in Finance." Accessed October 21, 2026. https://mbrenndoerfer.com/writing/integral-calculus-differential-equations-quantitative-finance.
HARVARDAcademic
Michael Brenndoerfer (2025) 'Integral Calculus & Differential Equations in Finance'. Available at: https://mbrenndoerfer.com/writing/integral-calculus-differential-equations-quantitative-finance (Accessed: October 21, 2026).
SimpleBasic
Michael Brenndoerfer (2025). Integral Calculus & Differential Equations in Finance. https://mbrenndoerfer.com/writing/integral-calculus-differential-equations-quantitative-finance
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy