Incorrect Sortino ratio
We are calculating the sortino ratio wrong, specifically the downside deviation portion.
Zipline has the same issue, see https://github.com/quantopian/zipline/issues/747 for an example, we only have issue 2 in pyfolio.
This paper by Red Rock Capital discusses the issue http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf
Here is the correct function for downside deviations
def downside_dev(returns, required_ROR=0):
diff = returns - required_ROR
mask = diff > 0
dsides = returns.mask(mask, 0)
sq_devs = np.square(dsides)
return np.sqrt(np.mean(sq_devs))
EDIT: changed the above function to subtract the required return.
I wrote code that properly calculates the sortino ratio and checked it against the example in the Red Rock paper (output below).
One thing I'm not sure about is annualizing, they used annual returns in their example but we use daily returns.
Any thoughts @justinlent
def downside_risk(returns, required_return=0):
downside_diff = returns - required_return
mask = downside_diff > 0
downside_diff[mask] = 0.0
squares = np.square(downside_diff)
mean_squares = np.nanmean(squares, axis=0)
return np.sqrt(mean_squares)
def sortino_ratio(returns, required_return=0):
mu = np.nanmean(returns - required_return, axis=0)
return mu / downside_risk(returns, required_return)
>>> returns = pd.Series([17, 15, 23, -5, 12, 9, 13, -4]) / 100.
>>> print sortino_ratio(returns)
4.4172610429938617
@humdings what do you think about annualizing both the numerator and denominator values before doing the division? So something like:
(mu * 252) / (downside_risk * sqrt(252))
I like reporting annualized values because I feel like that is industry convention. But in the case of only a 2 year backtest, for example, computing 'mu' or 'downside_risk' with just 2 annual values would just be silly.
Would annualizing them prior to the division still be in the spirit of what the Sortino Ratio is attempting to inform the user?
That sounds good to me.
Since x / sqrt(x) = sqrt(x), we can just multiply the result by sqrt(252). Unless we want the downside deviation to return an annualized value.
I'll submit a PR for this since it's written already
Yep totally. I was just being explicit with the annualization calculation for example - def makes sense to just multiply the result by sqrt(252)
Fixed by https://github.com/quantopian/pyfolio/pull/159.