How do I find the bug behind a wrong result?

Find three common bugs in a returns calculation: read an error from its last line, check the shape after a merge with validate, and test a function on a small input whose answer is known with np.testing.assert_allclose.

After this lesson, you can find a column of the wrong type, a merge that repeats rows and a formula with the wrong divisor in a returns calculation.

Where does an error point?

Read an error from its last line, which names the exception and what went wrong, and then find the line of your own code that passed the bad values. Here the last line says that a division received two strings, because the closes arrive as text with commas.

The example is a long panel, as in the lesson on long and wide panels, of two made-up stocks over four days, with closes in pounds as text. daily_returns computes each stock’s daily return with .pct_change(), as in the lesson on percentage changes. try and except TypeError as error catch the exception, and type(error).__name__ gives its name, as in the lesson on reading errors. .str.replace(",", "", regex=False) removes the commas and pd.to_numeric turns the text into numbers.

The following box catches the error and then fixes the column.

import numpy as np
import pandas as pd

prices = pd.DataFrame({
    "ticker": ["AAA"] * 4 + ["BBB"] * 4,
    "day": [0, 1, 2, 3] * 2,
    "close": ["1,000", "1,010", "989.8", "1,004.647", "1,000", "1,100", "990", "1,019.7"],
})

def daily_returns(prices, column):
    return prices.groupby("ticker")[column].pct_change(fill_method=None)

try:
    daily_returns(prices, "close")
except TypeError as error:
    print(type(error).__name__, error)

prices["close_number"] = pd.to_numeric(prices["close"].str.replace(",", "", regex=False))
prices["stock_return"] = daily_returns(prices, "close_number")
print(prices.round(4))
TypeError unsupported operand type(s) for /: 'str' and 'str'
  ticker  day      close  close_number  stock_return
0    AAA    0      1,000      1000.000           NaN
1    AAA    1      1,010      1010.000         0.010
2    AAA    2      989.8       989.800        -0.020
3    AAA    3  1,004.647      1004.647         0.015
4    BBB    0      1,000      1000.000           NaN
5    BBB    1      1,100      1100.000         0.100
6    BBB    2        990       990.000        -0.100
7    BBB    3    1,019.7      1019.700         0.030

AAA’s return on day 1 is \(1{,}010 / 1{,}000 - 1 = 0.01\). prices.dtypes shows a column of text as object.

Why did a merge change the mean return?

A merge repeats a row for every match, so a lookup table with a repeated ticker adds rows, and the mean counts them twice. A sector table with two rows for BBB turns six returns into nine and raises the mean from 0.583% to 0.722%.

As in the lesson on merges, .merge(..., on="ticker", how="left") keeps every return. validate="many_to_one" requires each ticker to appear at most once in the lookup table and raises a MergeError otherwise. .drop_duplicates() removes the repeated row, which is safe here, because both BBB rows say Banks.

The following box shows the extra rows, the error that validate raises, and the repaired merge.

returns = prices.dropna(subset=["stock_return"])[["ticker", "day", "stock_return"]]
sectors = pd.DataFrame({"ticker": ["AAA", "BBB", "BBB"], "sector": ["Energy", "Banks", "Banks"]})

merged = returns.merge(sectors, on="ticker", how="left")
print(len(returns), len(merged), round(returns["stock_return"].mean(), 5), round(merged["stock_return"].mean(), 5))

try:
    returns.merge(sectors, on="ticker", how="left", validate="many_to_one")
except pd.errors.MergeError as error:
    print(type(error).__name__)

print(len(returns.merge(sectors.drop_duplicates(), on="ticker", how="left", validate="many_to_one")))
6 9 0.00583 0.00722
MergeError
6

How do I catch a wrong formula?

Test a function on a small input whose answer you can compute by hand. Four daily returns alternating between 1% and −1% have a sample standard deviation of \(\sqrt{4 \times 0.01^2 / 3}\), so their yearly volatility is 0.1833, and a function that gives 0.1587 has a bug.

\[ \sigma = \sqrt{252}\,\sqrt{\frac{1}{n-1}\sum_{t}(r_t - \bar r)^2} \]

Here \(r_t\) is the return on day \(t\), \(\bar r\) their mean and \(n\) the number of returns.

np.testing.assert_allclose(actual, expected, rtol=1e-12) passes silently when the two numbers agree and raises an AssertionError when they do not. np.std divides by \(n\) by default, and ddof=1 makes it divide by \(n - 1\).

The following box tests the wrong function and then the fixed one.

def yearly_volatility(returns):
    return np.std(returns) * np.sqrt(252)

test_returns = np.array([0.01, -0.01, 0.01, -0.01])
expected = np.sqrt(4 * 0.01 ** 2 / 3) * np.sqrt(252)
print(round(yearly_volatility(test_returns), 4), round(expected, 4))

try:
    np.testing.assert_allclose(yearly_volatility(test_returns), expected, rtol=1e-12)
except AssertionError as error:
    print(type(error).__name__)

def yearly_volatility(returns):
    return np.std(returns, ddof=1) * np.sqrt(252)

np.testing.assert_allclose(yearly_volatility(test_returns), expected, rtol=1e-12)
print(round(yearly_volatility(test_returns), 4))
0.1587 0.1833
AssertionError
0.1833

The ratio of the wrong answer to the right one is \(\sqrt{3/4} = 0.866\), which points to the divisor.

Your turn

Test a function total_return on BBB’s returns of days 1 and 2 against the answer from its closes, \(990 / 1{,}000 - 1\). You should see −0.01.

np.prod(1 + returns) - 1 compounds the returns.

def total_return(returns):
    return np.prod(1 + np.asarray(returns)) - 1

bbb_returns = prices.loc[(prices["ticker"] == "BBB") & prices["day"].isin([1, 2]), "stock_return"]
np.testing.assert_allclose(total_return(bbb_returns), 990 / 1000 - 1, rtol=1e-12)
print(round(total_return(bbb_returns), 4))
-0.01