Sortino Ratio in Python: Measuring Downside Risk from Daily Returns

Standard deviation treats a strong up-day and a painful down-day as the same kind of event. The Sortino ratio measures only the shortfall below a chosen target, so it treats the two kinds of day differently. This guide computes it from daily returns in Python and shows where its estimator choices matter.

E-E-A-T scope. This guide is based on the original papers, public documentation, and the code below, which was run on synthetic data; we did not backtest a real strategy.

What the Sortino ratio measures, and its formula

The Sortino ratio is defined as S = (R − T) / DR, where R is the average return (annual in the source; the code works on daily returns and annualises), T is the target or minimum acceptable return, and DR is the downside deviation, per the definition on Wikipedia’s Sortino ratio page, which attributes the ratio itself to Sortino and Price. The downside deviation has a continuous form:

DR = sqrt( ∫ from −∞ to T of (T − r)² f(r) dr )

where f(r) is the density of returns. Intuitively, DR averages the squared shortfalls below the target, and only below the target, then takes the square root.

The downside-risk paper is Sortino and van der Meer (1991), “Downside Risk: Capturing what’s at stake in investment situations”, Journal of Portfolio Management 17(4):27–31 (full paper PDF). The benchmark it is compared against is the Sharpe ratio.

The practical difference: Sharpe penalises upside and downside variance equally, while Sortino penalises only returns below the target. Per Wikipedia, the two give similar results when the return distribution is near symmetric and the target is near the median. The synthetic experiment below tests that remark only loosely, as explained there.

Why downside deviation is not standard deviation

Downside deviation measures dispersion only on the adverse side of a chosen threshold. Wikipedia’s Sortino ratio article describes it as the target semi-deviation, the square root of target semi-variance, so only the shortfall below the target enters. Standard deviation, by contrast, averages squared deviations on both sides of the mean. For the broader concept, see Wikipedia’s downside risk page.

In discrete form, the estimator used throughout this post is:

DR = sqrt( mean over ALL N periods of min(r_t − T, 0)² )

Two details matter. First, the min(r_t − T, 0) clip zeroes out every return at or above the target, so upside observations contribute nothing to DR. Second, the mean is taken over all N periods, not just the losing ones. That choice determines how rare losses are treated, as the FAQ below explains, so it should be stated whenever you report a number.

The discrete-versus-continuous convention

There is more than one way to turn the continuous downside-risk integral into a number from a sample. Wikipedia’s Sortino ratio article states that the continuous formula is preferred over the simpler discrete version. It also notes that some practitioners use discrete periodic returns to compute downside risk, and calls that method “conceptually and operationally incorrect”, because it negates the foundational statistic of Brian M. Rom’s post-modern portfolio theory framework.

This post implements a discrete-periodic estimator, the all-N semi-deviation, because it runs directly on a return series. The article’s criticism is aimed at discrete periodic returns, which this demo uses. The demo’s form, the all-N semi-deviation about T, is not the article’s “standard deviation of below-target periodic returns”, so the post does not claim the criticism applies to it in full. It implements the estimator anyway and does not claim Wikipedia endorses it. If two implementations disagree, check the estimator convention first, before you look at the data.

The Python implementation

The implementation below computes annualised Sharpe and Sortino ratios from a numpy array of daily returns, using numpy’s random Generator to draw the synthetic data, numpy.minimum to clip returns at the target, and numpy.mean for the averaging step. The numpy source is on GitHub.

import numpy as np

P = 252  # trading days per year


def sharpe(r):
    # annualised Sharpe with rf = 0; sample std (ddof=1)
    return np.sqrt(P) * r.mean() / r.std(ddof=1)


def sortino(r, target=0.0):
    # per-period target; downside deviation divides by ALL N periods, not by the count of losses
    downside = np.minimum(r - target, 0.0)
    dd = np.sqrt(np.mean(downside ** 2))
    return np.sqrt(P) * (r.mean() - target) / dd


def simulate(seed, kind, n=2520):
    rng = np.random.default_rng(seed)
    if kind == "symmetric":
        return rng.normal(0.0004, 0.01, n)
    # negatively skewed: frequent small gains, ~2% of days a 3-5% loss
    base = rng.normal(0.0012, 0.0025, n)
    shock = rng.random(n) < 0.02
    return base - shock * rng.uniform(0.03, 0.05, n)


def hand_check():
    r = np.array([0.01, -0.02, 0.03, -0.01])
    dd = np.sqrt(np.mean(np.minimum(r, 0.0) ** 2))
    return r.mean(), dd, r.mean() / dd


if __name__ == "__main__":
    m, dd, ratio = hand_check()
    print(f"hand check: mean={m:.6f} downside_dev={dd:.6f} per-period ratio={ratio:.4f}")
    print("hand check by hand: downside=[0,-0.02,0,-0.01]; mean sq=(0.0004+0.0001)/4=0.000125; sqrt=0.01118; mean r=0.0025; 0.0025/0.01118=0.2236")
    for kind in ("symmetric", "skewed"):
        r = simulate(42, kind)
        print(f"{kind}: n={len(r)} mean_daily={r.mean():.6f} sd_daily={r.std(ddof=1):.6f} "
              f"min/max={r.min():.4f}/{r.max():.4f} "
              f"sharpe={sharpe(r):.3f} sortino(T=0)={sortino(r):.3f}")

