I have code that calculates $R^2$ with summations $$R^2 = \frac{(\sum xy - \frac1n \sum x \sum y)^2}{(\sum x^2 - \frac1n \sum x \sum x) (\sum y^2 - \frac1n \sum y \sum y)},$$ which is equivalent to $$R^2 = \frac{cov(x, y) \cdot cov(x, y)}{var(x) \cdot var(y)}.$$
I know the code is correct by benchmarking, but I have never seen this form. Can someone please explain or provide a reference? Thanks!
FWIW, the code is built for speed. It does rolling regressions and can quickly find each summation by differencing a cumulative sum.