DEV Community

Josue Luzardo Gebrim
Josue Luzardo Gebrim

Posted on

Time series analysis of Bitcoin price in Python with fbprophet ?!

Analyzes the price of Bitcoin in Python using fbprophet?

Warning: This publication is not a recommendation for investing or not investing in bitcoins, if you want to know more about it, look for a duly certified specialist with experience in the subject, please!

Motivation: I was studying time series and seeing the ease of using the Python library for time series analysis, the fbprophet, I decided to apply it to a data set, via LinkedIn I received the news that the virtual bitcoin currency had a value of 100 thousand and this led me to think using fbprophet, what would be the value of that currency in a year?

https://www.seudinheiro.com/2020/bolsa-dolar/dolar-bitcoin-criptomeda-100-mil-reais/

https://www.moneytimes.com.br/bitcoin-a-r-100-mil-entenda-o-sucesso-da-corretora-brasileira-mercado-bitcoin/

Bitcoin?

It is a decentralized virtual currency and not controlled by a central bank, produced by thousands of computers around the world, 1 bitcoin is worth R$ 98,278.07 reais (December 5, 2020).

https://exame.com/mercados/entenda-o-que-e-bitcoin/

How to get bitcoin values in time series format?

To use fbprophet, a time series is needed, I started researching and found the coinbase API (cryptocurrency trading platform), and using an HTTP request with the date parameter it is possible to know the price of bitcoin in relation to the real on that date.
To make it even easier, there is a library that assists in using the coinbase API in Python:

I used the Google Colab environment with the GPU (Video Card) enabled …

Installing Coinbase library via PIP:

!pip install coinbase

Create an API access key in the coinbase and then replace ‘xpto123’ with the values provided:

api_key =  'xpto123'
api_secret = 'xpto123'
Enter fullscreen mode Exit fullscreen mode

Import the library into Python:

from coinbase.wallet.client import Client
client = Client(api_key, api_secret)
Enter fullscreen mode Exit fullscreen mode

As I’m going to use dates, I imported the Datetime library:

import datetime

I created a function to get the bitcoin’s real value on a given day:

def price_bitcoin_in_day(date_search):
    return float((client.get_spot_price(currency_pair='BTC-BRL', 
      date=date_search)).amount)
Enter fullscreen mode Exit fullscreen mode

I created a function to get the bitcoin values for a range of days:

import pandas as pd
#days = number of days searcheddef
data_bitcoin_price_in_days(days):
  # The first surveyed date is today (December 5, 2020)  date_search = datetime.date.today() 

  #price is the price in reais found.  
price = price_bitcoin_in_day(date_search)  
  #creating the list with the first values
  data = [{'day': date_search, 'price': price}]  
  # informing the number of days to be searched
  for i in range(1, days):    
      print(i)       
      # Previous day's date
      date_search = date_search - datetime.timedelta(days=1)    
      #Researching the price...
      price = price_bitcoin_in_day(date_search)      
      #Added the new values searched and their dates to the list
      data = data + [{'day' : date_search, 'price' : price}]  

#returned the complete list
return data
Enter fullscreen mode Exit fullscreen mode

Searching the last 10 years (4015 days):

dados = data_bitcoin_price_in_days(4015)

I like to use a dataframe (data structure of the Pandas library), so I turned the list into a dataframe:

df_dados = pd.DataFrame(dados)

FBprophet?

“Prophet is a procedure for forecasting time series data based on an additive model in which non-linear trends are adjusted with annual, weekly, and daily seasonality, in addition to the effects of holidays. Works best with time series with strong seasonal effects and multiple seasons of historical data. The prophet is robust for missing data and changes in trend, and usually handles outliers well. ”

FBprophet is an open-source Python library for analyzing time series maintained by the Facebook developer team.

https://facebook.github.io/prophet/

Installing the library:

!pip install fbprophet

Importing the library:

import Prophet

Renaming the columns, fbprophet only accepts data frames in this format:

df_dados.rename(columns = {'day':'ds', 'price':'y'}, inplace = True)

Training the model:

m = Prophet(changepoint_prior_scale=0.15, daily_seasonality=True)
m.fit(df_dados)
Enter fullscreen mode Exit fullscreen mode

Creating the dates for the next 365 days:

future = m.make_future_dataframe(periods=365)
future.tail()
Enter fullscreen mode Exit fullscreen mode

Predicting bitcoin values over the next 365 days:

forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
Enter fullscreen mode Exit fullscreen mode

image.png

Showing in graph form:

from fbprophet.plot import plot_plotly, plot_components_plotly
plot_plotly(m, forecast)
Enter fullscreen mode Exit fullscreen mode

image.png

The goal here is to use FBProphet, thinking that Bitcoin would provide an interesting data set.

Using the FBProphet library, we were able to prospect the amount of R$ 82,239.37 reais on December 5, 2021, that is, a devaluation of R$ 16,030.70 reais in one year.

BUT,

The model was unable to predict the recent high of bitcoin and the uncertainty of the values is visible at the end of the forecast year, making this forecast unreliable.
Personally, I don’t think this price forecast is useful looking at such a market that is likely to interfere, but it will be interesting to follow it and see how and if, Facebook’s algorithms can predict something.

NOTE: Facebook recently launched NeuralProphet, a library for analyzing time series using neural networks inspired by FBProphet and AR-Net using PyTorch.

https://github.com/ourownstory/neural_prophet

I think it is very recent, subject to changes and evolutions to be used …

References:

https://towardsdatascience.com/bitcoin-predictive-price-modeling-with-facebooks-prophet-b66efd0169a0

https://towardsdatascience.com/apple-stock-and-bitcoin-price-predictions-using-fbs-prophet-for-beginners-python-96d5ec404b77

Buy Me A Coffee

Follow me on Medium :)

Discussion (4)

Collapse
cincybc profile image
CincyBC

Have you tried this with "traditional" models like ARIMA to compare? Obrigado!

Collapse
jlgjosue profile image
Josue Luzardo Gebrim Author

not yet, who knows in the future with more data looking at more indicators, would you show me some way? I appreciate the idea, thank you :)

Collapse
cincybc profile image
CincyBC

There are lots of examples with things like ARIMA. Give it a try! machinelearningmastery.com/arima-f...

There is something called the M-competitions where different techniques are used for times series forecasting and compared (en.wikipedia.org/wiki/Makridakis_C...). Traditional statistical models regularly outperform the Deep Thinking models.

Thread Thread
jlgjosue profile image
Josue Luzardo Gebrim Author

Wow, very good, thank you very much for sharing; I will start studying this option; I do not promise anything for this year. =)