Simple coding question. How do I mean correct a set of panel data. The example here is a set of values to TSR by Year and Company, and the companies fall into categories in the variable Category

The coding I was trying is:

gen MeanTSR = 0
forvalues Y = 2005/2018 {

bysort Category: egen meanTSR`Y' = mean(TSR) if Year == Y
replace MeanTSR = meanTSR`Y' if Year == Y

}

gen corrTSR = TSR - MeanTSR

What I find is that I get the same value for all years, as if the if Year == Y was not effective.
There must be a better "Stata" way to do this.

Many thanks
Jamie