Howwise RSS
Trading Software7 min read

How to Annualize Sharpe Ratio Correctly in Python (pandas)

Short answer

To annualize Sharpe ratio, compute mean over standard deviation of per-period excess returns, then multiply by the square root of periods per year (252 daily, 365 crypto, 52 weekly, 12 monthly). A daily 0.06 becomes about 0.95.

Key takeaways
  • Annualized Sharpe = per-period Sharpe * sqrt(periods per year), and it is only valid when the periods per year matches the calendar of your data.
  • Convert the annual risk-free rate to a per-period rate once, and subtract it before computing the mean and standard deviation.
  • Using 252 on a 365-day crypto series understates Sharpe by a factor of sqrt(252/365), about 17%.
  • Daily and monthly annualized figures differ because of autocorrelation, volatility clustering and estimation error, and Lo's adjustment explains the autocorrelation part.
  • Always publish the frequency, periods per year, risk-free treatment and sample size next to the number, with a confidence interval.

How is the Sharpe ratio computed and annualized?

The Sharpe ratio is the mean of excess returns divided by their sample standard deviation, both measured per period: SR = mean(r - rf) / std(r - rf, ddof=1). The result is in units of one period, so a daily Sharpe and a monthly Sharpe are different quantities and cannot be compared directly.

To annualize, scale to a common horizon. Under i.i.d. returns, the mean over N periods grows with N and the standard deviation grows with sqrt(N). The ratio therefore grows with sqrt(N): annualized SR = SR_period * sqrt(periods_per_year).

Worked example: a daily Sharpe of 0.06 gives 0.06 * sqrt(252) = 0.06 * 15.875 = 0.95. The same strategy measured monthly would show a monthly Sharpe near 0.95 / sqrt(12) = 0.27, which looks small only because it is a different unit.

Use ddof=1 (pandas default for .std()). NumPy's np.std defaults to ddof=0, which silently gives a slightly higher Sharpe, and the gap is noticeable on short samples.

What is a correct annualization function in pandas?

One function should own the periods-per-year lookup, the risk-free conversion and the sample checks, so every report uses identical rules. The table below gives the usual factors. The right value is whatever matches how many observations your series really contains in a year.

FrequencyPeriods per yearNotes
Daily, equities/futures252Exchange trading days; roughly 250 to 253 depending on year
Daily, crypto365Trades 24/7, so every calendar day has a bar
Weekly52Use 52, or 52.18 for exactness
Monthly12Compound daily returns to month-end
1-minute, US equities390 * 252390 regular-session bars per day
5-minute, 24h crypto288 * 365288 bars per day
Hourly, crypto24 * 3658,760 bars
import numpy as np
import pandas as pd

PPY = {"D_EQ": 252, "D_CRYPTO": 365, "W": 52, "M": 12,
       "1min_EQ": 390 * 252, "5min_CRYPTO": 288 * 365, "1h_CRYPTO": 24 * 365}

def rf_per_period(rf_annual, ppy, compound=True):
    # (1+rf)^(1/N)-1 is exact for compounding; rf/N is the simple approximation
    return (1 + rf_annual) ** (1 / ppy) - 1 if compound else rf_annual / ppy

def sharpe(returns, ppy, rf_annual=0.0, annualize=True):
    r = returns.dropna()
    excess = r - rf_per_period(rf_annual, ppy)
    sr = excess.mean() / excess.std(ddof=1)
    return sr * np.sqrt(ppy) if annualize else sr

# usage
# daily = pd.Series(..., index=DatetimeIndex)   # simple returns
# print(len(daily), daily.index[0], daily.index[-1])  # sanity check
# print(sharpe(daily, PPY["D_EQ"], rf_annual=0.03))
Tip: Print len(returns) and the first and last dates next to every Sharpe. A year of US equity data should have about 252 rows; 365 rows means weekends are present and 252 is the wrong factor.

How do I handle the risk-free rate without annualizing it twice?

