# simple moving average python numpy:A Guide to Using the Simple Moving Average in Python and NumPy

*author*

A Guide to Using the Simple Moving Average in Python and NumPy

The simple moving average (SMA) is a popular technical indicator used in financial markets to help analyze the price action of a security or stock. It provides a snapshot of the average price over a specified time period, which can help identify trends and support/resistance levels. In this article, we will explore how to calculate the simple moving average using Python and the NumPy library.

What is the Simple Moving Average?

The simple moving average (SMA) calculates the average price of a security over a specific time period, usually one period per trading day. The calculation is based on the closing price for each trading day, and the weight given to each price is proportional to the time elapsed since the last trading day. The SMA helps identify trends, provide support and resistance levels, and provide an early warning signal when a security's price is about to break a trend.

Calculating the Simple Moving Average in Python and NumPy

To calculate the simple moving average in Python and NumPy, we first need to import the necessary libraries. In this case, we will use the NumPy library for mathematical calculations and pandas for data manipulation.

```python

import numpy as np

import pandas as pd

```

Next, we will create a data frame with the required columns: the closing price of each trading day and the number of periods (time weight).

```python

data = pd.DataFrame({

'Date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],

'Close': [100, 150, 125, 175, 140]

})

```

Now, we will calculate the simple moving average using the NumPy library. We will set the number of periods to 3, which means that the most recent price will have a weight of 1, the next price will have a weight of 2, and the next price will have a weight of 3.

```python

data['SMA_3'] = np.sa.umax(data['Close'], m=3)

```

Finally, we will plot the price and the simple moving average to visualize the result.

```python

import matplotlib.pyplot as plt

plt.plot(data['Date'], data['Close'], label='Close Price')

plt.plot(data['Date'], data['SMA_3'], label='Simple Moving Average (3 Periods)')

plt.xlabel('Date')

plt.ylabel('Price')

plt.title('Simple Moving Average in Python and NumPy')

plt.legend()

plt.show()

```

The simple moving average is a powerful technical indicator that can help investors and traders better understand the price action of a security or stock. In this guide, we showed how to calculate the simple moving average in Python and NumPy using the `numpy.savgol_auto()` function. By understanding how to use the simple moving average, you can better navigate the financial markets and make more informed investment decisions.

comentsHave you got any ideas?