---
# System prepended metadata

title: Python - Moving Average(MA)
tags: [Technical Analysis, Python]

---

# Python - Moving Average(MA)

## Drawing Moving Average from Scratch
* import packages

```python
import pandas as pd
import matplotlib.pyplot as plt
from statistics import mean
```

* Read in data(Take Taiwan Index Futures(TXF) for example)
```python
txf_30 = pd.read_csv("TXF_30.csv")
txf_30.head()
```
![](https://hackmd.io/_uploads/SJX95r4Ja.png)


### Method 1: define average function
```python
def my_average(data):
    return sum(data) / len(data)
```

### Method 2: use mean method from statistics library

Code
```python
# n represents n days in a interval
n = 30

# create a temp list to calculate average
prices = []

# initialize two new columns in TXF_30.csv

txf_30["MA_avg"] = -1
txf_30["MA_mean"] = -1

for index, close in enumerate(txf_30["close"]):
    # if elements in temp_num is less then n-days interval, then add elements
    if len(prices) < n:
        prices.append(close)

    else:
        prices.append(close)
        if len(prices) == n:
            continue
        # when the len is larger than n, pop the first one
        prices.pop(0)
        avg = my_average(prices)
        ma = mean(prices)

        # update back to csv file
        txf_30.loc[index, "MA_avg"] = avg
        txf_30.loc[index, "MA_mean"] = ma
```

### Method 3: use rolling() from pandas
```python
txf_30["MA"] = txf_30["close"].rolling(n).mean()
```
![](https://hackmd.io/_uploads/rkycoSE16.png)


### Plot
```python
fig, ax = plt.subplots(1, 1, figsize=(20, 10))

plt.title("TXF_30_Close and " + f"{n}" + "MA")
plt.plot(txf_30["close"].astype(float), color="c", label="close")
plt.plot(txf_30["MA"].astype(float), color="r", label=f"{n}MA")

plt.show()
```
![](https://hackmd.io/_uploads/ryXk3HN16.png)