Subtract the risk-free rate per period, before computing the mean and standard deviation. If your rf is quoted as 4% a year and you have daily returns, subtract (1.04)^(1/252) - 1, about 0.0156% per day, or the simple approximation 0.04/252. Subtracting 0.04 from daily returns, or subtracting a per-day rate after annualizing the Sharpe, are the two classic unit bugs.

A constant rf shifts the mean and leaves the standard deviation unchanged. A time-varying rf, such as a T-bill series, should be aligned to the return index and converted per row, because it can slightly change the standard deviation too.

For dollar-neutral long-short books and futures strategies, returns are often already excess returns, because the cash is not tied up in the position or the financing is embedded. In that case rf is 0, and subtracting a Treasury yield would double count. State which convention you used.

Warning: Never annualize rf and then subtract it from per-period returns. Mismatched rf units are one of the most common reasons two Sharpe figures for the same strategy disagree.

Why does the Sharpe ratio change with frequency?

First, the raw numbers are in different units, so compare only after annualizing. Second, even annualized figures differ, because sqrt(N) scaling assumes i.i.d. returns and real returns violate that in several ways.

Autocorrelation is the main one. For a mean-reverting strategy, daily returns are negatively autocorrelated, so daily losses and gains partly cancel inside the month. Monthly volatility is then lower than sqrt(21) times daily volatility, so the monthly-annualized Sharpe is higher than the daily-annualized one. With positive autocorrelation (trend, smoothed or stale marks), long-horizon variance is larger, so daily-annualized scaling understates risk and overstates Sharpe.

Volatility clustering and fat tails add further noise, and monthly Sharpe is estimated from far fewer samples, so its error is much larger.

Compound when resampling. Summing daily returns to get monthly returns is only right for log returns. In recent pandas the month-end alias is 'ME'; the old 'M' alias is deprecated.

def to_period(daily, rule):
    # simple returns: compound, never sum
    return (1 + daily).resample(rule).prod() - 1

weekly  = to_period(daily, "W-FRI")
monthly = to_period(daily, "ME")   # 'M' is deprecated in recent pandas

for name, s, ppy in [("daily", daily, 252), ("weekly", weekly, 52), ("monthly", monthly, 12)]:
    print(name, len(s), round(sharpe(s, ppy, rf_annual=0.0), 3))

How do I adjust the Sharpe ratio for autocorrelation?

Lo (2002) replaces sqrt(q) with q / sqrt(q + 2 * sum_{k=1}^{q-1} (q-k) * rho_k), where q is the number of periods in the aggregation horizon (for example 252 for a year of daily returns) and rho_k is the lag-k autocorrelation of returns. If all rho_k are zero, the factor reduces to sqrt(q). Positive autocorrelation shrinks the factor, so the adjusted Sharpe is lower than the naive one.

This matters most for illiquid assets, smoothed or marked-to-model returns, and strategies with overlapping holdings, where today's return shares information with yesterday's. For liquid daily strategies with near-zero autocorrelation it changes little.

Sample autocorrelations at high lags are noisy. Many practitioners truncate at a modest number of lags, which is a judgment call to disclose, and the code below uses the full range as a simple default.

def lo_factor(returns, q):
    r = returns.dropna()
    rho = [r.autocorr(lag=k) for k in range(1, q)]
    denom = q + 2 * sum((q - k) * rho[k - 1] for k in range(1, q))
    return q / np.sqrt(denom)

def sharpe_lo(returns, ppy, rf_annual=0.0, q=None):
    q = q or ppy
    r = returns.dropna()
    excess = r - rf_per_period(rf_annual, ppy)
    return excess.mean() / excess.std(ddof=1) * lo_factor(excess, q)

How uncertain is an annualized Sharpe ratio?

For a per-period Sharpe, the approximate standard error is sqrt((1 + 0.5 * SR^2) / T), where T is the number of observations. Multiply by sqrt(ppy) to put it in annual units, then use a 95% interval of SR +/- 1.96 * SE.

