Time series analysis of Bitcoin price in Python with fbprophet ?!
Tags: python, machinelearning, bitcoin, datascience
Published: 2021-12-22 23:44:51

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'
``` 

Import the library into Python:


```Python
from coinbase.wallet.client import Client
client = Client(api_key, api_secret)
``` 

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)
``` 

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


```Python
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
``` 

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:

```Python
m = Prophet(changepoint_prior_scale=0.15, daily_seasonality=True)
m.fit(df_dados)
```

Creating the dates for the next 365 days:

```Python
future = m.make_future_dataframe(periods=365)
future.tail()
```
Predicting bitcoin values over the next 365 days:
```Python
forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639867090187/WfHaJ7mEZ.png)

Showing in graph form:

```
from fbprophet.plot import plot_plotly, plot_components_plotly
plot_plotly(m, forecast)
```


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639867127496/8b_F8B2Mq.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

 <a href="https://www.buymeacoffee.com/jlgjosue" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a> 

Follow me on [Medium](https://jlgjosue.medium.com/)  :)