How do I attach a group’s value to every row with transform?
Put each day’s mean return on every stock’s row with groupby transform, attach each stock’s cumulative return to the right rows, and see why apply with group_keys=True does not fit back into the panel.
After this lesson, you can put a group’s result, such as the day’s mean return, on every row of a panel.
How do I put the day’s mean on every row?
.groupby("date")["stock_return"].transform("mean") computes each date’s mean and repeats it on every row of that date, so the result has one value per row, 24, while .mean() gives one per date, 8. On 2 March, the mean of the three returns is 0.29%, and AAA’s return of 1.20% is 0.91 percentage points above it.
Here \(r_{j,t}\) is stock \(j\)’s return on day \(t\), \(\bar r_t\) the day’s mean, which is the return of a portfolio with a third in each stock, and \(e_{j,t}\) the stock’s excess return.
The panel holds three made-up stocks’ daily returns in decimals on eight weekdays, one row per stock and date. np.repeat repeats each date three times and np.tile repeats the three tickers eight times, as in the lesson on joining arrays, and .ravel() reads the return matrix row by row in the same order. Assigning the eight date-labelled means directly leaves all 24 rows missing, because pandas matches the dates with the row numbers 0 to 23.
The following box puts the day’s mean on every row and computes the excess returns.
A function passed to .transform() gets each stock’s returns and returns one value per row, so cumulative_return, which compounds the returns, attaches each stock’s cumulative return to its own rows. AAA’s cumulative return is 0.3398% after two days and 0.96% through 11 March.
\[
C_{j,t} = \prod_{s \le t} (1 + r_{j,s}) - 1
\]
.apply(cumulative_return) gives the same numbers, but its default group_keys=True adds the ticker to the row labels, so assigning the result to the panel raises a TypeError. group_keys=False keeps the panel’s row numbers.
The following box attaches the cumulative returns and tries the default apply.
For 2 March, print each stock’s excess return divided by the day’s sample standard deviation, rounded to three decimals. You should see 0.989 for AAA, −1.011 for BBB and 0.022 for CCC.
TipShow answer
transform("std") puts each day’s standard deviation on the day’s three rows.