Calculating the Simple Moving Average in Python

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@chasmic-cosm·
0.000 HBD
Calculating the Simple Moving Average in Python
![simple moving average 1.png](https://images.hive.blog/DQmdtGVzkhvk4tQning8iGQutk6FUezBS9kQuFyzn2T75Rv/simple%20moving%20average%201.png)

# Theory

Moving averages are used as a basis for many technical indicators. A moving average is a sort of *local* average around a given point. In signal processing terms the moving average acts as a lowpass filter, removing high frequency "noise" from the signal.

# Implementation

The `signal` parameter is a one dimensional array. It makes sense to use the [typical price](https://hive.blog/investing/@chasmic-cosm/calculating-the-typical-price-of-an-asset-in-python) as this input. 

```python
import numpy as np

def simple_moving_average(signal, points):
    """
    Calculate the N-point simple moving average of a signal


    Inputs:
        signal: numpy array -   A sequence of price points in time
        points: int         -   The size of the moving average

    Outputs:
        moving_average:     numpy array -   The moving average at each point in the signal
    """
    moving_average = np.zeros(len(signal))

    for i in range(points):
        moving_average[i] = np.sum(signal[0:i + 1])/(i+1)

    for i in range(points, len(signal)):
        moving_average[i] = np.sum(signal[i + 1 - points:i + 1])/(points)

    return moving_average
```
# Results

Comparing the simple moving average to the typical price reveals the behaviour of the SMA: it is smoother than the typical price signal and it lags behind the typical price signal.

![sma vs typical price.png](https://images.hive.blog/DQmeEgx1hMTZbpRPYngj3JKFeLhCkWcYkLhgj1UofB7DAuC/sma%20vs%20typical%20price.png)

It is also worth comparing moving averages of different periods:

![sma 10 vs 20.png](https://images.hive.blog/DQmVQU3P7yAYxLRBdZ5UAVTMLTCjdBhYZaG7Ygq5PHErTZ2/sma%2010%20vs%2020.png)

Note that the 20 point moving average is smoother than the 10 point moving average and lags even further behind the typical price.

Posted Using [LeoFinance](https://leofinance.io/@chasmic-cosm/calculating-the-simple-moving-average-in-python)
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,