Calculating Downside Beta with daily returns

#1
Dear Stata community,

I am desperate for help regarding Stata, since I am a total beginner and not sure how I am supposed to handle this problem.

I am currently working on a project where I have to calculate the downside Beta of around 2,010 companies. I have the daily stock returns for every company between the years 2007 and 2016. Furthermore, I have the S&P 500 Composite Index's daily returns for the time range as well. Calculating a downside Beta basically means that I calculate the firm's Beta in times when the market index (S&P 500) performs below a certain benchmark (in this case 0). My dataset is set up as follows:

YYYYMMDD AAA X Y
YYYYMMDD AAA X Y
YYYYMMDD AAA X Y
...
YYYYMMDD AAA X Y
YYYYMMDD BBB X Y
YYYYMMDD BBB X Y
YYYYMMDD BBB X Y
...

YYYYMMDD is the format of date. AAA and BBB symbolise the tickers of the companies. X are the company daily stock returns and Y are the S&P 500 daily stock returns.

This dataset now only includes the dates where the S&P 500 Return has performed below the benchmark (0). Basically, the dataset can be compared to panel data, whereby the time range is repeated for every company. Since the dataset has already been sorted for the 'downside' situations, I basically have to conduct a normal Beta calculation now for every company. However, what I need is the Beta for each company in each year (2007-2016). The formula that I need to utilise for the Beta calculation is: B = cov(ri,rm)/var(rm) whereby ri = asset i's return (I am using daily returns), rm = market return (the S&P 500 daily return), cov = covariance, and var = variance.

I would be incredibly grateful for any help regarding this matter and would be very happy about an answer from you.

Cheers,

Konstantin