0

I would like to calculate a moving average in Pandas. Instead of specifying the number of observations, I would like to specify the number of days. The number of observations varies every day.

Example input:

+--------+------------+------------+
| TICKER | DATE       | RATING     |
+--------+------------+------------+
| AAPL   | 05.10.2020 | 0.24080577 |
+--------+------------+------------+
| AAPL   | 05.10.2020 | 0.11473013 |
+--------+------------+------------+
| AAPL   | 05.10.2020 | 0.7327437  |
+--------+------------+------------+
| AAPL   | 06.10.2020 | 0.49492914 |
+--------+------------+------------+
| AAPL   | 06.10.2020 | 0.83926228 |
+--------+------------+------------+
| AAPL   | 07.10.2020 | 0.18731226 |
+--------+------------+------------+
| AAPL   | 07.10.2020 | 0.12772092 |
+--------+------------+------------+
| AAPL   | 07.10.2020 | 0.8952811  |
+--------+------------+------------+ 

Example output:

+--------+------------+------------+
| TICKER | DATE       | RATING     |
+--------+------------+------------+
| AAPL   | 05.10.2020 | 0.36275986 |
+--------+------------+------------+
| AAPL   | 06.10.2020 | 0.4844942  |
+--------+------------+------------+
| AAPL   | 07.10.2020 | 0.45409816 |
+--------+------------+------------+

In addition to a simple moving average I would like to use the exponentially weighted average: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html

Antoni
  • 21
  • 2
  • Can you explain more on this " specifying the number of observations, I would like to specify the number of days. The number of observations varies every day "? – Vishal Naik Aug 28 '20 at 18:26
  • Usually for a moving average you set a window of for example 5 rows. Here I would like to set a window of 5 days. Each day can have multiple rows. – Antoni Aug 28 '20 at 18:29
  • On 05.10.2020 you have 3 observations on 06.10.2020 you have 2 observation so moving average window 3 and 2 respectively did you mean like this? – Vishal Naik Aug 28 '20 at 18:32
  • The window resizes to the number of observations. Example: we want a 3 days average; today we had 2 observations, yesterday we had 4 observations, two days ago we had 3 observations -> window size= 9 – Antoni Aug 28 '20 at 18:41
  • Similar question has been answered: [https://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval](https://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval) – Antoni Aug 28 '20 at 18:56

0 Answers0