Technical indicators Moving Averages


Background

A moving average is used to determine the direction of a trend, it sums up the data points of a financial security over a specific time period and divides the total by the number of data points to arrive at an average, this could help to smooth out the price data by creating a constantly updated average price.

By calculating the moving average, the impacts of random, short-term fluctuations on the price of a financial security over a specified time frame are mitigated.

Simple moving averages (SMAs)

The simple moving average (SMA) is straightforward and it is obtained by summing the recent data points in a given set and dividing the total by the number of time periods.

Exponential moving averages (EMAs)

Esponential moving agerage (EMA) gives more weight to the most recent price points to make it more responsive to recent data points.

Python Implementation

import pandas as pd
import sqlite3

# load S&P500 data from stored database
sp500_db = sqlite3.connect(database="sp500_data.sqlite")

df = pd.read_sql_query(sql="SELECT * FROM SP500",
                       con=sp500_db,
                       parse_dates={"Date"})
df.head()

level_0indexDateTickerAdj CloseCloseHighLowOpenVolumegarmin_klass_volrsiatrmacdmacd signalbb_lowbb_midbb_high
0002014-04-29A35.04953438.12589338.30472237.17453438.1187404688612.0-0.002274NaNNaNNaNNaNNaNNaNNaN
1112014-04-29AAL33.47674235.50999835.65000234.97000135.2000018994200.0-0.000788NaNNaNNaNNaNNaNNaNNaN
2222014-04-29AAPL18.63333321.15464221.28500021.05392821.205000337377600.0-0.006397NaNNaNNaNNaNNaNNaNNaN
3332014-04-29ABBV34.03498551.36999951.52999950.75999850.9399995601300.0-0.062705NaNNaNNaNNaNNaNNaNNaN
4442014-04-29ABT31.83151838.54000138.72000138.25999838.3699994415600.0-0.013411NaNNaNNaNNaNNaNNaNNaN
# remove irrelevant columns
df = df.drop('index', axis=1)
df = df.drop('level_0', axis=1)
df.head()

DateTickerAdj CloseCloseHighLowOpenVolumegarmin_klass_volrsiatrmacdmacd signalbb_lowbb_midbb_high
02014-04-29A35.04953438.12589338.30472237.17453438.1187404688612.0-0.002274NaNNaNNaNNaNNaNNaNNaN
12014-04-29AAL33.47674235.50999835.65000234.97000135.2000018994200.0-0.000788NaNNaNNaNNaNNaNNaNNaN
22014-04-29AAPL18.63333321.15464221.28500021.05392821.205000337377600.0-0.006397NaNNaNNaNNaNNaNNaNNaN
32014-04-29ABBV34.03498551.36999951.52999950.75999850.9399995601300.0-0.062705NaNNaNNaNNaNNaNNaNNaN
42014-04-29ABT31.83151838.54000138.72000138.25999838.3699994415600.0-0.013411NaNNaNNaNNaNNaNNaNNaN
import pandas_ta

df = df.set_index(['Date','Ticker'])
# compute SMA and EMA
df['sma'] = df.groupby(level=1)['Adj Close'].transform(lambda x: pandas_ta.sma(close=x,length=20))
df['ema'] = df.groupby(level=1)['Adj Close'].transform(lambda x: pandas_ta.ema(close=x,length=20))
df.tail()

Adj CloseCloseHighLowOpenVolumegarmin_klass_volrsiatrmacdmacd signalbb_lowbb_midbb_highsmaema
DateTicker
2024-04-25XYL130.610001130.610001131.199997128.100006129.619995963600.00.00026461.4827450.6653060.3551460.2552764.8455914.8635024.881413128.482000128.582695
YUM141.559998141.559998142.169998140.389999141.9799961693100.00.00007665.6681630.3225660.5508300.2857844.9134824.9379684.962454138.497000138.658563
ZBH119.750000119.750000121.349998118.769997120.7099991078800.00.00020635.636078-0.350196-0.889200-0.6464804.7728464.8358884.898931125.012999123.565569
ZBRA292.529999292.529999293.290009271.630005274.359985674700.00.00135556.1722720.500501-0.391439-0.2424565.5887305.6663875.744044288.205502284.262362
ZTS153.360001153.360001153.589996150.039993150.9700014567200.00.00017839.8096191.374957-3.202379-3.5843534.9674085.0650655.162723157.579352157.003521
# update the database
df = df.reset_index()
df.to_sql(name="SP500",
          con=sp500_db,
          if_exists="replace",
          index=True)
sp500_db.close()
import plotly.graph_objs as go
from datetime import datetime

# select AAPL
aapl = df[df['Ticker'] == 'AAPL'].set_index('Date')

# only select the data from 2023-01-01
aapl_new = aapl[aapl.index > datetime(2023,1,1)]

# create a Plotly figure
fig = go.Figure()

# add the price chart
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['Adj Close'], mode='lines', name='Adj Close Price'))

# add the SMA chart
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['sma'], mode='lines', name='SMA'))

# add the EMA chart
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['ema'], mode='lines', name='EMA'))

# Customize the chart layout
fig.update_layout(title='AAPL Stock Price with Moving Averages',
                  xaxis_title='Date',
                  yaxis_title='Price',
                  showlegend=True)

# Show the chart
fig.show()

AAPL Moving Averages


Author: wenvenn
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source wenvenn !