# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 2
#     language: python
#     name: python2
# ---

# +
import matplotlib.pyplot as plt
import matplotlib.dates as pltdates
import numpy as np
import pandas as pd
import pathlib

# This tells Jupyter not to autoreload code changes on the notebook from disk
# %load_ext autoreload
# %autoreload 0

# this tells Jupyter to plot inline
# %matplotlib inline

# +
## PLOT: SMA on 3, 15 and 50 days for BTC-USD price
# -

# first, load data from CSV
btc_csv = pathlib.Path('../datasets/BTC-USD.csv').absolute()
btc = pd.read_csv(btc_csv, index_col=0, parse_dates=True)

# Calculate SMAs
sma_3 = btc.rolling(window=3).mean()
sma_15 = btc.rolling(window=15).mean()
sma_50 = btc.rolling(window=50).mean()

# +
# Plot price and SMAs
fig_1 = plt.figure(figsize=(15, 9))

# we will stack multiple line plots on the same figure
axes = fig_1.add_subplot(1, 1, 1)

axes.plot(btc.index, btc['close'], label='BTC close price')
axes.plot(sma_3.index, sma_3['close'], label = '3-days Simple MA')
axes.plot(sma_3.index, sma_15['close'], label = '15-days Simple MA')
axes.plot(sma_3.index, sma_50['close'], label = '50-days Simple MA')

# Legend, Y-axis labels and X-axis ticker formats
axes.legend(loc='best')
axes.set_ylabel('Price [$]')
axes.xaxis.set_major_formatter(pltdates.DateFormatter('%m/%y'))

# +
## PLOT: EMA on 3, 15 and 50 days for BTC-USD price
# -

# Calculate SMAs
ema_3 = btc.ewm(span=3).mean()
ema_15 = btc.ewm(span=15).mean()
ema_50 = btc.ewm(span=50).mean()

# +
# Plot price and EMAs
fig_2 = plt.figure(figsize=(15, 9))

# we will stack multiple line plots on the same figure
axes = fig_2.add_subplot(1, 1, 1)

axes.plot(btc.index, btc['close'], label='BTC close price')
axes.plot(sma_3.index, ema_3['close'], label = '3-days Exp MA')
axes.plot(sma_3.index, ema_15['close'], label = '15-days Exp MA')
axes.plot(sma_3.index, ema_50['close'], label = '50-days Exp MA')

# Legend, Y-axis labels and X-axis ticker formats
axes.legend(loc='best')
axes.set_ylabel('Price [$]')
axes.xaxis.set_major_formatter(pltdates.DateFormatter('%m/%y'))


# +
## PLOT: compare Simple and Exponential Moving Averages

# +
# Plot price and SMAs and EMAs
fig_3 = plt.figure(figsize=(15, 9))

# we will stack multiple line plots on the same figure
axes = fig_3.add_subplot(1, 1, 1)

axes.plot(btc.index, btc['close'], label='BTC close price')
axes.plot(sma_3.index, sma_15['close'], label = '15-days Simple MA')
axes.plot(sma_3.index, ema_15['close'], label = '15-days Exp MA')

# Legend, Y-axis labels and X-axis ticker formats
axes.legend(loc='best')
axes.set_ylabel('Price [$]')
axes.xaxis.set_major_formatter(pltdates.DateFormatter('%m/%y'))

# +
## PLOT: which of SMA and EMA best models price?
# -

# Let's calculate the distances between price and MAs and then compare them
sma_15_price_diff = np.absolute(btc['close'] - sma_15['close'])
ema_15_price_diff = np.absolute(btc['close'] - ema_15['close'])

# +
# Plot price and MA absolute difference
fig_4 = plt.figure(figsize=(15, 9))

# we will stack multiple line plots on the same figure
axes = fig_4.add_subplot(1, 1, 1)

axes.plot(btc.index, btc['close'], label='BTC close price')
axes.plot(sma_15_price_diff.index, sma_15_price_diff, label = '15-days SMA abs diff with price')
axes.plot(ema_15_price_diff.index, ema_15_price_diff, label = '15-days EMA abs diff with price')


# Legend, Y-axis labels and X-axis ticker formats
axes.legend(loc='best')
axes.set_ylabel('Price [$]')
axes.xaxis.set_major_formatter(pltdates.DateFormatter('%m/%y'))

# +
## SAVE MAs to CSV FILES
# -

datasets_folder = pathlib.Path('../datasets')
if not datasets_folder.exists():
    datasets_folder.mkdir()
mas_btc_csv = datasets_folder / pathlib.Path('moving_averages_BTC.csv')
mas_btc_csv.touch()
mas_df = pd.DataFrame({
    'day': btc.index,
    'sma_3': sma_3['close'],
    'sma_15': sma_15['close'],
    'sma_50': sma_50['close'],
    'ema_3': ema_3['close'],
    'ema_15': ema_15['close'],
    'ema_50': ema_50['close']
})
mas_df.set_index('day', inplace=True)
mas_df.to_csv(mas_btc_csv, index_label='day')

StarcoderdataJupyterScriptsDedupFiltered