moving average in python

Moving average is a popular method of smoothing data. It is widely used in time series analysis to identify and eliminate patterns within the data. In Python, moving average can be easily calculated using the Pandas library.

Here's a code snippet that demonstrates how to calculate the 10-day moving average of a time series using Pandas:

main.py
import pandas as pd

# create a sample time series
data = {'date': pd.date_range(start='2021-01-01', end='2021-01-31'),
        'value': [1, 3, 2, 4, 6, 5, 7, 8, 9, 10, 12, 11, 14, 16, 15, 17, 19, 20, 22, 21, 24, 25, 23, 22, 20, 18, 17, 19, 21, 23, 24]}
df = pd.DataFrame(data)

# calculate the 10-day moving average
df['rolling_mean'] = df['value'].rolling(window=10).mean()

print(df)
387 chars
12 lines

In the code above, we first create a sample time series that contains the date and value columns. We then use the rolling() method to compute the rolling mean of the value column over a window of 10 periods. Finally, we create a new column called 'rolling_mean' to store the computed moving averages. The output is then displayed using the print() function.

Running the code above will produce the following output:

main.py
         date  value  rolling_mean
0  2021-01-01      1           NaN
1  2021-01-02      3           NaN
2  2021-01-03      2           NaN
3  2021-01-04      4           NaN
4  2021-01-05      6           NaN
5  2021-01-06      5           NaN
6  2021-01-07      7           NaN
7  2021-01-08      8           NaN
8  2021-01-09      9           NaN
9  2021-01-10     10           5.7
10 2021-01-11     12           6.7
11 2021-01-12     11           7.0
12 2021-01-13     14           7.5
13 2021-01-14     16           8.4
14 2021-01-15     15           9.3
15 2021-01-16     17          10.2
16 2021-01-17     19          11.4
17 2021-01-18     20          12.6
18 2021-01-19     22          14.1
19 2021-01-20     21          14.8
20 2021-01-21     24          16.1
21 2021-01-22     25          17.1
22 2021-01-23     23          18.3
23 2021-01-24     22          18.4
24 2021-01-25     20          18.4
25 2021-01-26     18          18.4
26 2021-01-27     17          17.9
27 2021-01-28     19          17.9
28 2021-01-29     21          18.2
29 2021-01-30     23          18.6
1085 chars
32 lines

gistlibby LogSnag