Example: daily SR 0.06 (annualized 0.95) over 5 years, T = 1260. SE = sqrt(1.0018 / 1260) = 0.0282 per day, or 0.45 annualized. The interval is roughly 0.07 to 1.83.

The same strategy observed monthly over 3 years (T = 36) has monthly SR 0.27 and SE = sqrt(1.0376 / 36) = 0.17 per month, or 0.59 annualized. The interval is about -0.2 to 2.1. A few years of monthly data gives a very wide interval, so a Sharpe is not statistically distinguishable from zero without enough samples.

This formula assumes i.i.d. returns. If you tested many variants, the Deflated Sharpe Ratio (Bailey and Lopez de Prado) adjusts the significance for the number of trials and for non-normality.

def sharpe_ci(returns, ppy, rf_annual=0.0, z=1.96):
    sr_p = sharpe(returns, ppy, rf_annual, annualize=False)
    T = returns.dropna().shape[0]
    se_a = np.sqrt((1 + 0.5 * sr_p**2) / T) * np.sqrt(ppy)
    sr_a = sr_p * np.sqrt(ppy)
    return sr_a - z * se_a, sr_a, sr_a + z * se_a

Why is my Sharpe different from another tool's? A debug checklist

Work through the causes in order of likelihood. Most mismatches are unit or calendar errors, not statistics.

  1. Units: confirm both sides use simple returns (not log, not percent, not prices or cumulative equity). Call .pct_change() on prices first, and divide percent figures by 100.
  2. Periods per year: compare len(series) against expectation. Crypto on 252 understates by sqrt(252/365) = 0.831, about 17% (for example 1.50 reported as 1.25). The reverse mistake, 365 on equities, overstates by about 20%.
  3. Risk-free: check that both use the same rf, converted per period once, and that a long-short or futures series is not being charged cash rates twice.
  4. Compounding and resampling: monthly returns must come from (1+r).resample('ME').prod() - 1, not sum.
  5. Zero and filled bars: flat days when not invested, forward-filled prices, or missing bars shrink volatility. Weekend rows in a 252-based equity series inflate the count.
  6. ddof and sample window: use ddof=1 and check the first and last dates match. Tools such as quantstats, empyrical or pyfolio may differ in rf handling and in whether they use 252 by default.
  7. Autocorrelation and sample error: only after the above, apply Lo's factor and compare confidence intervals before concluding that two figures truly differ.
Tip: Prefer annualizing from the daily series because it has more data and a tighter interval, but confirm that the returns are not stale or smoothed. Report frequency, ppy, rf treatment and period alongside the number.

Common questions

Should I use 252 or 365 for crypto Sharpe ratio?

Use 365 for daily crypto data, because the market trades every calendar day and the series has about 365 rows a year. Using 252 on that data understates the result by sqrt(252/365) = 0.831, roughly 17%. For intraday bars use bars per day * 365, such as 288 * 365 for five-minute bars.

Can I annualize a monthly Sharpe ratio by multiplying by 12?

No. Multiply by sqrt(12), about 3.46. The mean scales with 12 but the standard deviation scales with sqrt(12), so the ratio scales with sqrt(12) under i.i.d. returns.

Should I use log returns or simple returns for Sharpe?

Pick one and use it consistently. Log returns add across time, which makes resampling by summing correct, while simple returns must be compounded with (1+r).prod() - 1. Mixing them, or comparing against a tool that uses the other, shifts the result slightly.

Does the risk-free rate matter if it is small?

It matters whenever the rate is a meaningful fraction of the mean return, since it is subtracted from the numerator. At daily frequency the per-day value looks tiny but is comparable to a small daily mean. For dollar-neutral or futures series, returns are often already excess and rf should be 0.

Why is my monthly Sharpe so different from my daily one?

Beyond unit scaling, the monthly estimate uses roughly 21 times fewer observations, so its standard error is much larger. Autocorrelation and volatility clustering also make the sqrt(N) rule inexact. Compare the two with confidence intervals and Lo's adjustment before treating the gap as meaningful.

Related topics:sharpe ratiopandasbacktestingrisk metrics