Hi, I'm trying to write an SQL statement where I calculate rolling averages for different stocks, but I'm stuck now and hoping for your help. My tables contain "ShareName", "DayDate" and "EndPrice", and I want a rolling average for "EndPrice".
The code I wrote counts averages for, for example, 5 days, but since I do not have values for all days when the stock exchange is closed during the weekends, the code will count incorrectly when there are holes for weekends in the table. I would instead like it to calculate the mean value based on the number of records, for example the 5 previous records, and then sorted by date.
The other problem I have is that I want it to store the rolling average of each item in the table.
Please /Håkan
DayDate |
ShareName |
EndPrice |
2021-12-01 |
A |
5 |
2021-12-02 |
A |
4 |
2021-12-04 |
A |
5 |
2021-12-01 |
B |
2 |
2021-12-02 |
B |
3 |
Code:
SELECT A.ShareName, A.DayDate, (SELECT AVG(B.EndPrice) FROM MyTable AS B WHERE
B.ShareName = A.ShareName AND
B.DayDate >= DateAdd("d",-6, A.DayDate) AND B.DayDate <= A.DayDate) AS MA5
FROM MyTable AS A
ORDER BY A.ShareName, A.DayDate;