Three implementation notes. Both ratios are annualised with sqrt(252) applied to per-period figures: annualised Sharpe is sqrt(252) * mean(r) / std(r, ddof=1), and annualised Sortino is sqrt(252) * (mean(r) − T) / DR_period. The Sharpe function uses the sample standard deviation with ddof=1, while the Sortino denominator here averages over all N periods. And target is a parameter of sortino(), not a constant: the demo calls it with its default, T = 0, but nothing in the formula requires that.

If you would rather not maintain your own function, empyrical and quantstats are Python libraries of risk metrics, and pandas is the common tool for loading return series.

A hand check you can do without a computer

You can check the formula’s arithmetic with four numbers and a calculator. The script’s hand_check() returns a mean of 0.0025, a downside deviation of 0.011180, and a per-period ratio of 0.2236, and prints them on its first line of output, shown in full below. The function reimplements the formula inline and does not call sortino(), so the check covers the arithmetic, not that function.

Take the returns [0.01, -0.02, 0.03, -0.01] with T = 0. Clipping at zero gives the downside series [0, -0.02, 0, -0.01]. The mean of the squares is (0.0004 + 0.0001) / 4 = 0.000125, which divides by four, all periods, not the two losing ones. The square root is 0.01118. The mean return is 0.0025, and 0.0025 / 0.01118 = 0.2236. When a library’s Sortino output surprises you, a four-element check like this is a fast way to find out whether the surprise is in the data or in the estimator.

What the synthetic run shows, and what it does not

On a single seed of synthetic data, the symmetric series produces Sharpe −0.007 and Sortino −0.010, while the negatively skewed series produces Sharpe 0.923 and Sortino 1.006. These numbers characterise the simulated distributions only: one seed, no out-of-sample test, and no real ticker data. Here is the full output of the script above:

hand check: mean=0.002500 downside_dev=0.011180 per-period ratio=0.2236
hand check by hand: downside=[0,-0.02,0,-0.01]; mean sq=(0.0004+0.0001)/4=0.000125; sqrt=0.01118; mean r=0.0025; 0.0025/0.01118=0.2236
symmetric: n=2520 mean_daily=-0.000005 sd_daily=0.010052 min/max=-0.0361/0.0322 sharpe=-0.007 sortino(T=0)=-0.010
skewed: n=2520 mean_daily=0.000350 sd_daily=0.006022 min/max=-0.0511/0.0091 sharpe=0.923 sortino(T=0)=1.006

The symmetric case checks the estimator, not the Wikipedia remark. The realised mean is −0.000005, so both ratios sit near zero. With a mean at zero and returns symmetric about it, half the variance lies below T = 0, so this all-N downside deviation is about sd/√2, and the Sortino ratio is about √2 times Sharpe. The output is consistent with that factor, −0.010 against −0.007, although both values are near zero, so the agreement is weak evidence. Wikipedia’s “similar results” remark is qualitative, and with this discrete estimator the scale differs even for symmetric returns. We did not re-seed to find a positive-mean case.

The skewed case is the demonstration. Its return stream has frequent small gains and a small fraction of large losses, and the min/max of −0.0511/0.0091 shows that asymmetry. Sortino reads higher here (1.006 against 0.923). The mechanism is arithmetic: the Sortino denominator counts only below-target deviations, while Sharpe’s standard deviation also counts upside dispersion, and in this simulated stream the upside is narrow. That is this simulation’s outcome, and the post does not claim Sortino reads higher than Sharpe on skewed series in general.

When to use Sortino versus Sharpe

Use Sharpe when you want the widely used benchmark and returns are roughly symmetric. Use Sortino when asymmetric loss is the thing you are trying to capture. The Omega ratio is one of several alternatives when a single ratio feels too coarse for the question you are asking.

A few practical rules of thumb follow from the definitions rather than from any new evidence. For a near-symmetric return stream with the target near the mean, this estimator’s Sortino is about √2 times Sharpe, and the extra parameter (the target) is one more thing to justify. If the distribution is visibly skewed, Sortino answers a question Sharpe cannot: how much dispersion exists strictly below the threshold you care about. Whenever you report either ratio, report the target and the annualisation convention alongside it, because a reader cannot reconstruct either from the ratio alone.

FAQ

Why does the downside deviation divide by all N periods instead of only the losing ones?

Dividing by all N periods makes DR an average over the whole series, so the same loss sizes produce a smaller DR when losses are rarer. Dividing by the count of losing periods removes that frequency effect, so the same loss sizes give the same DR regardless of how often they occur. Which is right depends on what you want the ratio to measure. The demo follows the all-period convention and states it.

What should the target return T be?

The demo uses T = 0. The target enters both the numerator and, through DR, the denominator, so the ratio depends on it. Pick a target that matches the mandate you are evaluating, state it whenever you publish a Sortino figure, and treat two numbers with different targets as not directly comparable.

Which Python libraries compute the Sortino ratio for me?

quantstats exposes a sortino method in its statistics module, and empyrical provides common financial risk and performance metrics. Both are worth reading at the source level before trusting their output. Alternatively, the function in this post is a few lines of numpy and states its convention openly. Whichever route you take, check the library’s definition before comparing its numbers to yours.

The Bottom Line

The Sortino ratio replaces standard deviation with downside deviation, the square root of the mean, over all periods, of squared shortfalls below a target. The estimator is a handful of numpy: clip returns at the target with np.minimum, square, average over all N periods, take the square root, and annualise with sqrt(252). The hand check confirms the arithmetic on four numbers. The synthetic run shows that the code behaves as defined, and one skewed-stream gap that is a property of the simulation. Name your target and estimator convention whenever you report a number: the article prefers the continuous form and calls the discrete-periodic approach, which this demo uses, conceptually and operationally incorrect.

← Back to all posts