logo

Lucas Katayama/Moving Averages

Created Mon, 14 Aug 2023 13:40:54 -0300 Modified Mon, 14 Aug 2023 13:40:54 -0300

Moving Averages

This docs exaplain 3 types of moving averages:

  • Simple Moving Average (SMA)
  • Smooth Moving Average (SMMA)
  • Exponential Moving Average (EMA)

Preparing data

Importing libraries

import plotly.graph_objs as go
from plotly.offline import iplot
import pandas as pd
import requests
from datetime import datetime, timedelta

Getting candles


window = 10
precision = "1h"
end = datetime.now()
start = end - timedelta(days=window)


params = "?precision={}&from={}&to={}".format(precision, start.strftime("%s"), end.strftime("%s"))
resp = requests.get("https://www.mercadobitcoin.com.br/v4/BRLBTC/candle" + params)
if resp.status_code != 200:
  print("something went wrong")

data = resp.json()["candles"]
print(data)
df = pd.DataFrame.from_dict(data)
df.columns = ['time', 'open', 'close', 'high', 'low', 'volume']
df["time"] = pd.to_datetime(df["time"], unit="s", utc=True)


candle = go.Candlestick(
    x=df['time'],
    open=df['open'].tolist(),
    close=df['close'].tolist(),
    high=df['high'].tolist(),
    low=df['low'].tolist(),
    name='Candles',
)

Simple Moving Average

A simple moving average (SMA) is an arithmetic moving average calculated by adding recent prices and then dividing that by the number of time periods in the calculation average.

df["sma"] = df['close'].rolling(window=window).mean()

smafig = go.Scatter(
    x=df['time'],
    y=df['sma'],
    name='Simple Moving Average',
    line=dict(color='rgba(204, 102, 0, 50)', width=1)
)

go.Figure(data=[candle, smafig])

Smooth Moving Average

A Smoothed Moving Average is an Exponential Moving Average, only with a longer period applied. The Smoothed Moving Average gives the recent prices an equal weighting to the historic ones. The calculation does not refer to a fixed period, but rather takes all available data series into account. This is achieved by subtracting yesterday’s Smoothed Moving Average from today’s price. Adding this result to yesterday’s Smoothed Moving Average, results in today’s Moving Average.

from pyti.smoothed_moving_average import smoothed_moving_average as sma

profit = 1.02
factor = 0.03
fsma_window = window
ssma_window = window * 3

df['fast_smma'] = sma(df['close'].tolist(), fsma_window)
df['slow_smma'] = sma(df['close'].tolist(), ssma_window)

buy_signals = []
for i in range(1, len(df['close'])):
    ssma = df['slow_smma'][i]
    price = df['low'][i]
    # 3% greater than the lower price
    if ssma > price and (ssma - price > factor * price):
        buy_signals.append([df['time'][i], price])

plots = []
if len(buy_signals) > 0:

  ts = [item[0] for item in buy_signals]
  sell = [item[1] * profit for item in buy_signals]
  buy = [item[1] for item in buy_signals]

  buys = go.Scatter(
      x=ts,
      y=buy,
      name='Buy signals',
      mode='markers',
      marker_color='rgba(128, 128, 128, .8)'
  )

  sells = go.Scatter(
      x=ts,
      y=sell,
      name='Sell signals',
      mode='markers',
      marker_color='rgba(0, 128, 255, .8)'
  )
  plots += [buys, sells]

fsmmafig = go.Scatter(
    x=df['time'],
    y=df['fast_smma'],
    name='Fast Smooth Moving Average',
    line=dict(color='rgba(255, 204, 153, 20)', width=1)
)

ssmmafig = go.Scatter(
    x=df['time'],
    y=df['slow_smma'],
    name='Slow Smooth Moving Average',
    line=dict(color='rgba(255, 128, 0, 20)', width=1)
)


plots += [candle, fsmmafig, ssmmafig]


go.Figure(data=plots)

Exponential Moving Average

An exponential moving average (EMA) is a type of moving average (MA) that places a greater weight and significance on the most recent data points. The exponential moving average is also referred to as the exponentially weighted moving average. An exponentially weighted moving average reacts more significantly to recent price changes than a simple moving average (SMA), which applies an equal weight to all observations in the period.

from pyti.exponential_moving_average import exponential_moving_average as ema

df["ema"] = pd.DataFrame(ema(data=df["close"].tolist(), period=window))

emafig = go.Scatter(
    x=df['time'],
    y=df['ema'],
    name='Exponential Moving Average',
    line=dict(color='rgba(255, 178, 102, 50)', width=1)
)

go.Figure(data=[candle, emafig])

Comparison

go.Figure(data=[candle, smafig, ssmmafig, fsmmafig, emafig])