In this post/Jupyter Notebook we'll look at Time Series and theory surrounding them.
⚠️Please be aware that this blog is much easier and nicer to read directly in
Colab 👆 or through GitHub!
[CA]: Time Series #1 - Decomposing & Working with Time Series
This CA is originally found on kaggle.com/lundet/.., as we entered a competition to predict cryptocurrency prices - G-Research Crypto Forecasting.
N.B. This blog/notebook is adapted into a Jupyter notebook that's easier to replicate, that is we don't use the Kaggle API + GBs of data that was required for said competition.
- Part One - Decomposing & Working with Time Series (theoretical) ()
- Part Two - Predicting Stock Prices (Time Series) using classical Machine Learning ()
- Part Three -Forecasting Cryptocurrency Prices (Time Series) using Deep Learning (PyTorch, Tensorflow/Keras & darts) ()
Moving on to the content! 🤓
Time Series Concepts
Time Series has some important attributes that are unique compared to other data types such as
Time Series can be decomposed into multiple other time series that together compose the decomposed one (composition baby!).
As shown above we can build a time series out of a
Seasonality, that means we can also decompose the
This can be done in a few ways, mostly either through a
- Additive means that if we add
Seasonalitytogether we create
- Multiplicative means that if we multiply
Seasonalitytogether we create
But these two are not enough to compose a full time series, usually we have noise too.
It seems we're onto something. But still it's not really how we usually see time series!
What else is left? Autocorrelation!
Autocorrelation is a correlation between two observation at different time steps, if values separated by an interval have an strong positive or negative correlation it's indicated that past values influence the current value.
To keep it simple, if a time series is autocorrelated it's new state has a correlation with a earlier step.
And there we go! 😎
We got a legit timeseries, pat yourself on your back and be proud. We did it.
Let's get started with real data... 🧑💻
Installation & Importing
We need to have libraries which allows us to simplify operations and focus on the essential.
DataFramelibrary that allows you to visualize, wrangle, and investigate data in different ways
numpyis a math library which is implemented in
Fortranand combined with vectorized code it's incredibly fast!
- This is key in Python as Python is a really slow language.
pandas_datareadergives us easy access to different data formats, directly in
plotlygives your plots the next level interactivity that you've always wanted
from IPython.display import clear_output
!pip install -U pandas_datareader
!pip install plotly
!pip install matplotlib
!pip install seaborn
!pip install statsmodels
And importing our libraries
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import numpy as np # linear algebra
import pandas_datareader as pdr
from datetime import datetime
Reading Cryptocurrency Data
pandas_datareader we can query multiple API:s, and among them Yahoo.
Yahoo as a financial API that follows stocks, currencies, cryptocurrencies and much more!
Let's see what we can do.
df = pdr.get_data_yahoo('BTC-USD', start=datetime(2020, 1, 1), end=datetime(2022, 1, 1))
The data seems great, but one should always validate it visually and programmatically.
How about plotting it first?
Plotting can be done in multiple ways, let's start using the
pandas way. 🐼
Make plots of Series or DataFrame.
Includes options like
density) and much more.
Let's add some interactivity to this, and plot
High on top of that!
Super simple using
plotly as the backend! 😎
df[['Close', 'High', 'Low']].plot(backend='plotly')
Show plotly chart (as it's invisible in blog-mode)
You can also plot a candle-stick chart by using
import plotly.graphical_objects as go
fig = go.Figure(data=[go.Candlestick(x=df.index,
The data does look nice, but we need to figure if there's any issues in the data.
Graphs might be missing some values that are not clearly visible as there's so much data. Our final data validation should always be programatical.
Validating that data makes sense and that there's no errors is very important when you're building models. Having outliers, errors and other things can lead to some really weird behaviour.
There's a few tools we can use:
Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values.
Can we we make this more readable?
.any(), or even 'cheating' using
Adj Close False
df.isna().any().any() # 👀
Next up: Validating that there's no missing days
This can be done in multiple ways, but for now I choose to use
pd.DataFrame.diff: First discrete difference of element.
Bonus: Diff can also handle
periodbeing how far to diff.
Name: Date, dtype: float64
Ok, so we've got a series. Try to validate that no
diff is greater than 1 day using a broadcasted/vectorized operation.
pandasautomatically broadcast operations by operator overloading, e.g.
I think we can call quits on the validation part for now.
Let's move on to different ways we can format the data, a common format is
Because data is very different moving in time we wish to normalize the data somehow. This can be done in multiple ways, some common ways are:
pd.DataFrame.diffwhich takes the difference between x_1 and x_2
- The negative aspect of this is that the difference is still not scaled
pd.DataFrame.pct_changewhich validates the % difference
LogReturnwhich is the logarithmic return between each time step (x_1, x_2, ..).
- Apply a
Scalerwhich scales the data somehow
- Can be
Maxto (0,1) or (-1,1)
- Can be a
MeanScalerwhich scales the data to have a mean of 0.
... and more.
We'll start of with
LogReturn which is common in forecasting of stocks.
def log_return(series, periods=1):
df['LogReturn'] = log_return(df['Close'])
Name: LogReturn, dtype: float64
.diff takes the diff with the next element you'll end up with a
NaN, as such we wish to remove the first element.
df = df[1:]
Name: Close, dtype: float64
For now we'll leave it here and move on to looking at
Data Analysis: Correlation
df = pdr.get_data_yahoo(['BTC-USD', 'ETH-USD'], start=datetime(2020, 1, 1), end=datetime(2022, 1, 1))
And retrieving only the
Close to have something to compare.
df = df['Close']
Let's validate the correlation, e.g. how our values correlate to each other!
The correlation looks pretty high... We can use
seaborn to show even better data by adding the plots.
import seaborn as sns
<seaborn.axisgrid.PairGrid at 0x7f122c88e6d0>
Indeed, looks very correlated! 🤩
What conclusions can we take from the above chart? Cryptocurrencies using daily data are indeed correlated, that is ETH prices depends on BTC and v.v.
This blog is getting close to its end, and as such we won't go further in depth of this.
For the reader an excercise would be to predict the BTC price depending on ETH, which should be possible based on this correlation. We'll go further into this later.
Data Analysis: Decomposition
Decomposing Time Series means that we try to find seasonality, trends and other things. This can be done using
statsmodels which is a very impressive library that originally was done in
R but now exists in Python.
from statsmodels.tsa.seasonal import seasonal_decompose
res = seasonal_decompose(df['BTC-USD'])
Looks nice and dandy! But we can modify this further by adding
freq parameter to validate how it looks by decomposing either through
additive, and updating the
period in the newest version) to decompose it based on different periods.
res = seasonal_decompose(df['BTC-USD'], model='additive', period=365) # Try weekly or monthly decomposition.
We're now looking at our final data analysis step, Fast Fourier Transform, A.K.A. FFT!
Data Analysis: FFT
We'll also add an Fast Fourier Transform which can show which frequencies the data "resets" at.
import numpy as np
import matplotlib.pyplot as plt
fft = np.fft.rfft(df['BTC-USD'])
plt.xticks([1, 365.2524], labels=['1/Year', '1/day'])
_ = plt.xlabel('Frequency (log scale)')
That's it for this time. Make sure to view part 2 if you want to start predicting some data, and in part 3 we'll do the final prediction where we'll look at different forecast horizons!
To learn more about Time Series and how one can analyze them please view the other parts,