❌

Normal view

Simulation of the bitcoin price with the Monte Carlo method

4 December 2022 at 20:13

We are going to launch ourselves to carry out a simulation of the bitcoin price with the Monte Carlo method together with the Black-Scholes-Merton model and thus calculate the different price predictions from a year ago to today. It is a simulation with some evil, since a year ago we were close to the maximum price (ATH) and this last year the price of BTC has suffered one of the biggest falls in its history, but that is exactly what we want to see what percentage of the paths generated by this method are close to the current reality of the BTC price, in one of the most complicated scenarios that can occur. To clarify, first of all, that a Monte Carlo simulation with the Black-Shcoles-Merton equation does not seem to be a good method to predict the price of bitcoin in such a long term, since the degree of randomness is very high this due to the variability of supply and demand, the difficulty of estimating a possible fundamental value as there are no underlying assets and also being influenced by macroeconomic data that ultimately intervenes as an exogenous variable, make, in my opinion, that the price evolution is incalculable one year ahead.

What is the Monte Carlo method?

They are a set of techniques that allow obtaining solutions to mathematical, physical, economic problems… through repeated random tests.

With the Monte Carlo method possible resulting scenarios (simulations) are generated from a series of initial data and one or more random variables, the different resulting solutions can be used to calculate formulas, such as in the case of calculating the number pi, to forecast possible future scenarios as in the case that we will deal with here when using it together with the Black-Sholes-Merton stochastic equation and for many other uses within mathematics, physics, economics…

Yahoo Finance module for Python is installed.

!pip install yfinance > /dev/null

The libraries to be used in the study are imported.

import pandas as pd import numpy as np import math from time import time import requests import matplotlib.pyplot as plt import yfinance as yf import plotly.express as px import seaborn as sns import warnings warnings.filterwarnings(‘ignore’)

The bitcoin price data is downloaded from Yahoo finance.

df = yf.download('BTC-USD', interval = '1d')[['Close']]

[100%**] 1 of 1 completed

This is the formula of the Black-Scholes-Merton (1973 stochastic differential equation (SDE) economic model that we will use to generate the simulation.

The Euler discretized version of SDE is used to make it easier to convert to Python code.

Calculation of the necessary parameters for the equation.

# Parameters: sigma, r, S0, dt, I

# Calculation of volatility, in the formula it refers to the intrinsic but we will use the annualized
volatility_days = 30
df['pct_change'] = df['Close'].pct_change()*100
df['stdev'] = df['pct_change'].rolling(volatility_days).std()

# Number of annual daily sessions. In the case of the stock market it is 252 but for bitcon it is 365 because it works every day
df['vol'] = df['stdev']*(365**0.5)
df.dropna(inplace=True)

sigma = df.vol.mean() / 100

# Maturity. Option expiration date. We set it to 1
T = 1

# Calculation of r (riskless short rate)
# The rate of return expected by investors (r) can be estimated from the CAMP model
# r = rf + beta * mrp
# rf: is the risk-free rate -> rf = 0.0020
# mrp: is a market risk premium. -> mrp = 0.0438
r = 0.0020 + 0.94 * 0.0438

# The number of days to simulate
M = 365

# Closing price of bitcoin from which the simulation will start
S0 = df.Close[-M]

# Length of time interval
dt = T / M

# Number of paths to simulate
I = 20000 

print("S0, initial day: \t", S0)
print("r, riskless short rate: ", r)
print("M, number of days: \t", M)
print("I, paths simulating: \t", I)

S0, initial day: 49368.84765625
r, riskless short rate: 0.043171999999999995
M, number of days: 365
I, paths simulating: 20000

# Simulating I paths with M days (time steps)
S = S0 * np.exp(np.cumsum((r - 0.5 * sigma ** 2) * dt + sigma * math.sqrt(dt) * np.random.standard_normal((M + 1, I)), axis=0))
S[0] = S0

The graph with 20 simulations plus the variation of the real price is shown in black (+).

# Real price ot BTC
real = df[(df.index > df.index[-M])]['Close']

plt.figure(figsize=(18,8))
plt.title('Bitcoin simulation Monte Carlo last year')
plt.plot(real.values, 'k+')
plt.plot(S[:, :20])
plt.grid(True)
plt.xlabel('Days')
plt.ylabel('BTC(USD)')

Graph with the distribution of the closing prices simulated at the end of the 365 days with two vertical lines in red indicating the values above and below 10% and with the real price line in black.

closing_prices = S[-1]
top_ten = np.percentile(closing_prices, 100-10)

# Pull bottom 10% of possible outcomes
bottom_ten = np.percentile(closing_prices, 10);

plt.figure(figsize=(18,8))
plt.hist(closing_prices, bins=100)
plt.axvline(top_ten,color='r', linestyle='dashed', linewidth=2)
plt.axvline(bottom_ten,color='r', linestyle='dashed', linewidth=2)
plt.axvline(real.values[-1],color='k', linestyle='dashed', linewidth=2)
plt.xlabel('BTC Price')
plt.ylabel('Frequency')
plt.show()
print("Expected BTC price: \t", round(np.mean(closing_prices), 2)) print("Quantile (5%): \t\t", np.percentile(closing_prices, 5)) print("Quantile (95%): \t", np.percentile(closing_prices, 95))

Expected BTC price: 51892.19
Quantile (5%): 13656.425038591678
Quantile (95%): 124992.2848675734

Number of simulations that have been generated, including those with a lower price than today and the percentage that these represent with respect to the total.

df1_T = pd.DataFrame(S[-1:, :I]).T df1_T.columns = ['btc_price_last_day'] print("Nº simulations: \t\t\t", df1_T.count()) print("Nº simulatios less price today: \t", df1_T[(df1_T['btc_price_last_day'] < df.Close[-1])].count()) print("Average simulatios less price today: \t", df1_T[(df1_T['btc_price_last_day'] < df.Close[-1])].count()*100/df1_T.count())

Nº simulations: btc_price_last_day 20000
Nº simulatios less price today: btc_price_last_day 1864
Average simulatios less price today: btc_price_last_day 9.32

Conclusions

We have spent a year with one of the biggest BTC price drops in history, several factors have come together, unfavorable macroeconomic news for the economy, the fall of large crypto companies with the loss of funds from their clients and also within the periods cyclical events that occur every 4 years in bitcoin due to the halving we are in the part that has historically been bearish. As we mentioned at the beginning, the Monte Carlo simulation is not useful for us to predict the price one year ahead, but it is useful for us to know that of all the possible scenarios we are close to 5% worse, which indicates what has been said, we are fully involved in a crypto winter.

Daily simulation update on this page “Simulation of the price of BTC with Monte Carlo“.

Simulación del precio de bitcoin con el método de Monte Carlo

24 November 2022 at 13:47

Vamos a lanzarnos a realizar una simulación del precio de bitcoin con el método de Monte Carlo junto con la ecuación del modelo Black-Scholes-Merton para así calcular las diferentes predicciones del precio desde hace un año hasta hoy. Es una simulación con cierta maldad, ya que hace un año estábamos cerca del máximo de precio (ATH) y este último año el precio de BTC ha sufrido una de las mayores caídas de su historia, pero es justamente eso lo que queremos ver que porcentaje de los caminos generados por este método se acercan a la realidad actual del precio BTC, en uno de los escenarios más complicados que se pueden dar. Aclarar, antes que nada, que una simulación de Monte Carlo con la ecuación de Black-Shcoles-Merton no tiene pinta de ser un buen método para predecir el precio de bitcoin a tan largo plazo, ya que el grado de aletoriedad es muy alto de este debido a la variabilidad de la oferta y la demanda, la difícultad de estimar un posible valor fundamental al no haber activos subyacentes y además estar influenciado por los datos macroeconomía que al final interviene como una variable exógena, hacen, en mi opinión, que la evolución del precio sea incalculable a una año vista.

¿Qué es el método de Monte Carlo?

Son un conjunto de técnicas que permiten obtener soluciones a problemas matemáticos, físicos, económicos… por medio de pruebas aleatorias repetidas.

Con el método de Monte Carlo se generan posibles escenarios resultantes (simulaciones) a partir de una serie de datos iniciales y una o varias variables aleatorias, las diferentes soluciones resultantes se pueden utilizar para calcular fórmulas, como en el caso del cálculo del número pi, para pronosticar posibles escenarios futuros como en el caso que trataremos aquí al usarlo junto a la ecuación estocástica de Black-Sholes-Merton y para otros muchos usos dentro de la matemática, física, economía…

Se instala el módulo de finanzas para Python de Yahoo.

!pip install yfinance > /dev/null

Se importan las bibliotecas que se utilizarán en el estudio.

import pandas as pd
import numpy as np
import math
from time import time
import requests
import matplotlib.pyplot as plt
import yfinance as yf
import plotly.express as px
import seaborn as sns
import warnings

warnings.filterwarnings('ignore')

Se descargan los datos del precio de bitcoin de Yahoo finance.

df = yf.download('BTC-USD', interval = '1d')[['Close']]

[100%**] 1 of 1 completed

Esta es la fórmula del modelo económico de Black-Scholes-Merton (1973 stochastic differential equation (SDE) que utilizaremos para generar la simulación.

Se utiliza la versión discretizada de Euler de SDE para que sea más fácil convertirla en código Python.

Cálculo de los parámetros necesarios para la ecuación

# Parameters: sigma, r, S0, dt, I

# Calculation of volatility, in the formula it refers to the intrinsic but we will use the annualized
volatility_days = 30
df['pct_change'] = df['Close'].pct_change()*100
df['stdev'] = df['pct_change'].rolling(volatility_days).std()

# Number of annual daily sessions. In the case of the stock market it is 252 but for bitcon it is 365 because it works every day
df['vol'] = df['stdev']*(365**0.5)
df.dropna(inplace=True)

sigma = df.vol.mean() / 100

# Maturity. Option expiration date. We set it to 1
T = 1

# Calculation of r (riskless short rate)
# The rate of return expected by investors (r) can be estimated from the CAMP model
# r = rf + beta * mrp
# rf: is the risk-free rate -> rf = 0.0020
# mrp: is a market risk premium. -> mrp = 0.0438
r = 0.0020 + 0.94 * 0.0438

# The number of days to simulate
M = 365

# Closing price of bitcoin from which the simulation will start
S0 = df.Close[-M]

# Length of time interval
dt = T / M

# Number of paths to simulate
I = 20000 

print("S0, initial day: \t", S0)
print("r, riskless short rate: ", r)
print("M, number of days: \t", M)
print("I, paths simulating: \t", I)

S0, initial day: 56280.42578125
r, riskless short rate: 0.043171999999999995
M, number of days: 365
I, paths simulating: 20000

# Simulating I paths with M days (time steps)
S = S0 * np.exp(np.cumsum((r - 0.5 * sigma ** 2) * dt + sigma * math.sqrt(dt) * np.random.standard_normal((M + 1, I)), axis=0))
S[0] = S0

Se muestra la gráfica con 20 simulaciones más la variación del precio real en negro (+).

# Real price ot BTC
real = df[(df.index > df.index[-M])]['Close']

plt.figure(figsize=(18,8))
plt.title('Bitcoin simulation Monte Carlo last year')
plt.plot(real.values, 'k+')
plt.plot(S[:, :20])
plt.grid(True)
plt.xlabel('Days')
plt.ylabel('BTC(USD)')

Gráfico con la distribución de los precios de cierre simulados al final de los 365 días con dos líneas verticales en rojo indicando lo valores por encima y por debajo del 10% y con la línea del precio real en negro.

closing_prices = S[-1]
top_ten = np.percentile(closing_prices, 100-10)

# Pull bottom 10% of possible outcomes
bottom_ten = np.percentile(closing_prices, 10);

plt.figure(figsize=(18,8))
plt.hist(closing_prices, bins=100)
plt.axvline(top_ten,color='r', linestyle='dashed', linewidth=2)
plt.axvline(bottom_ten,color='r', linestyle='dashed', linewidth=2)
plt.axvline(real.values[-1],color='k', linestyle='dashed', linewidth=2)
plt.xlabel('BTC Price')
plt.ylabel('Frequency')
plt.show()
print("Expected BTC price: \t", round(np.mean(closing_prices), 2))
print("Quantile (5%): \t\t", np.percentile(closing_prices, 5))
print("Quantile (95%): \t", np.percentile(closing_prices, 95))

Expected BTC price: 58576.6
Quantile (5%): 15728.06144884368
Quantile (95%): 140307.08467573024

Número de simulaciones que se han generado, de ellas las que tienen un precio inferior al de hoy y el porcentaje que suponen estas con respecto del total.

df1_T = pd.DataFrame(S[-1:, :I]).T
df1_T.columns = ['btc_price_last_day']
print("Nº simulations: \t\t\t", df1_T.count())
print("Nº simulatios less price today: \t", df1_T[(df1_T['btc_price_last_day'] < df.Close[-1])].count())
print("Average simulatios less price today: \t", df1_T[(df1_T['btc_price_last_day'] < df.Close[-1])].count()*100/df1_T.count())

Nº simulations: btc_price_last_day 20000
Nº simulatios less price today: btc_price_last_day 1160
Average simulatios less price today: btc_price_last_day 5.8

Conclusiones

Llevamos un año con una de las mayores bajadas de precio de BTC de la historia, se han aliado varios factores, noticas macroeconómicas desfavorables a la economía, la caída de grandes empresas cripto con la pérdida de fondos de sus clientes y además dentro de los periódos cíclicos que se producen cada 4 años en bitcoin debido al halving estamos en la parte que históricamente ha sido bajista. Como comentábamos al principio la simulación mediante Monte Carlo no nos vale para predecir el precio a un año vista pero si nos vale para saber que de todas los posibles escenarios estamos cerca del 5% peor, lo cual nos indica lo dicho, estamos metidos de lleno en un invierno cripto.

Link in github al notebook bitcoin-montecarlo-simulation

Actualización diaria de la simulación en esta página “Simulation of the price of BTC with Monte Carlo“.

Bitcoin volatility

15 November 2022 at 23:13

The high volatility that exists in bitcoin makes it difficult for it to be used as money, defining it as a generally accepted means of exchange. We are going to study in this article its volatility based on the historical data of the price of BTC and if it is decreasing or increasing over time.

Within the bitcoiner community there are two lines of opinion regarding price volatility:

  • A current that thinks that this will subside over time as its adoption increases and its market capitalization increases, making the variations in supply and demand have less percentage weight and therefore the price fluctuations are less. It will also help if its use as a financial asset decreases, so many investors who are currently susceptible to emotion, fear and euphoria will decrease and with this the extreme reactions in the market will decrease.
  • Another that believes that volatility is intrinsic to the fixed supply of bitcoin and that this inelasticity leads to very significant variations between supply and demand and with it price fluctuations. Bitcoin does not generate cash flow, so changes in sentiment influence the price much more than, for example, in the case of a company share. The fact that the production of bitcoin cannot be increased at any cost prevents speculation that stabilizes the price.

Both in one case and in the other, the fact that a fundamental or approximate price of bitcoin cannot be calculated creates doubts that lead the price to fall and rise sharply.

What is volatility?

The volatility of an asset is the change in price over a given period of time. High volatility is associated with riskier assets. In traditional financial markets, volatility is usually measured over a 30-day period, therefore the measure of volatility for a given day is based on the change in performance over the previous 29 days.

To calculate the volatility in bitcoin we use the classic method where the mobile standard deviation of the percentage changes in the price of BTC is taken during a certain period of time, that is, the percentage of change in the price is calculated day by day during the period , then the mean is calculated and how far the day-to-day values ​​are from that mean (the standard deviation).

Evolution of volatility in the price of bitcoin

We are going to study how the volatility of bitcoin has evolved throughout history and if it is going to decrease or increase over time. We will also compare it to the volatility of the price of gold and the SP 500 index to get an idea of ​​how much the difference is between them.

Conclusions

The conclusions we reached from the analysis carried out on the volatility with the bitcoin price data.

  • Bitcoin is a very volatile digital asset, to get an idea of ​​it, it is 4 times more volatile than gold and the SP500 index.
  • This volatility in the period studied from February 2014 to the present does not seem to be reducing but rather remains more or less stable.
  • The information that the data transmits to us is that the current that maintains that the volatility of the price of bitcoin as something intrinsic and that advocates that it will not be reduced over time would be the one that would be correct.
  • The definition of money would have three legs, a generally accepted medium of exchange, a unit of account, and a store of value. If the volatility continues like this, it will be difficult for bitcoin to be used as a means of exchange since the variability in the price means that neither sellers nor buyers are interested in using it for their daily exchanges and without having that property it is very difficult for it to become a unit of account, so it could not be considered money.
  • That it cannot be considered money does not mean that it does not have other financial uses, to date it has been a very good reserve of value in the medium and long term, since the progression in price has been meteoric, it also allows them to be their own users are the holders of the asset and not that these are guarded by banks or other organizations and the non-existence of intermediaries means that there is no limitation when buying and selling BTC.

Study of volatility based on data

Yahoo’s yfinance module is installed.

!pip install yfinance > /dev/null

The Python libraries that will be used in the study are the following.

import pandas as pd
import requests
import matplotlib.pyplot as plt
import yfinance as yf
from pylab import rcParams
import plotly.express as px
import seaborn as sns
import warnings

warnings.filterwarnings('ignore')

Download the daily bitcoin price data from the Yahoo finance website.

btc_data = yf.download('BTC-USD', interval = '1d')[['Close']]

[*********************100%***********************] 1 of 1 completed

Calculation of the standard deviation in a window of 30 days.

volatility_days = 30
btc_data['pct_change'] = btc_data['Close'].pct_change()*100
btc_data['stdev'] = btc_data['pct_change'].rolling(volatility_days).std()

To convert the volatility of a short-term measure to a long-term metric, a multiplication of the measure by a factor that is the square root of the total number of trading periods of the asset in the interested period is usually carried out, for example if we want annualize it and since Bitcoin operates 24 hours a day, 7 days a week, 365 days a year, we have to multiply by np.sqrt(365), which is different from traditional assets where the value of 252 is used as there are 252 stock trading days per year.

# Annualizing the standard deviation to 30 days
btc_data['vol'] = btc_data['stdev']*(365**0.5)
btc_data.dropna(inplace=True)
btc_data.head()
Closepct_changestdevvol
Date
2014-10-17383.7579960.3142013.91480774.792279
2014-10-18391.4419862.0023013.72897571.241968
2014-10-19389.545990-0.4843623.50331366.930710
2014-10-20382.845001-1.7202053.45081165.927651
2014-10-21386.4750060.9481663.42842465.499950

Graph with the volatility of the price of BTC at 30 days from October 2014 to the present.

plt.figure(figsize=(20,10))
plt.title(str(volatility_days) + ' day BTC closing price volatility')
plt.plot(btc_data.vol)

The percentage of how the closing price of BTC has changed from one day to the next.

plt.figure(figsize=(20,10))
plt.title('Day BTC closing price percentage change')
plt.plot(btc_data['pct_change'], label='Day BTC closing price percentage change')
plt.legend()

When making a linear adjustment of the values of the volatility of BTC since October 2014, it is observed that the line is close to the horizontal, which indicates that there is no decrease in volatility over time, but that to date the volatility has has maintained and has even increased slightly.

plt.figure(figsize=(20,10))
btc_data['id_'] = range(1, 1+len(btc_data))
sns.regplot(x='id_', y='vol', data=btc_data,
            marker='o', color='blue', scatter_kws={'s':1})

Download data on the price of gold and the SP500 index from the Yahoo finance website.

gold_data = yf.download('GC=F', start=btc_data.index[0])[['Close']]
gold_data['pct_change'] = gold_data.pct_change()*100
gold_data['stdev'] = gold_data['pct_change'].rolling(volatility_days).std()
gold_data['vol'] = gold_data['stdev']*(252**0.5)
gold_data.dropna(inplace=True)

SP500_data = yf.download('^GSPC', start=btc_data.index[0])[['Close']]
SP500_data['pct_change'] = SP500_data.pct_change()*100
SP500_data['stdev'] = SP500_data['pct_change'].rolling(volatility_days).std()
SP500_data['vol'] = SP500_data['stdev']*(252**0.5)
SP500_data.dropna(inplace=True)

[*********************100%***********************] 1 of 1 completed [*********************100%***********************] 1 of 1 completed

The average of the volatility of bitcoin throughout the period studied is more than four times that of gold and that of the SP 500 index. The high volatility of bitcoin makes it very difficult for it to be used as money, understanding this as a generally accepted means of exchange, since for sellers it implies great uncertainty, since if after the sale of their products the price drop abruptly can mean that they have no benefits or even losses, if on the contrary the price rises substantially their benefits will skyrocket.

print("Bitcoin and SP500 volatility ratio: " + str(round(100 * btc_data['vol'].mean() / SP500_data['vol'].mean(),0)) + "%")
print("Bitcoin and gold volatility ratio: " + str(round(100 * btc_data['vol'].mean() / gold_data['vol'].mean(),0)) + "%")

Bitcoin SP500 volatility ratio: 434.0%

Bitcoin gold volatility ratio: 475.0%

Graph with the comparison between the volatility of bitcoin with that of the price of gold and that of the SP500 index.

plt.figure(figsize=(20,10))
plt.title(str(volatility_days) + ' day bitcoin and SP500 closing price volatility')
plt.plot(btc_data.vol, label='BTC')
plt.plot(SP500_data.vol, label='SP500')
plt.plot(gold_data.vol, label='Gold')
plt.legend()
plt.show()

Link notebook Python in github: Bitcoin volatility

Volatilidad en bitcoin

14 November 2022 at 20:17

La alta volatilidad que existe en bitcoin dificulta que pueda ser utilizado como dinero, definiendo este como medio de cambio generalmente aceptado. Vamos a estudiar en este artículo su volatilidad a partir de los datos históricos del precio de BTC y si está está disminuyendo o aumentando con el paso del tiempo.

Dentro de la comunidad bitcoiner hay dos líneas de opinión con respecto a la volatilidad del precio:

  • Una corriente que piensa que esta irá remitiendo con el tiempo a medida que aumente su adopción y suba su capitalización de mercado haciendo que las variaciones en la oferta y la demanda tengan menos peso porcentual y por ello la oscilaciones en el precio sean menores. También ayudará que disminuya su uso como activo financiero por lo que muchos inversores que actualmente son susceptibles a la emoción, miedo y euforia, disminuirán y con ello bajarán las reacciones extremas en el mercado.
  • Otra que cree que la volatilidad es intrínseca a la oferta fija de bitcoin y que esa inelasticidad conlleva a que las variaciones entre la oferta y la demanda sean muy significativas y con ello las oscilaciones precio. Bitcoin no genera flujo de caja, por lo que los cambios de sentimiento influyen mucho más en el precio, que por ejemplo en el caso de una acción de una empresa. El hecho de que no se pueda aumentar la producción de bitcoin a ningún coste impide que haya una especulación que estabilice el precio.

Tanto en un caso como en otro el hecho de que no se pueda calcular un precio fundamental o aproximado de bitcoin crea unas dudas que llevan a que el precio baje y suba con fuerza.

¿Qué es la volatilidad?

La volatilidad de un activo es la variación del precio durante un período de tiempo determinado. Una alta volatilidad se asocia con activos más riesgosos. En los mercados financieros tradicionales la volatilidad suele medirse en un período de 30 días, por lo tanto, la medida de la volatilidad para un día determinado se basa en la variación del rendimiento en los 29 días anteriores.

Para el cálculo de la volatilidad en bitcoin utilizamos el método clásico donde se toma la desviación estándar móvil de los cambios porcentuales del precio de BTC durante un período de tiempo determinado es decir se calcula el porcentaje de cambio en el precio día a día durante el periodo, posteriormente se calcula la media y cuanto se distancian los valores día a día de esa media (la desviación estándar).

Evolución de la volatilidad en el precio de bitcoin

Vamos a estudiar como ha evolucionado la volatilidad de bitcoin a lo largo de la historia y si esta va a menos o a más con el paso del tiempo. También la compararemos con la volatilidad del precio del oro y del índice SP 500 para tener una idea de cuanta es la diferencia entre ellas.

Conclusiones

En base a la analítica realizada sobre el histórico de datos de BTC que se mostrará en el siguiente apartado llegamos a las siguientes conclusiones:

  • Bitcoin es un activo digital muy volátil, para hacernos una idea de ello es 4 veces más volátil que el oro y que el índice SP500.
  • Esta volatilidad en el periodo estudiado desde octubre del año 2014 hasta la actualidad no parece estar reduciéndose sino que se mantiene más o menos estable.
  • La información que nos trasmiten los datos es que la corriente que mantiene que la volatilidad del precio de bitcoin como algo intrínseco y que aboga porque no se reducirá con el paso del tiempo sería la que estaría en lo correcto.
  • La definición de dinero tendría tres patas, medio de intercambio generalmente aceptado, unidad de cuenta y reserva de valor. Si la volatilidad continua así, va a ser difícil que bitcoin sea utilizado como medio de intercambio ya que la variabilidad en el precio hace que ni vendedores ni compradores les interese utilizarlo para sus intercambios diarios y sin tener esa propiedad es muy complicado que pueda convertirse en una unidad de cuenta, por lo que no podría se considerado dinero.
  • Que no se pueda considerar dinero no significa que no tenga otros usos financieros, hasta la fecha ha sido una muy buena reserva de valor a medio y largo plazo, ya que la progresión en el precio ha sido meteórica, también permite que sean los propios usuarios los poseedores del activo y no que estos sean custodiados por los bancos u otros organismos y la no existencia de intermediarios hace que no existe ninguna limitación a la hora de adquirir y vender BTC.

Estudio de la volatilidad en base a los datos

Se instala el módulo yfinance de Yahoo.

!pip install yfinance > /dev/null

Las bibliotecas de Python que se utilizarán en el estudio son las siguientes.

import pandas as pd
import requests
import matplotlib.pyplot as plt
import yfinance as yf
from pylab import rcParams
import plotly.express as px
import seaborn as sns
import warnings

warnings.filterwarnings('ignore')

Descarga de los datos de la cotización diaria de bitcoin de la web de Yahoo finance.

btc_data = yf.download('BTC-USD', interval = '1d')[['Close']]

Cálculo de la desviación estándar en una ventana temporal de 30 días.

volatility_days = 30
btc_data['pct_change'] = btc_data['Close'].pct_change()*100
btc_data['stdev'] = btc_data['pct_change'].rolling(volatility_days).std()

Para convertir la volatilidad de una medida a corto plazo a una métrica a largo plazo, se suele realiza una multiplicación de la medida por un factor que es la raíz cuadrada del numero total de períodos de negociación del activo en el periodo interesado por ejemplo si queremos anualizarla y como Bitcoin opera las 24 horas del día, los 7 días de la semana, los 365 días del año, tenemos que multiplica por la raíz cuadrada de 365, que es diferente a de los activos tradicionales donde se usa el valor de 252 ya que son los días de negociación de acciones por año.

# Annualizing the standard deviation to 30 days
btc_data['vol'] = btc_data['stdev']*(365**0.5)
btc_data.dropna(inplace=True)
btc_data.head()
Closepct_changestdevvol
Date
2014-10-17383.7579960.3142013.91480774.792279
2014-10-18391.4419862.0023013.72897571.241968
2014-10-19389.545990-0.4843623.50331366.930710
2014-10-20382.845001-1.7202053.45081165.927651
2014-10-21386.4750060.9481663.42842465.499950

Gráfico con la volatilidad del precio de BTC a 30 días desde octubre del 2014 hasta la actualidad.

plt.figure(figsize=(20,10))
plt.title(str(volatility_days) + ' day BTC closing price volatility')
plt.plot(btc_data.vol)

El porcentaje de cómo ha cambiado el precio de cierre de BTC de un día para otro.

plt.figure(figsize=(20,10))
plt.title('Day BTC closing price percentage change')
plt.plot(btc_data['pct_change'], label='Day BTC closing price percentage change')
plt.legend()

Al hacer un ajuste lineal de los valores de la volatilidad de BTC desde octubre del 2014 se observa que la recta está cercana a la horizontal por lo que indica que no hay un decrecimiento de la volatilidad con el tiempo sino que hasta la fecha la volatilidad se ha mantenido e incluso ha aumentado ligeramente.

btc_data['id_'] = range(1, 1+len(btc_data))
sns.regplot(btc_data.id_, btc_data.vol)

Descarga de los datos del precio del oro y del índice SP500 de la web de Yahoo finance.

gold_data = yf.download('GC=F', start=btc_data.index[0])[['Close']]
gold_data['pct_change'] = gold_data.pct_change()*100
gold_data['stdev'] = gold_data['pct_change'].rolling(volatility_days).std()
gold_data['vol'] = gold_data['stdev']*(252**0.5)
gold_data.dropna(inplace=True)

SP500_data = yf.download('^GSPC', start=btc_data.index[0])[['Close']]
SP500_data['pct_change'] = SP500_data.pct_change()*100
SP500_data['stdev'] = SP500_data['pct_change'].rolling(volatility_days).std()
SP500_data['vol'] = SP500_data['stdev']*(252**0.5)
SP500_data.dropna(inplace=True)

La media de la volatilidad de bitcoin a lo largo del periodo estudiado es más de cuatro veces que la del oro y la del índice SP 500. La alta volatilidad de bitcoin lo hace que sea muy difícil que sea usado como dinero, entendiendo este como un medio de intercambio generalmente aceptado, ya que para los vendedores les supone una gran incertidumbre, ya que si posteriormente a la venta de sus productos el precio baja de forma abrupta puede suponer que no tengan beneficios o incluso pérdidas, si por el contrario el precio sube sustancialmente sus beneficios se dispararán.

print("Bitcoin and SP500 volatility ratio: " + str(round(100 * btc_data['vol'].mean() / SP500_data['vol'].mean(),0)) + "%")
print("Bitcoin and gold volatility ratio: " + str(round(100 * btc_data['vol'].mean() / gold_data['vol'].mean(),0)) + "%")

Bitcoin SP500 volatility ratio: 434.0%

Bitcoin gold volatility ratio: 475.0%

Gráfica con la comparativa entre la volatilidad de bitcoin con la del precio del oro y la del índice SP500.

plt.figure(figsize=(20,10))
plt.title(str(volatility_days) + ' day bitcoin and SP500 closing price volatility')
plt.plot(btc_data.vol, label='BTC')
plt.plot(SP500_data.vol, label='SP500')
plt.plot(gold_data.vol, label='Gold')
plt.legend()
plt.show()

Study of a BTC strategy combining DCA with the Fear and Greed

9 November 2022 at 19:51

Analysis of an investment strategy for the purchase of bitcoin where the DCA (Dollar Cost Average) and the market sentiment, Fear and Greed index, are combined.

The strategy will consist of the moment that would correspond to the periodic purchase (DCA) the Fear and Greed (F&G) metric will be evaluated and if it has a value greater than 50, which is equivalent to a positive market sentiment, in the end, a comparison will be made of this blended strategy against a standard DCA during the period in which Fear and Greed Index data is available, which is February 2018 to the present.

Dollar Cost Averaging (DCA) is a type of strategy that consists of investing the same amount of money from time to time, it is independent of what happens in the market since you will invest the same, even if the price of BTC goes up or down.
This reduces the impact that a market entry at the wrong time can have and minimizes the consequences of high BTC volatility.
Initially it is intended to buy and hold (hodl) but it is not mandatory.
It is a practically neglected option. You invest an amount of money at a certain time and leave it there for a while with the idea that bitcoin will tend to rise in the long term.
It does not require a large initial investment and allows you to plan your risk.

The Fear and Greed Index is a metric published by https://alternative.me/crypto/fear-and-greed-index/  that attempts to predict market sentiment based on these 5 indicators:

  • Volatility (25%)
  • Market Volume / Momentum (25%)
  • Social Networks (15%)
  • Dominance (10%)
  • Trends (10%)

Disclaimer

This article is not investment advice, act according to your own criteria.

The Python libraries that will be used in the study are the following.

import pandas as pd
import requests
import matplotlib.pyplot as plt
import yfinance as yf
from pylab import rcParams
import plotly.express as px
import warnings

warnings.filterwarnings('ignore')
rcParams['figure.figsize'] = 10, 5

Download Bitcoin price data from Yahoo Finance.

df = yf.download('BTC-USD', interval = '1d')[['Close']]
df.rename(columns = {'Close':'close'}, inplace=True)
df.index.name = 'timestamp'
df['timestamp'] = df.index
df.reset_index(drop=True, inplace=True)
df.timestamp = pd.to_datetime(df.timestamp, unit='s').dt.tz_localize(None)
df.set_index(df.timestamp, inplace=True)
df.drop(['timestamp'], axis=1, inplace=True)

Download F&G data from alternative

r = requests.get('https://api.alternative.me/fng/?limit=0')

# Show fear and greed index from February 2018.
# Values range from 0 to 100, with low values indicating fear and high values indicating euphoria.
df1 = pd.DataFrame(r.json()['data'])
df1.value = df1.value.astype(int)
df1.timestamp = pd.to_datetime(df1.timestamp, unit='s')
df1.set_index(df1.timestamp, inplace=True)
df1.rename(columns = {'value':'fear_greed', 'timestamp':'date'}, inplace=True)
df1.drop(['time_until_update'], axis=1, inplace=True)

Fear and Greed Index Data Joins Bitcoin Dollar Price Data.

data = df.merge(df1, on='timestamp')
data = data.sort_index()
data.tail()

BTC price chart colored based on market sentiment as marked by the Fear and Greed index.

The bluer colors correspond to the feeling of fear and the more yellowish to euphoria.

It can be seen in the graph that yellowish colors predominate in periods of price increase and in periods of decrease, blue and violet are the most recurrent colors.

fig = px.scatter(data, x="date", y="close", color="fear_greed",
                 title="BTC price with fear and greed index in continuous color")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

A DCA strategy is implemented where BTC is bought once a week and only when the F&G is greater than 50.

limit_fear_greed = 50
buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy = data[(data.index.isin(buy_dates) & (data.fear_greed > limit_fear_greed))]

# The amount of dollars available weekly to buy is $100.
buy_dca = 100
data_buy['btc_amt'] = buy_dca / data_buy.close
data_buy['btc_amt_sum'] = data_buy.btc_amt.cumsum()
data_buy

The period for which F&G index data is available is from February 1, 2018 to the present.

print(data_buy.index[0])
print(data_buy.index[-1])

2018-02-18 00:00:00
2021-11-14 00:00:00

Calculation of the expenses and benefits of the mixed strategy (DCA and F&G) without taking into account the commissions for the purchase of BTC.

spent = buy_dca * len(data_buy)
amount = data_buy.iloc[-1].btc_amt_sum * data.iloc[-1].close
print("Nº of purchases: \t " + str(len(data_buy)))
print("Spent: \t\t\t $" + str(spent))
print("Gross profit: \t\t $" + str(amount))
print("Net profit: \t\t $" + str(amount - spent))

Nº of purchases: 81
Spent: $8100
Gross profit: $11779.893404192857
Net profit: $3679.893404192857

Weekly chart of the price of bitcoin when the Fear and Greed index is greater than 50.

The circles that appear in the graph indicate the moments of purchase according to this strategy. There are 3 areas of accumulation of them that coincide with the bullish periods of the price.

  • A first area from February to August of the year 2019 where the rise is moderate and the euphoria is less.
  • A second from August 2020 to May 2021 where one of the great bitcoin bull runs occurs and the euphoria is maximum, reaching values of 95 points.
  • And a last one from August 2021 to November 2021 where the euphoria is less but where the ATH (the highest value of all time) is reached on November 9, 2021, since then the fear and greed index has not exceeded the 50 for which no purchase order would have been executed.
fig = px.scatter(data_buy, x="date", y="close", color="fear_greed",
                 title="BTC weekly price with fear and greed index only when F&G > 50")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

Calculation of the performance of a pure DCA strategy where BTC is bought every week.

buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy_dca_week = data[(data.index.isin(buy_dates))]

# The weekly purchase is calculated in dollars so that the value spent during the period is similar in both cases. 
buy_dca_week = buy_dca * len(data_buy) / len(data_buy_dca_week)
data_buy_dca_week['btc_amt'] = buy_dca_week / data_buy_dca_week.close
data_buy_dca_week['btc_amt_sum'] = data_buy_dca_week.btc_amt.cumsum()
buy_dca_week

32.66129032258065

When calculating the benefits of the DCA strategy, the commissions for the purchase of bitcoin are not taken into account either.

spent_dca_week = buy_dca_week * len(data_buy_dca_week)
amount_dca_week = data_buy_dca_week.iloc[-1].btc_amt_sum * data.iloc[-1].close

print("Nº of purchases: \t " + str(len(data_buy_dca_week)))
print("Spent: \t\t\t $" + str(spent_dca_week))
print("Gross profit: \t\t $" + str(amount_dca_week))
print("Net profit: \t\t $" + str(amount_dca_week - spent_dca_week))

Comparative graph showing how the BTC acquired in the mixed strategy of DCA and F&G are accumulated.

In the case of the DCA and F&G line, no data has appeared since November 2021 because since then the Fear and Greed index has not exceeded 50 points.

data_buy['btc_amt_sum'].plot(label='DCA and F&G')
data_buy_dca_week['btc_amt_sum'].plot(label='DCA')
plt.legend()
plt.show()

Comparison in numbers of the two investment strategies. 

print("#####\t DCA and F&G Strategy \t#####")
print("Spent: \t\t\t $" + str(spent))
print("Net profit: \t\t $" + str(amount - spent))
print("Accumulated BTC: \t " + str(data_buy.iloc[-1].btc_amt_sum))
print("\n#####\t DCA Strategy \t\t#####")
print("Spent: \t\t\t $" + str(spent_dca_week))
print("Net profit: \t\t $" + str(amount_dca_week - spent_dca_week))
print("Accumulated BTC: \t " + str(data_buy_dca_week.iloc[-1].btc_amt_sum))

DCA and F&G Strategy
Spent: $8100
Net profit: $3679.893404192857
Accumulated BTC: 0.627840393893085

DCA Strategy
Spent: $8100.000000000001
Net profit: $6283.419267711178
Accumulated BTC: 0.7666021506913571

In view of the numbers, the mixed investment strategy in DCA bitcoin and the Fear and Greed index in the period studied is worse than a recurring purchase strategy of sam amount os money.

In this period we would have an expense of 8100 dollars and 0.62 BTC in our account, in the case of the combined strategy that is equivalent to $4527 discounting the purchase expenses and we would have 0.76 BTC if we had opted for a DCA that at today’s price minus the expenses It’s about $7,300.

Link to notebook at kaggle Study Bitcoin strategy DCA with Fear and Greed

Link to Python code on github Study Bitcoin strategy combining DCA with Fear Greed index

Study of a BTC strategy combining DCA with the Fear and Greed

9 November 2022 at 19:47

Analysis of an investment strategy for the purchase of bitcoin where the DCA (Dollar Cost Average) and the market sentiment, Fear and Greed index, are combined .

The strategy will consist of the moment that would correspond to the periodic purchase (DCA) the Fear and Greed (F&G) metric will be evaluated and if it has a value greater than 50, which is equivalent to a positive market sentiment, in the end, a comparison will be made of this blended strategy against a standard DCA during the period in which Fear and Greed Index data is available, which is February 2018 to the present.

Dollar Cost Averaging (DCA) is a type of strategy that consists of investing the same amount of money from time to time, it is independent of what happens in the market since you will invest the same, even if the price of BTC goes up or down.
This reduces the impact that a market entry at the wrong time can have and minimizes the consequences of high BTC volatility.
Initially it is intended to buy and hold (hodl) but it is not mandatory.
It is a practically neglected option. You invest an amount of money at a certain time and leave it there for a while with the idea that bitcoin will tend to rise in the long term.
It does not require a large initial investment and allows you to plan your risk.

The Fear and Greed Index is a metric published by https://alternative.me/crypto/fear-and-greed-index/  that attempts to predict market sentiment based on these 5 indicators:

  • Volatility (25%)
  • Market Volume / Momentum (25%)
  • Social Networks (15%)
  • Dominance (10%)
  • Trends (10%)

Disclaimer

This article is not investment advice, act according to your own criteria.

The Python libraries that will be used in the study are the following.

import pandas as pd
import requests
import matplotlib.pyplot as plt
import yfinance as yf
from pylab import rcParams
import plotly.express as px
import warnings

warnings.filterwarnings('ignore')
rcParams['figure.figsize'] = 10, 5

Download Bitcoin price data from Yahoo Finance.

df = yf.download('BTC-USD', interval = '1d')[['Close']]
df.rename(columns = {'Close':'close'}, inplace=True)
df.index.name = 'timestamp'
df['timestamp'] = df.index
df.reset_index(drop=True, inplace=True)
df.timestamp = pd.to_datetime(df.timestamp, unit='s').dt.tz_localize(None)
df.set_index(df.timestamp, inplace=True)
df.drop(['timestamp'], axis=1, inplace=True)

Download F&G data from alternative

r = requests.get('https://api.alternative.me/fng/?limit=0')

# Show fear and greed index from February 2018.
# Values range from 0 to 100, with low values indicating fear and high values indicating euphoria.
df1 = pd.DataFrame(r.json()['data'])
df1.value = df1.value.astype(int)
df1.timestamp = pd.to_datetime(df1.timestamp, unit='s')
df1.set_index(df1.timestamp, inplace=True)
df1.rename(columns = {'value':'fear_greed', 'timestamp':'date'}, inplace=True)
df1.drop(['time_until_update'], axis=1, inplace=True)

Fear and Greed Index Data Joins Bitcoin Dollar Price Data.

data = df.merge(df1, on='timestamp')
data = data.sort_index()
data.tail()

BTC price chart colored based on market sentiment as marked by the Fear and Greed index.

The bluer colors correspond to the feeling of fear and the more yellowish to euphoria.

It can be seen in the graph that yellowish colors predominate in periods of price increase and in periods of decrease, blue and violet are the most recurrent colors.

fig = px.scatter(data, x="date", y="close", color="fear_greed",
                 title="BTC price with fear and greed index in continuous color")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

A DCA strategy is implemented where BTC is bought once a week and only when the F&G is greater than 50.

limit_fear_greed = 50
buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy = data[(data.index.isin(buy_dates) & (data.fear_greed > limit_fear_greed))]

# The amount of dollars available weekly to buy is $100.
buy_dca = 100
data_buy['btc_amt'] = buy_dca / data_buy.close
data_buy['btc_amt_sum'] = data_buy.btc_amt.cumsum()
data_buy

The period for which F&G index data is available is from February 1, 2018 to the present.

print(data_buy.index[0])
print(data_buy.index[-1])

2018-02-18 00:00:00
2021-11-14 00:00:00

Calculation of the expenses and benefits of the mixed strategy (DCA and F&G) without taking into account the commissions for the purchase of BTC.

spent = buy_dca * len(data_buy)
amount = data_buy.iloc[-1].btc_amt_sum * data.iloc[-1].close
print("Nº of purchases: t " + str(len(data_buy)))
print("Spent: ttt $" + str(spent))
print("Gross profit: tt $" + str(amount))
print("Net profit: tt $" + str(amount - spent))

Nº of purchases: 81
Spent: $8100
Gross profit: $11779.893404192857
Net profit: $3679.893404192857

Weekly chart of the price of bitcoin when the Fear and Greed index is greater than 50.

The circles that appear in the graph indicate the moments of purchase according to this strategy. There are 3 areas of accumulation of them that coincide with the bullish periods of the price.

  • A first area from February to August of the year 2019 where the rise is moderate and the euphoria is less.
  • A second from August 2020 to May 2021 where one of the great bitcoin bull runs occurs and the euphoria is maximum, reaching values of 95 points.
  • And a last one from August 2021 to November 2021 where the euphoria is less but where the ATH (the highest value of all time) is reached on November 9, 2021, since then the fear and greed index has not exceeded the 50 for which no purchase order would have been executed.
fig = px.scatter(data_buy, x="date", y="close", color="fear_greed",
                 title="BTC weekly price with fear and greed index only when F&G > 50")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

Calculation of the performance of a pure DCA strategy where BTC is bought every week.

buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy_dca_week = data[(data.index.isin(buy_dates))]

# The weekly purchase is calculated in dollars so that the value spent during the period is similar in both cases. 
buy_dca_week = buy_dca * len(data_buy) / len(data_buy_dca_week)
data_buy_dca_week['btc_amt'] = buy_dca_week / data_buy_dca_week.close
data_buy_dca_week['btc_amt_sum'] = data_buy_dca_week.btc_amt.cumsum()
buy_dca_week

32.66129032258065

When calculating the benefits of the DCA strategy, the commissions for the purchase of bitcoin are not taken into account either.

spent_dca_week = buy_dca_week * len(data_buy_dca_week)
amount_dca_week = data_buy_dca_week.iloc[-1].btc_amt_sum * data.iloc[-1].close

print("Nº of purchases: t " + str(len(data_buy_dca_week)))
print("Spent: ttt $" + str(spent_dca_week))
print("Gross profit: tt $" + str(amount_dca_week))
print("Net profit: tt $" + str(amount_dca_week - spent_dca_week))

Comparative graph showing how the BTC acquired in the mixed strategy of DCA and F&G are accumulated.

In the case of the DCA and F&G line, no data has appeared since November 2021 because since then the Fear and Greed index has not exceeded 50 points.

data_buy['btc_amt_sum'].plot(label='DCA and F&G')
data_buy_dca_week['btc_amt_sum'].plot(label='DCA')
plt.legend()
plt.show()

Comparison in numbers of the two investment strategies. 

print("#####t DCA and F&G Strategy t#####")
print("Spent: ttt $" + str(spent))
print("Net profit: tt $" + str(amount - spent))
print("Accumulated BTC: t " + str(data_buy.iloc[-1].btc_amt_sum))
print("n#####t DCA Strategy tt#####")
print("Spent: ttt $" + str(spent_dca_week))
print("Net profit: tt $" + str(amount_dca_week - spent_dca_week))
print("Accumulated BTC: t " + str(data_buy_dca_week.iloc[-1].btc_amt_sum))

DCA and F&G Strategy
Spent: $8100
Net profit: $3679.893404192857
Accumulated BTC: 0.627840393893085

DCA Strategy
Spent: $8100.000000000001
Net profit: $6283.419267711178
Accumulated BTC: 0.7666021506913571

In view of the numbers, the mixed investment strategy in DCA bitcoin and the Fear and Greed index in the period studied is worse than a recurring purchase strategy of sam amount os money.

In this period we would have an expense of 8100 dollars and 0.62 BTC in our account, in the case of the combined strategy that is equivalent to $4527 discounting the purchase expenses and we would have 0.76 BTC if we had opted for a DCA that at today’s price minus the expenses It’s about $7,300.

Study of a BTC strategy combining DCA with the Fear and Greed

9 November 2022 at 19:15

Analysis of an investment strategy for the purchase of bitcoin where the DCA (Dollar Cost Average) and the market sentiment, Fear and Greed index, are combined.

The strategy will consist of the moment that would correspond to the periodic purchase (DCA) the Fear and Greed (F&G) metric will be evaluated and if it has a value greater than 50, which is equivalent to a positive market sentiment, in the end, a comparison will be made of this blended strategy against a standard DCA during the period in which Fear and Greed Index data is available, which is February 2018 to the present.

Dollar Cost Averaging (DCA) is a type of strategy that consists of investing the same amount of money from time to time, it is independent of what happens in the market since you will invest the same, even if the price of BTC goes up or down.
This reduces the impact that a market entry at the wrong time can have and minimizes the consequences of high BTC volatility.
Initially it is intended to buy and hold (hodl) but it is not mandatory.
It is a practically neglected option. You invest an amount of money at a certain time and leave it there for a while with the idea that bitcoin will tend to rise in the long term.
It does not require a large initial investment and allows you to plan your risk.

The Fear and Greed Index is a metric published by https://alternative.me/crypto/fear-and-greed-index/  that attempts to predict market sentiment based on these 5 indicators:

  • Volatility (25%)
  • Market Volume / Momentum (25%)
  • Social Networks (15%)
  • Dominance (10%)
  • Trends (10%)

Disclaimer

This article is not investment advice, act according to your own criteria.

The Python libraries that will be used in the study are the following.

import pandas as pd
import requests
import matplotlib.pyplot as plt
import yfinance as yf
from pylab import rcParams
import plotly.express as px
import warnings

warnings.filterwarnings('ignore')
rcParams['figure.figsize'] = 10, 5

Download Bitcoin price data from Yahoo Finance.

df = yf.download('BTC-USD', interval = '1d')[['Close']]
df.rename(columns = {'Close':'close'}, inplace=True)
df.index.name = 'timestamp'
df['timestamp'] = df.index
df.reset_index(drop=True, inplace=True)
df.timestamp = pd.to_datetime(df.timestamp, unit='s').dt.tz_localize(None)
df.set_index(df.timestamp, inplace=True)
df.drop(['timestamp'], axis=1, inplace=True)

Download F&G data from alternative

r = requests.get('https://api.alternative.me/fng/?limit=0')

# Show fear and greed index from February 2018.
# Values range from 0 to 100, with low values indicating fear and high values indicating euphoria.
df1 = pd.DataFrame(r.json()['data'])
df1.value = df1.value.astype(int)
df1.timestamp = pd.to_datetime(df1.timestamp, unit='s')
df1.set_index(df1.timestamp, inplace=True)
df1.rename(columns = {'value':'fear_greed', 'timestamp':'date'}, inplace=True)
df1.drop(['time_until_update'], axis=1, inplace=True)

Fear and Greed Index Data Joins Bitcoin Dollar Price Data.

data = df.merge(df1, on='timestamp')
data = data.sort_index()
data.tail()

BTC price chart colored based on market sentiment as marked by the Fear and Greed index.

The bluer colors correspond to the feeling of fear and the more yellowish to euphoria.

It can be seen in the graph that yellowish colors predominate in periods of price increase and in periods of decrease, blue and violet are the most recurrent colors.

fig = px.scatter(data, x="date", y="close", color="fear_greed",
                 title="BTC price with fear and greed index in continuous color")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

A DCA strategy is implemented where BTC is bought once a week and only when the F&G is greater than 50.

limit_fear_greed = 50
buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy = data[(data.index.isin(buy_dates) & (data.fear_greed > limit_fear_greed))]

# The amount of dollars available weekly to buy is $100.
buy_dca = 100
data_buy['btc_amt'] = buy_dca / data_buy.close
data_buy['btc_amt_sum'] = data_buy.btc_amt.cumsum()
data_buy

The period for which F&G index data is available is from February 1, 2018 to the present.

print(data_buy.index[0])
print(data_buy.index[-1])

2018-02-18 00:00:00
2021-11-14 00:00:00

Calculation of the expenses and benefits of the mixed strategy (DCA and F&G) without taking into account the commissions for the purchase of BTC.

spent = buy_dca * len(data_buy)
amount = data_buy.iloc[-1].btc_amt_sum * data.iloc[-1].close
print("Nº of purchases: \t " + str(len(data_buy)))
print("Spent: \t\t\t $" + str(spent))
print("Gross profit: \t\t $" + str(amount))
print("Net profit: \t\t $" + str(amount - spent))

Nº of purchases: 81
Spent: $8100
Gross profit: $11779.893404192857
Net profit: $3679.893404192857

Weekly chart of the price of bitcoin when the Fear and Greed index is greater than 50.

The circles that appear in the graph indicate the moments of purchase according to this strategy. There are 3 areas of accumulation of them that coincide with the bullish periods of the price.

  • A first area from February to August of the year 2019 where the rise is moderate and the euphoria is less.
  • A second from August 2020 to May 2021 where one of the great bitcoin bull runs occurs and the euphoria is maximum, reaching values of 95 points.
  • And a last one from August 2021 to November 2021 where the euphoria is less but where the ATH (the highest value of all time) is reached on November 9, 2021, since then the fear and greed index has not exceeded the 50 for which no purchase order would have been executed.
fig = px.scatter(data_buy, x="date", y="close", color="fear_greed",
                 title="BTC weekly price with fear and greed index only when F&G > 50")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

Calculation of the performance of a pure DCA strategy where BTC is bought every week.

buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy_dca_week = data[(data.index.isin(buy_dates))]

# The weekly purchase is calculated in dollars so that the value spent during the period is similar in both cases. 
buy_dca_week = buy_dca * len(data_buy) / len(data_buy_dca_week)
data_buy_dca_week['btc_amt'] = buy_dca_week / data_buy_dca_week.close
data_buy_dca_week['btc_amt_sum'] = data_buy_dca_week.btc_amt.cumsum()
buy_dca_week

32.66129032258065

When calculating the benefits of the DCA strategy, the commissions for the purchase of bitcoin are not taken into account either.

spent_dca_week = buy_dca_week * len(data_buy_dca_week)
amount_dca_week = data_buy_dca_week.iloc[-1].btc_amt_sum * data.iloc[-1].close

print("Nº of purchases: \t " + str(len(data_buy_dca_week)))
print("Spent: \t\t\t $" + str(spent_dca_week))
print("Gross profit: \t\t $" + str(amount_dca_week))
print("Net profit: \t\t $" + str(amount_dca_week - spent_dca_week))

Comparative graph showing how the BTC acquired in the mixed strategy of DCA and F&G are accumulated.

In the case of the DCA and F&G line, no data has appeared since November 2021 because since then the Fear and Greed index has not exceeded 50 points.

data_buy['btc_amt_sum'].plot(label='DCA and F&G')
data_buy_dca_week['btc_amt_sum'].plot(label='DCA')
plt.legend()
plt.show()

Comparison in numbers of the two investment strategies. 

print("#####\t DCA and F&G Strategy \t#####")
print("Spent: \t\t\t $" + str(spent))
print("Net profit: \t\t $" + str(amount - spent))
print("Accumulated BTC: \t " + str(data_buy.iloc[-1].btc_amt_sum))
print("\n#####\t DCA Strategy \t\t#####")
print("Spent: \t\t\t $" + str(spent_dca_week))
print("Net profit: \t\t $" + str(amount_dca_week - spent_dca_week))
print("Accumulated BTC: \t " + str(data_buy_dca_week.iloc[-1].btc_amt_sum))

DCA and F&G Strategy
Spent: $8100
Net profit: $3679.893404192857
Accumulated BTC: 0.627840393893085

DCA Strategy
Spent: $8100.000000000001
Net profit: $6283.419267711178
Accumulated BTC: 0.7666021506913571

In view of the numbers, the mixed investment strategy in DCA bitcoin and the Fear and Greed index in the period studied is worse than a recurring purchase strategy of sam amount os money.

In this period we would have an expense of 8100 dollars and 0.62 BTC in our account, in the case of the combined strategy that is equivalent to $4527 discounting the purchase expenses and we would have 0.76 BTC if we had opted for a DCA that at today’s price minus the expenses It’s about $7,300.

Estudio de una estrategia de compra de bitcoin combinando DCA con el índice Fear and Greed

8 November 2022 at 20:20

Análisis de una estrategia de inversión para la compra de bitcoin donde se combina el DCA (Dollar Cost Average) y el sentimiento del mercado, índice Fear and Greed.

La estrategia consistirá en el momento que correspondería a la compra periódica (DCA) se evaluará la métrica Fear and Greed (F&G) y si esta tiene un valor mayor de 50 que equivale a que el sentimiento de mercado es positivo, al final se realizará una comparativa de esta estrategia combinada frente a una DCA estándar durante el periodo que se se dispone de datos del índice Fear and Greed que es desde febrero 2018 hasta la actualidad.

El Dollar Cost Averaging (DCA) es un tipo de estrategia que consiste en invertir la misma cantidad de dinero cada cierto tiempo, es independiente de lo que suceda en el mercado ya que invertirás lo mismo, aunque el precio de BTC suba o baje.
Con ello se reduce el impacto que pueda tener una entrada en el mercado en el momento equivocado y minimizar las consecuencias de la alta volatilidad de BTC.
Inicialmente está pensada para comprar y mantener (hodl) pero no es obligatorio.
Es una opción prácticamente desatendida. Inviertes una cantidad de dinero en un momento determinado y lo dejas ahí durante tiempo con la idea de que bitcoin tenderá a subir en el largo plazo
No requiere una gran inversión inicial y te permite planificar tu riesgo.

El índice Fear and Greed es una métrica publicada por alternative que intenta predecir el sentimiento del mercado basándose en estos 5 indicadores: 

  • Volatilidad (25 %)
  • Volumen / impulso del mercado (25 %)
  • Redes Sociales (15%)
  • Dominancia (10%)
  • Tendencias (10%)

Disclaimer

Este artículo no es un consejo de inversión, actúa según tus propios criterios.

 

Se instala la librería necesaria para descargar los datos del precio de BTC de la web de Yahoo Finance.

!pip install yfinance > /dev/null

Las librerías Python que se utilizaran en el estudio son las siguientes.

import pandas as pd
import requests
import matplotlib.pyplot as plt
import yfinance as yf
from pylab import rcParams
import plotly.express as px
import warnings

warnings.filterwarnings('ignore')
rcParams['figure.figsize'] = 10, 5

Descarga de datos de precios de Bitcoin de Yahoo Finance.

df = yf.download('BTC-USD', interval = '1d')[['Close']]
df.rename(columns = {'Close':'close'}, inplace=True)
df.index.name = 'timestamp'
df['timestamp'] = df.index
df.reset_index(drop=True, inplace=True)
df.timestamp = pd.to_datetime(df.timestamp, unit='s').dt.tz_localize(None)
df.set_index(df.timestamp, inplace=True)
df.drop(['timestamp'], axis=1, inplace=True)

Descarga de los datos F&G de https://alternative.me/crypto/fear-and-greed-index/

r = requests.get('https://api.alternative.me/fng/?limit=0')

# Mostrar índice de miedo y codicia desde el febrero del año 2018.
# Los valores oscilan entre 0 y 100, donde los valores bajos indican miedo y los valores altos indican euforia.
df1 = pd.DataFrame(r.json()['data'])
df1.value = df1.value.astype(int)
df1.timestamp = pd.to_datetime(df1.timestamp, unit='s')
df1.set_index(df1.timestamp, inplace=True)
df1.rename(columns = {'value':'fear_greed', 'timestamp':'date'}, inplace=True)
df1.drop(['time_until_update'], axis=1, inplace=True)

Los datos del índice de miedo y avaricia se unen con los datos de precios de bitcoin en dólares.

data = df.merge(df1, on='timestamp')
data = data.sort_index()
data.tail()

Gráfico del precio de BTC coloreado en base al sentimiento del mercado marcado por el índice Fear and Greed.
Los colores más azulados corresponden al sentimiento de miedo y los más amarillentos a la euforia.

Se aprecia en la gráfica que en los periodos de subida de precio predominan los colores amarillentos y en los de bajada son los azules y violetas los colores más recurrentes.

fig = px.scatter(data, x="date", y="close", color="fear_greed",
                 title="BTC price with fear and greed index in continuous color")
fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

Se implementa una estrategia DCA donde se compra BTC una vez a la semana y sólo cuando el F&G es mayor de 50.

limit_fear_greed = 50
buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy = data[(data.index.isin(buy_dates) & (data.fear_greed > limit_fear_greed))]

# La cantidad de dolares disponibles semanalmente para comprar es de $100
buy_dca = 100
data_buy['btc_amt'] = buy_dca / data_buy.close
data_buy['btc_amt_sum'] = data_buy.btc_amt.cumsum()
data_buy

El periodo del que se disponen datos del índice F&G es del 1 de febrero del 2018 hasta la actualidad.

print(data_buy.index[0])
print(data_buy.index[-1])

2018-02-18 00:00:00
2021-11-14 00:00:00

Cálculo de los gastos y beneficios de la estrategia mixta (DCA y F&G) sin tener en cuenta las comisiones por la compra de BTC.

spent = buy_dca * len(data_buy)
amount = data_buy.iloc[-1].btc_amt_sum * data.iloc[-1].close
print("Nº of purchases: \t " + str(len(data_buy)))
print("Spent: \t\t\t $" + str(spent))
print("Gross profit: \t\t $" + str(amount))
print("Net profit: \t\t $" + str(amount - spent))

Nº of purchases: 81
Spent: $8100
Gross profit: $12389.597549207663
Net profit: $4289.597549207663

Gráfico semanal del precio de bitcoin cuando el índice de Fear and Greed es mayor de 50.
Los círculos que aparecen en la gráfica nos indican los momentos de compra según esta estrategia. Se aprecian 3 zonas de acumulación de ellos que coinciden con los periodos bullish del precio.

  • Una primera zona de febrero a agosto del año 2019 donde la subida es comedida y la euforia es menor.
  • Una segunda desde el agosto del 2020 hasta mayo del 2021 donde se produce una de las grandes corridas alcistas de bitcoin y el euforia es máxima llegando a alcanzar valores de 95 puntos. 
  • Y una última de agosto 2021 hasta noviembre del 2021 donde la euforia es menor pero donde se alcanza el ATH (el valor más alto de todos los tiempos) el 9 de noviembre del 2021, desde entonces el índice fear and greed no ha vuelto a sobrepasar los 50 por lo cual no se habría ejecutado ninguna orden de compra.

fig = px.scatter(data_buy, x="date", y="close", color="fear_greed",
                 title="BTC weekly price with fear and greed index only when F&G > 50")

fig.update_layout({
    "plot_bgcolor": "rgba(0, 0, 0, 0)",
    "paper_bgcolor": "rgba(0, 0, 0, 0)",
})
fig.show()

Cálculo del desempeño de la una estrategia DCA pura donde se compran BTC todas las semanas.

buy_dates = pd.date_range(data.index[0], data.index[-1], freq='1W')
data_buy_dca_week = data[(data.index.isin(buy_dates))]

# Se calcula la compra semanal en dólares para que el valor gastado durante el periodo sea parecido en los dos supuestos 
buy_dca_week = buy_dca * len(data_buy) / len(data_buy_dca_week)
data_buy_dca_week['btc_amt'] = buy_dca_week / data_buy_dca_week.close
data_buy_dca_week['btc_amt_sum'] = data_buy_dca_week.btc_amt.cumsum()
buy_dca_week

32.66129032258065

A la hora de calcular los beneficios de la estrategia DCA tampoco se tienen en cuenta las comisiones por la compra de bitcoin.

spent_dca_week = buy_dca_week * len(data_buy_dca_week)
amount_dca_week = data_buy_dca_week.iloc[-1].btc_amt_sum * data.iloc[-1].close

print("Nº of purchases: \t " + str(len(data_buy_dca_week)))
print("Spent: \t\t\t $" + str(spent_dca_week))
print("Gross profit: \t\t $" + str(amount_dca_week))
print("Net profit: \t\t $" + str(amount_dca_week - spent_dca_week))

Nº of purchases: 248
Spent: $8100.000000000001
Gross profit: $15127.876797682371
Net profit: $7027.87679768237

Gráfico comparativo donde se muestra como se van acumulando los BTC adquiridos en la estrategía mixta de DCA y F&G.
En el caso de la línea de DCA and F&G no aparecen datos desde noviembre 2021 porque desde entonces el índice Fear and Greed no ha superado los 50 puntos.

data_buy['btc_amt_sum'].plot(label='DCA and F&G')
data_buy_dca_week['btc_amt_sum'].plot(label='DCA')
plt.legend()
plt.show()

Comparativa de las dos estrategias de inversión en números.

print("#####\t DCA and F&G Strategy \t#####")
print("Spent: \t\t\t $" + str(spent))
print("Net profit: \t\t $" + str(amount - spent))
print("Accumulated BTC: \t " + str(data_buy.iloc[-1].btc_amt_sum))
print("\n#####\t DCA Strategy \t\t#####")
print("Spent: \t\t\t $" + str(spent_dca_week))
print("Net profit: \t\t $" + str(amount_dca_week - spent_dca_week))
print("Accumulated BTC: \t " + str(data_buy_dca_week.iloc[-1].btc_amt_sum))

DCA and F&G Strategy
Spent: $8100
Net profit: $4289.597549207663
Accumulated BTC: 0.627840393893085

DCA Strategy
Spent: $8100.000000000001
Net profit: $7027.87679768237
Accumulated BTC: 0.7666021506913571

A la vista de lo números la estrategia mixta de inversión en bitcoin de DCA y el índice Fear and Greed en el periodo estudiado es peor que una estrategia de compra recurrente de la misma cantidad de dinero.
En este periodo tendríamos un gasto de 8100 dólares y 0.62 BTC en nuestra cuenta, en el caso de la estrategía combinada que equivalen $4527 descontando los gastos de compra y tendríamos 0.76 BTC si hubiésemos optado por un DCA que al precio de hoy quitando los gastos son unos $7300.

Enlace al notebook en kaggle Study Bitcoin strategy DCA with Fear and Greed

Enlace al código Python en github Study Bitcoin strategy combining DCA with Fear Greed index

Is it profitable to trade bitcoin from the Fear and Greed index?

2 November 2022 at 20:04

Analysis of a basic case

If there is one indicator that bitcoin price doomsayers like, it is without a doubt the Fear and Greed Index, which is published daily on the Crypto Fear & Greed Index.

It is a metric that tries to guess the market sentiment, if it is positive (>50) it presupposes that there will be a greater demand for BTC so the price will rise and if it is negative (<50) it will result in sales of the asset with the consequent price drop.indicator Alternative for bitcoin has been published since 2/5/2018.

We are going to carry out a study to find out if it is profitable to buy and sell BTC following this indicator, which is known as backtesting, we choose a basic case where bitcoin is bought when the index is greater than 50, which is the value where it starts greed, and are sold when it drops below that limit. We will use the Python programming language together with the libraries that it has prepared for this type of analysis.

This metric is built daily from 5 data sources:

  • Volatility (25%). The volatility of the previous day is compared with the averages of the last 30 and 90 days. The idea behind it would be that high volatility is a sign of a fearful market.
  • Market volume/momentum (25%). This indicator compares yesterday’s volume with the average values ​​of the last 30 and 90 days. Understanding that high buying volumes indicate that the market is greedy and bullish.
  • Social Networks (15%). Analysis of messages on Twitter related to Bitcoin. High engagement rates mean more interest which translates into a greedy market.
  • Dominance (10%). The dominance of a coin is similar to the market capitalization share of the entire crypto market. If that bitcoin dominance increases against the other altcoins it is a bullish sign and if it decreases it is a bearish indicator.
  • Trends (10%). This indicator is extracted from the Google Trends data for various search queries related to Bitcoin, these numbers are analyzed and if the number of searches goes up it is assumed that the interest in Bitcoin increases and therefore the euphoria increases and the fear decreases.

First, the behavior of the Fear and Greed (F&G) indicator will be analyzed without taking into account the evolution of bitcoin prices.

For this we import the python libraries that will be used.

import pandas as pd
import numpy as np 
import requests
import matplotlib.pyplot as plt
import seaborn as sns
import yfinance as yf
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from scipy.stats import norm
from pylab import rcParams
import warnings

warnings.filterwarnings( 'ignore')
rcParams['figure.figsize'] = 10, 5

Data is downloaded Fear and Greed index data history

# Data download of https://alternative.me/crypto/fear-and-greed-index/
# The index fear_greed that shows today is the value calculated with yesterday's data
r = requests.get('https://api.alternative.me/fng/?limit=0')

A graph is shown with the time evolution of the

# Show fear and greed index since the beginning of the year 2018
# The values range between 0 and 100, with low values indicating fear and high values indicating euphoria.
df = pd.DataFrame(r.json()['data'])
df.value = df.value.astype(int)
df.timestamp = pd.to_datetime(df.timestamp, unit='s')
df.set_index (df.timestamp, inplace=True)
df.rename(columns = {'value':'fear_greed'}, inplace=True)
df.drop(['timestamp', 'time_until_update'], axis=1, inplace=True )
df.fear_greed.plot(figsize=(20,10))

The values ​​of the F&G index range from 0 to 100, where low data indicates fear in the market and high data indicates euphoria.

A priori, seeing the graph, no clear conclusions can be drawn, so I will choose to “interrogate” the data.

Initially, I look at the distribution of the values ​​and it can be seen that most of the data are around the value 26, which indicates that fear has predominated in this period and that the high values ​​associated with euphoria are less frequent.

# Show in a graph the distribution of the values ​​of the fear and euphoria index
# Where it can be seen that in this period the most recurrent values ​​are around 20 and 40, which are indicators of fear
sns.distplot(df['fear_greed' ], color='g', bins=30)

The mean is 42, the median is 39, which indicates that in this period, 2018 to 2022, in general terms there has been more fear than euphoria and in the box plot it can be seen Furthermore, most of the values ​​are between 24 and 59 and the rest of the values ​​are less frequent.

# The mean and median values ​​are around 40, which indicates that fear prevails over euphoria
print("Mean: " + str(df.fear_greed.mean()))
print("Median: " + str(df.fear_greed.median( )))
sns.boxplot(x='fear_greed', data=data)

If we analyze the autocorrelation of the sample data we will see that it exists and is greater the closer the data are. Which seems logical since fear and euphoria follow trends, they do not change arbitrarily from one day to the next and they will always have more influence on today’s value, yesterday’s data, than the day before yesterday, than two days ago. … and as the days go by this influence decreases.

# There is a high autocorrelation in the fear and greed index that decreases little by little as the days go by
# It is normal since fear and greed work for periods it is not usual to go from extreme fear one day to high greed the next day
# Today's index is more likely to be more like yesterday's than 2 weeks ago as trend changes take time to occur
plot_acf(df["fear_greed"], lags=30)
plt.show()

Regarding partial autocorrelation we don’t see this dependency so staggered, the data from yesterday and the day before yesterday have an influence, but the rest is already irrelevance.

# The partial autocorrelation is strong with respect to yesterday, a little more with the day before yesterday, but after those two days
# Does not exist since they are statistically insignificant since they are within the confidence interval (shaded part)
plot_pacf(df[" fear_greed"], lags=30)
plt.show()

This correlation that occurs in the value of F&G with previous days is not maintained if we focus on the increase or decrease in value from one day to the next where if we have a greater randomness.

# But if we focus on the variations of the index from one day to the next, we do find a great randomness
df.fear_greed.diff().plot(figsize=(15,6))
# If the distribution of values ​​of the difference is shown, we see that it is an almost normal distribution centered on a value close to 0
sns.distplot(df.fear_greed.diff(), color='c', bins=30, fit=norm)

Now it’s time to analyze the price of bitcoin in relation to the F&G index and for this reason I start by downloading the data of the closing price of bitcoin from the Yahoo finance website.

# Data Bitcoin price download of yahoo finance
df1 = yf.download('BTC-USD', interval = '1d')[['Close']]
df1.rename(columns = {'Close':'close'}, inplace =True)
df1.index.name = 'timestamp'
df1['timestamp'] = df1.index
df1.reset_index(drop=True, inplace=True)
df1.timestamp = pd.to_datetime(df1.timestamp, unit='s ').dt.tz_localize(None)
df1.set_index(df1.timestamp, inplace=True)
df1.drop(['timestamp'], axis=1, inplace=True)

We join in the same dataframe the index data plus the of the BTC price.

# The fear and greed index data is merged with the bitcoin price data in dollars
data = df.merge(df1, on='timestamp')
data = data.sort_index()
data.tail()

I show the price history in a graph of bitcoin from 5/2/2018 to the end of 2022 which is the data we have from the F&G index.

Making a very brief analysis, several differentiated periods can be seen:

  • From 2018 to the end of 2020, where there is relative stability in the price
  • From the end of 2020 to the first quarter of 2021, where there is an upward period, then we have a downward period, and then we get in November 2021 the highest price of BTC in history
  • And from then until the end of 2022 we live a bearish period
# The graph of the price of bitcoin during that same period
# Briefly analyzed we see a relative stability between 2018 and the end of 2020
# Subsequently a very pronounced rise until the end of the first quarter of 2021
# Then a descent followed by a big rise ending at the end of 2022
# And since then a bearish period
data.close.plot()

In order to compare prices and to know how good this indicator is to predict them we have to take into account that today’s Fear and Greed index data is published at 00:00 UTC from the information of the previous day and the pr One-day bitcoin closing price is its market value at 00:00 UTC. This means that at 00:00 UTC of the day we have the F&G index with today’s date and the closing price of BTC also with today’s date and with that information we want to execute a buy or sell strategy and that we will have to compare it to tomorrow’s closing price at 00:00 UTC of bitcoin.

# The fear and greed index is published at 00:00 UTC taking into account the data of the previous day
# The closing data of the bitcoin price is the value at 00:00 UTC
# Therefore, in order to make money, the value to be compared with is the closing price of the next day

# A column is included with the data from tomorrow's close and the difference between the two values
​​# Another columns with returns in value today and tomorrow and change ntc price

data['close_tomorrow'] = data['close'].shift(-1)
data['returns'] = data['close_tomorrow'] / data['close'] - 1
data['change_btc'] = (data['returns'] + 1 ).cumprod()
data = data.dropna()

Before carrying out the strategy, we see that the correlation between the F&G index and the BTC price of the following day is 0.24, a value above 0 indicates that there is a relationship, at least in the period studied, between the two values.

# We perform a correlation between the F&G index and the closing price of BTC the next day
# A total correlation would be 1 and 0 indicates that there is no correlation, so 0.24 indicates that there is a slight correlation
data['fear_greed']. corr(data['close_tomorrow'])

0.2400391649234413

We define the basic strategy where we proceed to buy when the F&G indicator is greater than 50 and sell when it is less than that value.

# A basic BTC purchase strategy is analyzed when the fear and greed index is greater than 50 
# and when it is less than that value, nothing is done
data['signal'] = np.where(data.fear_greed > 50, 1, 0)
data['strategy'] = (data['returns'] +1) ** data['signal']
data['cumulative'] = data[['strategy']].dropna().cumprod()
data.tail()

We show the backtesting in a graph where the performance of the chosen strategy is observed together with the evolution of the bitcoin price for the same period.

# Graph of the performance of the strategy compared to the evolution of the price
plt.figure(figsize=(20,10))
plt.plot(data['cumulative'], label ='Cumulative')
plt.plot(data[ 'change_btc'], label ='BTC')
plt.legend()

The result of this strategy is clearly positive with a profit of about 600%. In the final part of the graph it can be seen that the benefit remains horizontal because the Fear and Greed index has had values ​​below 50 since April 5, 2022.

# It is clearly observed that it is a good strategy for the period studied.
print('Initial value: \t' + str(data['cumulative'].iloc[1]))
print('End value: \t' + str(data['cumulative'].iloc[-2]) )
print('End value BTC: \t' + str(data['change_btc'].iloc[-2]))

Initial value: 1.0
End value: 6.430155875523231
End value BTC: 2.264909298446648

At first it seems like a very good strategy but now We know that the devil is in the details:

  • It is only 100% valid for the period, 02/05/2018 to 10/27/2022, but we do not know the performance it would have if we had a larger history of Fear and Greed index data.
  • The percentage of final profit is dependent on the initial point and the final point chosen with other references, the benefit can fluctuate considerably, but it is true that the graph shows that most of the time it has a better performance than the price of BTC.
  • The calculation of the profit follows the typical analysis of trading strategies where percentages are calculated, which is equivalent to the fact that every time a buy signal is given, all the capital is used, which is not very realistic.
  • And most importantly, the commissions that are going to be very important in this strategy have not been taken into account because all the available capital is being used in the purchase and sale orders.

I create a function to calculate the real profit of this strategy assuming that only an initial capital is used, that when there is a feeling of euphoria above 50 all the capital is used to buy BTC and that when the index falls below 50 all are sold bitcoin and including commissions.

# I carry out the most realistic practical exercise starting with an initial investment and adding a commission on purchases and sales
# Everything is sold when the buy signal runs out since in this strategy all the capital is used for buying and selling and the money is needed to buy again

def profit_calculation (_data, _initial_capital, _feeds):
  n_buy_sell = 0
  sell = 0
  profit = _initial_capital
  i = 0
  _buy_where = []
  _sell_where = []

  for date,row in data.iterrows(): 
      i+=1 
      if row['signal'] == 1:
          n_buy_sell += 1                
          buy = (profit / row['close'])*(1-_feeds) 
          _data.at[date, 'buy'] = buy
          profit = buy * row['close_tomorrow']
          _data.at[date, 'profit'] = profit
          sell = profit
          _buy_where.append(i)

      elif sell != 0:
          n_buy_sell += 1
          sell_BTC = (sell/ row['close'])*(1-_feeds) 
          _data.at[date, 'profit'] = profit
          _data.at[date, 'sell'] = sell_BTC
          profit = sell
          sell = 0
          _sell_where.append(i)

  print("Nº buy and sell: \t" + str(n_buy_sell))
  print("Feeds: \t\t\t" + str(_feeds) + "%")
  print("Initial capital: \t$" + str(_initial_capital))
  print("End capital: \t\t$" + str(round(profit,2)))
  print("Profit: \t\t$" + str(round(profit - _initial_capital, 2)))

  return(_buy_where, _sell_where)

The practical exercise is carried out with an initial capital of 10,000 dollars and we assume that the broker charges a commission of 0.3% for each purchase or sale.

# Initial investment of $10,000 and a commission of 0.3%
feeds = 0.003
initial_portfolio = 10000
portfolio_calculation(data, initial_portfolio, feeds)

The number of times buy or sell orders have been launched is 619 when about 1700 days have passed.

The capital that would be available today (October 27, 2022) is $11,846, $10,000 has been initially invested, so the total profit is $1,846, far from the 600% that the backtesting of the strategy indicated.

This is due to the commissions that, although they do not seem very high, having made so many purchases and sales and always with the total capital, makes the profits drop considerably.

No. buy and sell: 	619
Feeds: 			    0.003%
Initial portfolio: 	$10,000
End Portfolio: 		$11,846.65
Profit: 		    $1,846.65
plt.figure(figsize=(20,10))
plt.plot(data.close, label='BTC', c='y')
plt.scatter(data.iloc[buy_where].index,data.iloc[buy_where]['close'],marker='^',color='g',s=100)
plt.scatter(data.iloc[sell_where].index,data.iloc[sell_where]['close'],marker='v',color='r',s=100)
plt.legend()
plt.show()

We stop the exercise here, leaving the reader to try other strategies on this F&G index for himself.

Notebook in Python with the script to be able to copy and execute it Bitcoin Price Prediction with the Fear and Greed

Notebook in Github Bitcoin price prediction with the fear and greed

¿Es rentable realizar trading en bitcoin a partir del índice Fear and Greed?

28 October 2022 at 12:24

Análisis de un caso básico

Si hay un indicador que les guste a los agoreros del precio de bitcoin es sin duda el índice Fear and Greed (miedo y codicia) que se publica diariamente en la web de Crypto Fear & Greed Index.

Es una métrica que intenta adivinar el sentimiento del mercado, si este es positivo (>50) presupone que habrá una mayor demanda de BTC por lo que el precio subirá y si es negativo (<50) se traducirá en ventas del activo con la consiguiente bajada del precio. Este indicador de Alternative para bitcoin lleva publicándose desde el 5/2/2018.

Vamos a realizar un estudio para conocer si es rentable la compra y venta de BTC siguiendo este indicador, lo que se conoce como un backtesting, escogemos un caso básico donde se compran bitcoin cuando el índice es mayor que 50, que es el valor donde empieza la codicia, y se venden cuando baja por debajo de ese límite. Utilizaremos el lenguaje de programación Python junto con las librerías que tiene preparadas para este tipo de análisis.

Esta métrica la construyen diariamente a partir de 5 fuentes de datos:

  • Volatilidad (25 %). Se compara la volatilidad del día anterior con los promedios de los últimos 30 y 90 días. La idea que hay detrás sería que una alta volatilidad es una señal de un mercado temeroso.
  • Volumen / impulso del mercado (25 %). En este indicador se compara el volumen de ayer con los valores promedio de los últimos 30 y 90 días. Entendiendo que altos volúmenes de compra indican que el mercado está codicioso y alcista.
  • Redes Sociales (15%). Análisis de los mensajes en Twitter relacionados con Bitcoin. Tasas de interacciones altas significan más interés lo que se traduce en un mercado codicioso.
  • Dominancia (10%). El dominio de una moneda se asemeja a la cuota de capitalización de mercado de todo el criptomercado. Si aumenta ese dominio de bitcoin frente a las otras altcoins es una señal alcista y si disminuye es un indicador bajista.
  • Tendencias (10%). Este indicador se extrae de los datos de Google Trends para varias consultas de búsqueda relacionadas con Bitcoin, se analizan estos números y si el número de búsquedas sube se supone que el interés por Bitcoin aumenta y que por consiguiente aumenta la euforia y disminuye el miedo.

Primero se va a analizar el comportamiento del indicador Fear and Greed (F&G) sin tener en cuenta la evolución de precios de bitcoin.

Para ello importamos las librerías de python que se utilizarán.

import pandas as pd
import numpy as np 
import requests
import matplotlib.pyplot as plt
import seaborn as sns
import yfinance as yf
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from scipy.stats import norm
from pylab import rcParams
import warnings

warnings.filterwarnings('ignore')
rcParams['figure.figsize'] = 10, 5

Se descarga el histórico de datos del índice Fear and Greed

# Data download of https://alternative.me/crypto/fear-and-greed-index/
# The index fear_greed that shows today is the value calculated with yesterday's data
r = requests.get('https://api.alternative.me/fng/?limit=0')

Se muestra una gráfica con la evolución temporal del indicador

# Show fear and greed index since the beginning of the year 2018
# The values range between 0 and 100, with low values indicating fear and high values indicating euphoria.
df = pd.DataFrame(r.json()['data'])
df.value = df.value.astype(int)
df.timestamp = pd.to_datetime(df.timestamp, unit='s')
df.set_index(df.timestamp, inplace=True)
df.rename(columns = {'value':'fear_greed'}, inplace=True)
df.drop(['timestamp', 'time_until_update'], axis=1, inplace=True)
df.fear_greed.plot(figsize=(20,10))

Los valores del índice F&G se mueven entre el 0 al 100, donde los datos bajos indican miedo en el mercado y los altos euforia.

A priori viendo la gráfica no se pueden extraer conclusiones claras así que optaré por “interrogar” a los datos.

Inicialmente miro la distribución de los valores y se aprecia que la mayor parte de los datos están alrededor del valor 26 lo cual indica que en este periodo ha predominado el miedo y que los valores altos asociados con la euforia son menos frecuentes.

# Show in a graph the distribution of the values of the fear and euphoria index
# Where it can be seen that in this period the most recurrent values are around 20 and 40, which are indicators of fear
sns.distplot(df['fear_greed'], color='g', bins=30)

La media es 42, la mediana 39 lo que nos indica que en este periodo, 2018 a 2022, en términos generales ha habido más miedo que euforia y en el gráfico de caja se ve que además la mayor parte de los valores están entre el 24 y el 59 y que el resto de valores son menos frecuentes.

# The mean and median values are around 40, which indicates that fear prevails over euphoria
print("Mean: " + str(df.fear_greed.mean()))
print("Median: " + str(df.fear_greed.median()))
sns.boxplot(x='fear_greed', data=data)

Si analizamos la autocorrelación de los datos de la muestra veremos que esta existe y es mayor cuanto los datos son mas cercanos. Lo cual parece lógico ya que el miedo y la euforia siguen tendencias no cambian arbitrariamente de un día para otro y siempre tendrán más influencia en el valor de hoy, el dato de ayer, que el de antes de ayer, que el de hace dos días… y a medida que pasan los días este influencia va decreciendo.

# There is a high autocorrelation in the fear and greed index that decreases little by little as the days go by
# It is normal since fear and greed work for periods it is not usual to go from extreme fear one day to high greed the next day
# Today's index is more likely to be more like yesterday's than 2 weeks ago as trend changes take time to occur
plot_acf(df["fear_greed"], lags=30)
plt.show()

Con respecto a la autocorrelación parcial no vemos esta dependencia tan escalonada, influyen los datos de ayer y de antes de ayer pero el resto ya entra dentro de la irrelavancia.

# The partial autocorrelation is strong with respect to yesterday, a little more with the day before yesterday, but after those two days
# Does not exist since they are statistically insignificant since they are within the confidence interval (shaded part)
plot_pacf(df["fear_greed"], lags=30)
plt.show() 

Esta correlación que se da en el valor de F&G con los días anteriores no se mantiene si nos centramos en el incremento o decrecimiento del valor de un día para otro donde si tenemos una mayor aletoriedad.

# But if we focus on the variations of the index from one day to the next, we do find a great randomness
df.fear_greed.diff().plot(figsize=(15,6))
# If the distribution of values of the difference is shown, we see that it is an almost normal distribution centered on a value close to 0
sns.distplot(df.fear_greed.diff(), color='c', bins=30, fit=norm)

Ahora toca analizar el precio de bitcoin en relación con el índice F&G y por ello empiezo descargándome los datos del precio de cierre de bitcoin de la web de Yahoo finance.

# Data Bitcoin price download of yahoo finance
df1 = yf.download('BTC-USD', interval = '1d')[['Close']]
df1.rename(columns = {'Close':'close'}, inplace=True)
df1.index.name = 'timestamp'
df1['timestamp'] = df1.index
df1.reset_index(drop=True, inplace=True)
df1.timestamp = pd.to_datetime(df1.timestamp, unit='s').dt.tz_localize(None)
df1.set_index(df1.timestamp, inplace=True)
df1.drop(['timestamp'], axis=1, inplace=True)

Unimos en un mismo dataframe los datos del índice más los del precio de BTC.

# The fear and greed index data is merged with the bitcoin price data in dollars
data = df.merge(df1, on='timestamp')
data = data.sort_index()
data.tail()

Muestro en una gráfica el histórico de precios de bitcoin desde 5/2/2018 hasta finales del 2022 que son los datos que tenemos del índice F&G.

Haciendo un análisis muy somero se aprecian varios periodos diferenciados:

  • Del 2018 a finales del 2020 donde hay una relativa estabilidad en el precio
  • De finales del 2020 hasta el primer cuarto del 2021 donde hay un periodo alcista, posteriormente tenemos un periodo bajista, para luego conseguir en noviembre del 2021 el mayor precio de BTC de la historia
  • Y desde ahí hasta finales del 2022 vivimos un periodo bajista
# The graph of the price of bitcoin during that same period
# Briefly analyzed we see a relative stability between 2018 and the end of 2020
# Subsequently a very pronounced rise until the end of the first quarter of 2021
# Then a descent followed by a big rise ending at the end of 2022
# And since then a bearish period
data.close.plot()

De cara a comparar los precios y saber como de bueno es este indicador para predecirlos tenemos que tener en cuenta que el dato del índice de Fear and Greed de hoy se publica a las 00:00 UTC a partir de la información del día anterior y el precio de cierre de bitcoin de un día es su valor de mercado a las 00:00 UTC. Esto supone que a las 00:00 UTC del día tenemos el índice F&G con la fecha de hoy y el precio de cierre de BTC también con la fecha de hoy y con esa información queremos ejecutar una estrategia de compra o de venta y que tendremos que compararla con el precio de cierre de mañana a las 00:00 UTC de bitcoin.

# The fear and greed index is published at 00:00 UTC taking into account the data of the previous day
# The closing data of the bitcoin price is the value at 00:00 UTC
# Therefore, in order to make money, the value to be compared with is the closing price of the next day

# A column is included with the data from tomorrow's close and the difference between the two values
# Another columns with returns in value today and tomorrow and change ntc price

data['close_tomorrow'] = data['close'].shift(-1)
data['returns'] = data['close_tomorrow'] / data['close'] - 1
data['change_btc'] = (data['returns'] + 1).cumprod()
data = data.dropna()

Antes de realizar la estrategia vemos que la correlación entre el índice F&G y el precio de BTC del día siguiente es de 0.24 un valor por encima de 0 indica que si que existe una relación, por lo menos en el periodo estudiado, entre los dos valores.

# We perform a correlation between the F&G index and the closing price of BTC the next day
# A total correlation would be 1 and 0 indicates that there is no correlation, so 0.24 indicates that there is a slight correlation
data['fear_greed'].corr(data['close_tomorrow'])
0.2400391649234413

Definimos la estrategia básica donde se procede a comprar cuando el indicador F&G sea mayor que 50 y se vende cuando es menor que ese valor.

# A basic BTC purchase strategy is analyzed when the fear and greed index is greater than 50 
# and when it is less than that value, nothing is done
data['signal'] = np.where(data.fear_greed > 50, 1, 0)
data['strategy'] = (data['returns'] +1) ** data['signal']
data['cumulative'] = data[['strategy']].dropna().cumprod()
data.tail()

Mostramos el backtesting en un gráfico donde se observa el desempeño de la estrategia escogida junto a la evolución del precio de bitcoin para la mismo periodo.

# Graph of the performance of the strategy compared to the evolution of the price
plt.figure(figsize=(20,10))
plt.plot(data['cumulative'], label ='Cumulative')
plt.plot(data['change_btc'], label ='BTC')
plt.legend()

El resultado de esta estrategia es claramente positivo con un beneficio de alrededor de un 600%. En la parte final de la gráfica se aprecia que el beneficio se mantiene en horizontal debido a que el índice Fear and Greed lleva con valores por debajo de 50 desde 5 de abril del 2022.

# It is clearly observed that it is a good strategy for the period studied.
print('Initial value: \t' + str(data['cumulative'].iloc[1]))
print('End value: \t' + str(data['cumulative'].iloc[-2]))
print('End value BTC: \t' + str(data['change_btc'].iloc[-2]))
Initial value: 	1.0
End value: 	    6.430155875523231
End value BTC: 	2.264909298446648

A priori parece una muy buena estrategia pero ya sabemos que el diablo está en los detalles:

  • Es únicamente válida al 100% para el periodo, 5/02/2018 a 27/10/2022, pero desconocemos el rendimiento que tendría si tuviésemos un histórico mayor de datos del índice Fear and Greed.
  • El porcentaje de ganancia final es dependiente del punto inicial y del punto final escogido con otras referencias el beneficio puede oscilar considerablemente pero es cierto que en la gráfica se observa que la mayor parte del tiempo tiene un mejor desempeño que el precio del BTC.
  • El cálculo de la ganancia sigue el análisis típico de estrategias de trading donde se calculan porcentajes lo que equivale a que cada vez que se da una señal de compra se utiliza todo el capital lo cual no es muy realista.
  • Y lo más importante no se han tenido en cuenta las comisiones que van a ser muy importantes en esta estrategia porque se está utilizando todo el capital disponible en las órdenes de compra y venta.

Creo una función para calcular el beneficio real de esta estrategia suponiendo que sólo se utiliza un capital inicial, que cuando hay un sentimiento de euforia por encima de 50 se utiliza todo el capital para comprar BTC y que cuando el índice baja de 50 se venden todos los bitcoin e incluyendo las comisiones.

# I carry out the most realistic practical exercise starting with an initial investment and adding a commission on purchases and sales
# Everything is sold when the buy signal runs out since in this strategy all the capital is used for buying and selling and the money is needed to buy again

def portfolio_calculation (_data, _initial_portfolio, _feeds):
  n_buy_sell = 0
  sell = 0
  portfolio = _initial_portfolio

  for date,row in data.iterrows():      
      if row['signal'] == 1:
          n_buy_sell += 1                
          buy = (portfolio / row['close'])*(1-_feeds) 
          _data.at[date, 'buy'] = buy
          portfolio = buy * row['close_tomorrow']
          _data.at[date, 'portfolio'] = portfolio
          sell = portfolio
      
      elif sell != 0:
          n_buy_sell += 1
          sell_BTC = (sell/ row['close'])*(1-_feeds) 
          _data.at[date, 'portfolio'] = portfolio
          _data.at[date, 'sell'] = sell_BTC
          portfolio = sell
          sell = 0

  print("Nº buy and sell: \t" + str(n_buy_sell))
  print("Feeds: \t\t\t" + str(_feeds) + "%")
  print("Initial portfolio: \t$" + str(_initial_portfolio))
  print("End Portfolio: \t\t$" + str(round(portfolio,2)))
  print("Profit: \t\t$" + str(round(portfolio-_initial_portfolio, 2)))

Se realiza el ejercicio práctico con un capital inicial de 10000 dólares y suponemos que el broker cobra una comisión de un 0.3% por cada compra o venta.

# Initial investment of $10,000 and a commission of 0.3%
feeds = 0.003
initial_portfolio = 10000
portfolio_calculation(data, initial_portfolio, feeds)

El número de veces que se han lanzado órdenes de compra o venta es de 619 cuando han pasado unos 1700 días.

El capital que se tendría a día de hoy (27 de octubre 2022) es de 11846 dólares, se han invertido inicialmente 10000 $ así que el beneficio total es de 1846 $, muy lejos del 600% que nos indicaba el backtesting de la estrategia.

Esto es debido a las comisiones que aunque no parecen muy altas al haber realizado tantas compras y ventas y siempre con el total del capital hace que los beneficios bajen considerablemente.

Nº buy and sell: 	619
Feeds: 			    0.003%
Initial portfolio: 	$10000
End Portfolio: 		$11846.65
Profit: 		    $1846.65

Paramos aquí el ejercicio dejando al lector que pruebe por si mismo otras estrategias sobre este índice F&G.

Notebook en Python con el script para poder copiarlo y ejecutarlo Bitcoin Price Prediction with the Fear and Greed

Versión en Inglés: Is it profitable to trade bitcoin from the Fear and Greed index?

No creo en el chartismo

30 May 2022 at 21:32

No lo puedo negar, soy un escéptico del análisis técnico para Bitcoin, posiblemente si tuviese conocimiento sobre otro tipo de activos podría generalizar mi repulsa pero como soy un neófito en el resto de mercados sólo lo mantengo para bitcoin. 

La mayor parte de las estrategías básicas del llamado análisis técnico, como RSI, líneas de soporte y resistencia, canales, medias móviles… no soportan un backtesting en condiciones. Un backtesting en el mundo del trading es el método para determinar si una estrategia ha sido rentable en el pasado, para comprobarlo se valida su tesis contra todo (o parte) del histórico de datos y se determina si ha sido rentable y cuando y cuanto lo ha sido. 

Tampoco creo en las estrategías más avanzadas del estilo Bandas de Bollinger, MACD, niveles de Fibonacci, ondas de Elliott… sean más fiables, si realmente fuesen certeras todos los que las aplican serían millonarios y el resto las estaría aprendiendo para serlo en el futuro próximo y claramente no es así. Más bien suelen ser una buena forma de perder dinero. 

Ni las tendencias hombro-cabeza-hombro, ni cruces de la muerte, ni patrones de revisión alcista o bajista… son indicadores que aseguren que el precio vaya a comportarse de una forma determinada.

Resumiendo, mi sensación con el análisis técnico en BTC es que vale para que los traders profesionales y con experiencia lo aprovechen para prever las actuaciones de los no expertos y así hacerse con sus satoshis.

Por si quedase alguna duda, y a modo de apunte, los brokers CFD están obligados a publicar los traders que ganan o pierden en sus plataformas y los números para la mayoría son realmente malos.

Cuando las estrategías tienen unas reglas numéricas claras es fácil aplicar un backtesting para chequear su validez o invalidez para predecir los precios, por ejemplo un RSI XXX pero cuando se “analizan los patrones” en las gráficas es más complicado por lo indeterminadas que son, lo que hace que sea un campo abonado para que los chartistas nos vendan sus análisis, que resumiendo mucho, la mayor parte de las veces vienen a decir que el precio puede bajar hasta el soporte “Bitcoin, es mejor seguir el RSI o comprar y mantener (hodl)” o puede subir hasta la resistencia YYY. Otro clásico es cuando proponen comprar porque va a subir y luego resulta que baja y salen que es porque ha habido manipulación en el precio. Si lo dudáis podéis veros unos cuantos vídeos de youtubers, influencers, streamers expertos en predecir el precio de bitcoin.

La literatura básica para traders está llena de consejos que no funcionan y sus autores hacen caja a costa de los incautos que piensan que allí están las recetas para hacer dinero de la forma más fácil y para su desgracia no es así. Para desgracia de todos la vida no es tan fácil.  

En el siguiente post entraré en el análisis del indicador Fear & Greed que tanto gusta a los youtubers, influencers y demás expertos en el análisis técnico del precio de bitcoin. Haré un backtesting para conocer su capacidad predictiva real en el precio de BTC.

Viabilidad de un escenario de minado doméstico con bitcoin

9 May 2022 at 00:34

Pertenezco al numeroso grupo de mineros domésticos de Ethereum que debido a que esta actividad para esta moneda tiene fecha de caducidad y que será en unos meses por el cambio en el proceso de minado que pasará de la prueba de trabajo (PoW) a la prueba de participación (PoS) está buscando la posibilidad de minar otra moneda, y qué mejor que hacerlo con BTC directamente, que con diferencia es el mejor activo digital que tenemos.

Para ello vamos a analizar la viabilidad económica de un escenario concreto de minería doméstica de BTC. 

A modo de disclaimer hay que aclarar que es un estudio de un caso concreto teniendo en cuenta 4 variables, no es algo que nos pueda valer para extraer conclusiones definitivas ya que es limitado y algunas de estas variables son cambiantes en el tiempo y de difícil predicción pero nos vale como una primera aproximación para saber si es interesante meterse en esa actividad o si es necesario profundizar más. Un análisis completo y preciso necesitaría del uso del método Montecarlo y me lo dejaré en la recámara para poder realizarlo en el futuro.

 El escenario a valorar va a intentar ser favorable a la minería y será el siguiente:

  • No vamos a tener en cuenta el gasto energético (0 €/kWh). Este posiblemente sea el parámetro más importante a la hora de valorar si es rentable o no minar pero es muy variable dependiendo del país donde nos encontremos y además no tenerlo en cuenta nos permite realizar el estudio sólo con bitcoin sin tener en cuenta el fiat.
  • Vamos a elegir el ASIC Antminer S19 Pro que en el mercado minorista a día de hoy está a unos 9000 € que si los pasamos a BTC, aumentando su precio un 20% (38400 € = 32000 * 1,2) porque actualmente se encuentra muy afectado por la subida de los tipos de interés, medido en BTC se quedaría en 0,234375. Aquí está una de las claves del estudio porque a día de hoy el precio del ASIC está muy caro en relación con el precio del BTC, no siempre ha sido así.
  • El incremento de la dificultad de minado. Los beneficios de los mineros son directamente proporcionales a la dificultad y está ha variado en los últimos años de esta forma. Escogeré un porcentaje de incremento de la dificultad de un 20%. 
FechaDificultadPorcentaje de cambio anual
2022-04-272979440758931218,96%
2021-05-132504648759008355,52%
2020-05-0516104807485529140,20%
2019-05-18670463268058761,80%
Fuente: btc.com
  • La producción diaria de BTC a día de hoy del ASIC Antminer S19 Pro sin hacerle un overclock es de 0,0005 BTC.
Escenario propuesto
Precio BTC (€)38400
Precio del Antminer S19 Pro (€)9000
Precio minero Antminer S19 Pro (BTC)0,234375
Incremento de la dificultad anual20,00%
Producción diaria (BTC)0,0005
Fuente producción diaria S19 Pro: minerstat

Si no tenemos en cuenta la disminución del beneficio por el incremento de la dificultad tendríamos que los días necesarios para recuperar la inversión realizada en la compra del minero es de 468 días.

Días ROI = Coste minero Antminer S19 Pro (BTC) / Producción diaria (BTC) = 0,234375 / 0,0005 = 468 días

Para calcular los días necesarios para recuperar la inversión voy a crear una tabla con los datos diarios del descuento diario por la dificultad, la generación diaria y los BTC que se van acumulando y cuando estos BTC lleguen a 0,234375, el precio del ASIC  tendremos el ROI (Retorno de la Inversión) los días necesarios para recuperar el dinero puesto para pagar el ASIC. 

El descuento diario por el incremento de la dificultad es: 

Producción diaria (BTC) * Incremento de la dificultad anual / 365

La generación diaria de BTC teniendo en cuenta el descuento por dificultad es: 

El descuento diario por el incremento de la dificultad - la generación de BTC del día anterior

DíasDescuento diario por la dificultadGeneración diaria BTC con el descuento por dificultadBTC acumulados
10,00000027397260270,0004997260274
20,00000027382248080,00049945220490,0009991782323
30,00000027367244110,00049917853250,001498356765
40,00000027352248350,000498905010,001997261775
50,00000027337260820,00049863163740,002495893412
60,0000002732228150,00049835841460,002994251827
70,00000027307310390,00049808534150,003492337168
80,00000027292347480,0004978124180,003990149586
90,00000027277392770,00049753964410,00448768923
100,00000027262446250,00049726701960,00498495625
110,00000027247507920,00049699454450,005481950794

…

5380,00000020411853750,00037231221230,2329025247
5390,00000020400669170,00037210820560,2332746329
5400,00000020389490720,00037190431070,2336465372
5410,0000002037831840,00037170052750,2340182378
5420,00000020367152190,0003714968560,2343897346

Los días necesarios para recuperar la inversión realizada en el ASIC teniendo en cuenta la depreciación por el incremento de la dificultad serían 542 

Mostrado en una gráfica los BTC acumulados frente a los días, quedaría así

La verdad que los números que salen en este escenario para la minería doméstica de BTC en el día de hoy son muy desalentadores ya que ni siquiera estamos teniendo en cuenta los gastos por el precio de la energía, y la comparación frente a una estrategia compra directa de BTC por el mismo capital invertido a día de hoy o simplemente siguiendo una estrategia de compra regulares al estilo DCA (Dollar Cost Average) por el dinero equivalente en la compra del ASIC. 

¿Por qué pasa esto?

  • El precio del BTC de hoy está muy bajo, aunque le he sumado un 20% pero aun así es muy bajo y la historia nos demuestra que la tendencia del precio del bitcoin es claramente ascendente.
  • El precio del ASIC para minoristas a día de hoy está muy caro, normalmente el precio de este aparato ha sido su generación diaria de BTC por 365 pero la gran demanda que hay en la actualidad debida a las grandes empresas mineras que están expandiéndose principalmente por EEUU y la escasez de microchips ha hecho que los precios se hayan disparado.
  • No estamos teniendo en cuenta los gastos de mantenimiento del ASIC ni las posibles paradas del dispositivos por distintos motivos.

¿Es todo tan feo? 

No.

  • Lo más probable es que el precio de BTC siga su trayectoria ascendente por lo que los bitcoin producidos hoy dentro de un año tengan un mayor valor en relación con el fiat.
  • Los BTC generados con los mineros son sin KYC (Know You Customer) no tienen asociado el nombre de ninguna persona.
  • Los BTC generados no tienen casi historia detrás, ya que los generan los mineros (pool minero) y posteriormente, o anteriormente depende de la política del pool, son distribuidos a los propietarios de los ASIC, sea como sea el número de transacciones es mínimo y eso puede ser que en el futuro sea un valor añadido.
  • Este estudio es de un caso particular con unas premisas determinadas y sólo teniendo en cuenta las 4 variables que considero primordiales, sin contar el gasto energético. 

Por último si alguien detecta cualquier error en los cálculos o comentarios de cualquier otra índole serán muy bienvenidos porque soy el primer interesado en realizar home mining con bitcoin.

Bitcoin, it is better to follow the RSI or buy and hodl (HODL)

8 January 2022 at 14:27

It is easy to find multiple sites on the web where they recommend using the RSI (Relative Strength Index) indicator to perform a technical analysis of the price of an asset.

So we are going to examine how one of the most used strategies with this indicator in the last three years has behaved in the case of bitcoin.

The Relative Strength Index (RSI) is a technical indicator that measures the speed and change of price movements, it was developed by J. Welles Wilder.

The RSI moves from 0 to 100 and the most common strategy is to open a long position (buy stocks) if the RSI indicator rises above the 30 level from below because at that time the stocks are considered oversold and if the RSI of the stock crosses the 70 level from above a short position must be entered (selling shares) because the stock is considered to be overbought.

The calculation process to calculate this metric is as follows:

  • The closing price for the last 14 days is tracked.
  • It is determined whether the closing price of the current day is higher or lower than that of the previous day.
  • The average profit or loss for the last 14 days is calculated.
  • The relative strength is calculated, RS = AvgGain / AvgLoss
  • The relative strength index is calculated, RSI = 100 – 100 / (1 + RS)

We are going to carry out a Python program where we will perform a backtest to see if it would have been worth acting as indicated by the RSI.

We import the necessary libraries

import pandas as pd 
import numpy as np 
from datetime import datetime
from pandas_datareader.data import DataReader
import matplotlib.pyplot as plt
from math import floor
from termcolor import colored as cl

Obtain the data of the price of bitcoin in the last 3 years

start = datetime(2019,1,1)
end = datetime(2021,12,31)
df = DataReader('BTC-USD', 'yahoo', start, end)

Calculate the RSI using the exponential moving average in a period of 14 days

periods = 14
df['close_delta'] = df['Close'].diff()
df['gain'] = df['close_delta'].clip(lower=0)
df['loss'] = -1 * df['close_delta'].clip(upper=0)


df['ema_up'] = df['gain'].ewm(com=periods -1, adjust=True).mean()
df['ema_down'] = df['loss'].ewm(com=periods -1, adjust=True).mean()
df['rs'] = df['ema_up']/df['ema_down']
df['rsi'] = 100-(100/(1+df['rs']))

Show the results

plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (20, 10)

ax1 = plt.subplot2grid((10,1), (0,0), rowspan = 4, colspan = 1)
ax2 = plt.subplot2grid((10,1), (5,0), rowspan = 4, colspan = 1)
ax1.plot(df['Close'], linewidth = 2.5)
ax1.set_title('BTC CLOSE PRICE')
ax2.plot(df['rsi'], color = 'orange', linewidth = 2.5)
ax2.axhline(30, linestyle = '--', linewidth = 1.5, color = 'grey')
ax2.axhline(70, linestyle = '--', linewidth = 1.5, color = 'grey')
ax2.set_title('BTC RELATIVE STRENGTH INDEX')
plt.show()

Implement the strategy 30 70

df['return'] = df['Close']/df['Close'].shift(1)
df['signal'] = np.where((df['rsi'] < 30),1,np.nan)
df['signal'] = np.where((df['rsi'] > 70),0,df['signal'])
df['signal'].ffill(inplace=True)
df['strategy'] = df['return'] ** df['signal'].shift(1)

Graph showing the trajectory of the strategy followed

plt.rcParams.update(plt.rcParamsDefault)
df[['strategy']].dropna().cumprod().plot(figsize=(10,6))
As can be seen in the graph, if we had had a profit of 60% (not counting commissions), which means that if on January 1, 2019 we had bought $ 1000 in bitcoin on December 31, 2021 we would have $ 1600 which it is very good and there has been a large period with a profit of 200% and even a peak with a 240%.

Now we are going to buy that profit with the evolution of the price of bitcoin.
df[['return','strategy']].dropna().cumprod().plot(figsize=(10,6))
In this graph it can be seen that the price evolution has really been much better than the strategy followed with the RSI indicator, the price has revalued by 1200% since January 1, 2019 and December 31, 2021, much higher than 60% that we would have achieved with the RSI. If we had bought $ 1,000 at the beginning of 2019, we would have $ 12,000 at the end of 2021.
Not counting the first 4 months of 2019 where the price performance is similar to that of the strategy followed with the RSI, the rest of the time the profit is much higher if we had bought and held the BTC.

Python code (notebook) on github: Bitcoin, it is better to follow the RSI or buy and hodl

Bitcoin, es mejor seguir el RSI o comprar y mantener (hodl)

4 January 2022 at 20:09

Es fácil encontrar múltiples sitios en la web donde recomiendan utilizar el indicador RSI (Relative Strength Index) para realizar un análisis técnico del precio de un activo. 

Así que vamos a examinar cómo se ha comportado una de las estrategías más utilizadas con este indicador en los últimos tres años en el caso de bitcoin.

El índice de fuerza relativa (RSI) es un indicador técnico que mide la velocidad y el cambio de los movimientos de precios, fue desarrollado por J. Welles Wilder.

El RSI se mueve de 0 a 100 y la estrategía más habitual es abrir una posición larga (comprar acciones) si el indicador RSI sube por encima del nivel 30 desde abajo porque en ese momento las acciones se consideran sobrevendidas y si el RSI de la acción cruza el nivel 70 desde arriba se debe entrar en una posición corta (venta de acciones) porque se considera que la acción está sobrecomprada.

El proceso de cálculo para calcular esta métrica es el siguiente:

  • Se hace un seguimiento del precio de cierre de los últimos 14 días.
  • Se determina si el precio de cierre del día actual es más alto o más bajo que el del día anterior.
  • Se calcula la ganancia o pérdida promedio durante los últimos 14 días.
  • Se calcula la fuerza relativa, RS = AvgGain / AvgLoss
  • Se calcula el índice de fuerza relativa, RSI = 100 – 100 / (1 + RS)

Vamos a realizar un programa en Python donde realizaremos un backtest para saber si nos hubiese merecido la pena actuar según lo indicado por el RSI.

Importamos las librerías necesarias

import pandas as pd 
import numpy as np 
from datetime import datetime
from pandas_datareader.data import DataReader
import matplotlib.pyplot as plt
from math import floor
from termcolor import colored as cl 

Obtenemos los datos del precio de bitcoin en los últimos 3 años

start = datetime(2019,1,1)
end = datetime(2021,12,31)
df = DataReader('BTC-USD', 'yahoo', start, end)

Calculamos el RSI utilizando la media móvil exponencial en un periodo de 14 días

periods = 14
df['close_delta'] = df['Close'].diff()
df['gain'] = df['close_delta'].clip(lower=0)
df['loss'] = -1 * df['close_delta'].clip(upper=0)


df['ema_up'] = df['gain'].ewm(com=periods -1, adjust=True).mean()
df['ema_down'] = df['loss'].ewm(com=periods -1, adjust=True).mean()
df['rs'] = df['ema_up']/df['ema_down']
df['rsi'] = 100-(100/(1+df['rs']))

Mostramos los resultados

plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (20, 10)

ax1 = plt.subplot2grid((10,1), (0,0), rowspan = 4, colspan = 1)
ax2 = plt.subplot2grid((10,1), (5,0), rowspan = 4, colspan = 1)
ax1.plot(df['Close'], linewidth = 2.5)
ax1.set_title('BTC CLOSE PRICE')
ax2.plot(df['rsi'], color = 'orange', linewidth = 2.5)
ax2.axhline(30, linestyle = '--', linewidth = 1.5, color = 'grey')
ax2.axhline(70, linestyle = '--', linewidth = 1.5, color = 'grey')
ax2.set_title('BTC RELATIVE STRENGTH INDEX')
plt.show()

Implementamos la estrategia 30 70

df['return'] = df['Close']/df['Close'].shift(1)
df['signal'] = np.where((df['rsi'] < 30),1,np.nan)
df['signal'] = np.where((df['rsi'] > 70),0,df['signal'])
df['signal'].ffill(inplace=True)
df['strategy'] = df['return'] ** df['signal'].shift(1)

Gráfico que muestra la trayectoria de la estrategia seguida

plt.rcParams.update(plt.rcParamsDefault)
df[['strategy']].dropna().cumprod().plot(figsize=(10,6))

Según se aprecia en el gráfico si hubiésemos tenido una ganancia de un 60% (sin contar las comisiones), lo que significa que si el 1 de enero de 2019 hubiésemos comprado 1000 $ en bitcoin el 31 de diciembre del 2021 tendríamos 1600 $ lo cual está muy bien y ha habido un periodo grande con una ganancia de un 200% e incluso un pico con una del 240%.

Ahora vamos a comprar esa ganancia con la evolución del precio de bitcoin.    

df[['return','strategy']].dropna().cumprod().plot(figsize=(10,6))

En este gráfico se aprecia que realmente ha sido mucho mejor la evolución del precio que la estrategia seguida con el indicador RSI, el precio se ha revalorizado un 1200% desde el 1 de enero del 2019 y el 31 de diciembre del 2021, muy superior al 60% que hubiésemos conseguido con el RSI. Si hubiésemos comprado 1000 $ al inicio del 2019 tendríamos 12000 $ al final del 2021.

Sin contar los 4 primeros meses del 2019 donde el desempeño del precio es similar al de la estrategia seguida con el RSI, el resto del tiempo la ganancia es mucho mayor si hubiésemos comprado y mantenido los BTC.   

Analysis of the bitcoin price, week 19-25 of July 2021. Realized Price Metric

27 July 2021 at 01:14

This week the price of BTC started at $ 31,500 and ended at $ 34,600, in general terms it is a recovery week in the price where it came to be at $ 29,300 and has ended in a clear rise of more than 8% and with a good bullish projection in the short term.

Possibly the event that has most influenced the rise in the price of bitcoin has been The B Word event on July 21 that brought together Elon Musk CEO of Tesla, SpaceX … Jack Dorsey CEO of Twitter and Square and Catherine Wood , CEO of Ark Invest to chat about the curiosities of Bitcoin. The market was waiting for the statements that Elon Musk was going to make and that for the most part have been pro Bitcoin and he has even acknowledged owning bitcoin in addition to Ethereum and Dogecoin which has pushed the price of BTC higher. This shows us that Elon’s opinions on bitcoin continue to carry a lot of weight with investors mainly in the short term. 

You can see the talk at the following link

Another unconfirmed bullish news is the rumor that Amazon will allow paying with bitcoin at the end of the year. 

Once again, the price of bitcoin behaves the opposite of the generalized sentiment, we had two three weeks with a large part of the analysts and investors predicting a big drop and this week what we have is a rise in the price that has not yet found its resistance so it will foreseeably continue to rise.

One more example of this negative sentiment is the high number of short positions that were opened on Sunday, July 25, that is, we have many more people betting that bitcoin is going to fall in price than people who think it is going to rise. The volume of the short is surprising for a long time that it has not been seen something the same and also with the little volume that is currently in the Spot market, in any case they have not been successful and the losses have been considerable and most of them were leveraged. 

In the last 24 hours, more than 800 million dollars of short positions have been liquidated in the futures market to more than one this has done a lot of damage.

the amount of shorts and as

On the volume

We continue in the trend of low trading, the volume of sale and purchase of BTC remains at a minimum, on July 20 and 21 the volume increased but in general terms trading continues to decline .

A low volume does not mean that the value has to go down, what it entails is less price sustainability. If a large volume is traded, the number of buyers and sellers and the amount of BTC is greater, which helps the agreed price to be more difficult to move and, on the contrary, when we have a low volume it is easier than movements with more. low capital are able to move the price, both up and down.

News

This week the good news trumps the negative.

  • Bitcoin event held, The B Word
  • Bank of America allows some clients to trade bitcoin futures
  • Tether says an audit will take place in a few months
  • Rumor that Amazon plans to accept Bitcoin payments by the end of the year. 

There is a saying in the stock market of “buy with the rumor, sell with the news”.

The metric of the week, Realized Price

A good indicator to detect downward or stable periods in the medium term is the Realized Price, which is the value of all coins at the price they were purchased divided by the amount of BTC in circulation.

The Market Capitalization is the result of multiplying all the currencies that there are by the value of the BTC today.

So the realized price shows us the average purchase value of the BTCs and the market capitalization tells us how much all of the bitcoins in circulation are worth now.

In the chart of the realized price, the periods where the line is horizontal show the bearish or stable periods and when the line rises it shows the bullish periods.

When the price curve crosses above the realized price, a strongly bearish period begins and when the cross is reversed, that is, the price curve crosses the price curve from below, a bullish period is entered. .

Bitcoin distribution, the Sharks.

The only group that decreases its BTC holdings this week are the Shark, which are the addresses that have between 100 and 1000 BTC, in this group are some of the institutional investors who are waiting to see the price evolution to act part of this The middle class sent some of their BTC to the exchanges (Humpback) to sell, the rest of the groups are stockpiling bitcoin because they expect it to rise in the short medium term.

If we look at the number of addresses of the Shark in the last week it is seen that they have decreased by 21 which corroborates that sale of BTC by some of them.

In general, the Shark have kept their BTC holdings stable in this lateralized period that bitcoin has been having since May 19.  

Analysis of the BTC price during the week of July 19 to 25, 2021. Bitcoin Realized Price Metric

Análisis del precio bitcoin, semana 19-25 de julio 2021. Métrica Precio Realizado

26 July 2021 at 21:50

Esta semana el precio de BTC se inició en los 31500 $ y acabó en los 34600 $, en términos generales es una semana de recuperación en el precio donde llegó a estar en los 29300 dólares y ha acabado en claro ascenso de más de un 8% y con una buena proyección alcista en el corto plazo.

Posiblemente el hecho que más ha influido en el ascenso del precio del bitcoin ha sido el evento The B Word del 21 de julio que ha juntado a Elon Musk CEO de Tesla, SpaceX… a Jack Dorsey CEO de Twitter y Square y a Catherine Wood, CEO de Ark Invest para conversar sobre las curiosidades de Bitcoin. El mercado esperaba las declaraciones que iba a realizar Elon Musk y que en su mayor parte han sido pro Bitcoin e incluso ha reconocido poseer bitcoin además de Ethereum y Dogecoin lo que ha impulsado el precio de BTC al alza. Esto nos demuestra que las opiniones de Elon sobre bitcoin siguen teniendo mucho peso en los inversores principalmente en el corto plazo. 

Se puede ver la charla en el siguiente enlace

Otra noticia alcista no confirmada es el rumor de que Amazon va a permitir pagar con bitcoin a finales de año. 

Una vez más el precio de bitcoin se comporta a la inversa del sentimiento generalizado, llevábamos dos tres semanas con gran parte de los analistas e inversores augurando una gran bajada y en esta semana lo que tenemos es un alza en el precio que todavía no ha encontrado su resistencia por lo que previsiblemente seguirá subiendo.

Una muestra más de este sentimiento negativo es el elevado número de posiciones en corto que se abrían el domingo 25 de julio, es decir que tenemos muchas más personas apostando que bitcoin va a caer de precio que personas que piensan que va a subir. El volumen del short es sorprendente hace tiempo que no se veía algo igual y además con el poco volumen que hay actualmente en el mercado Spot, sea como sea no han acertado y las pérdidas han sido considerables y la mayor parte estaban apalancados. 

En las últimas 24 horas se han liquidado más de 800 millones de dólares de posiciones en corto en el mercado de futuros a más de uno esto le ha hecho mucho daño.

Sobre el volumen

Seguimos en la tendencia de baja negociación, el volumen de venta y compra de BTC sigue en mínimos, los días 20 y 21 de julio el volumen tuvo un aumentó pero en términos generales la negociación sigue a la baja.

Un bajo volumen no supone que el valor tenga que ir a la baja lo que conlleva es una menor sostenibilidad en el precio. Si se negocia un gran volumen el número de compradores y vendedores y la cantidad de BTC es mayor lo que ayuda a que el precio que se acuerde sea más difícil de moverse y por el contrario cuando tenemos un bajo volumen es más sencillo que movimientos con más bajo capital sean capaces de mover el precio, tanto al alza como a la baja.

Noticias

Esta semana las noticias buenas se imponen a las negativas.

  • Se celebra el evento sobre Bitcoin, The B Word
  • Bank of America permite a algunos clientes el trading de futuros de bitcoin
  • Tether dice que se realizará una auditoría en unos meses
  • Rumor de que Amazon planea aceptar pagos con Bitcoin a finales de año. Existe un dicho en el mercado de valores de “compra con el rumor vende con la noticia”

La métrica de la semana, Precio Realizado

Un buen indicador para detectar a medio plazo periodos bajistas o estables es el Precio Realizado, que es el valor de todas las monedas al precio que se compraron dividido por la cantidad de BTC que hay en circulación.

La Capitalización de Mercado es el resultado de multiplicar todas las monedas que hay por el valor de el BTC hoy.

Así que el precio realizado nos muestra el valor promedio de compra de los BTC y la capitalización de mercado nos dice cuánto valen ahora la totalidad de los bitcoin en circulación.

En el gráfico del precio realizado los periodos donde la línea está horizontal muestran los periodos bajistas o estables y cuando la línea sube nos muestra los periodos alcistas.

Cuando la curva del precio cruza por arriba al precio realizado se inicia un período fuertemente bajista (bearish) y cuando el cruce es a la inversa es decir la curva del precio cruza desde abajo a la del precio se entra en un periodo alcista (bullish).

Bitcoin distribución, los Sharks.

El único grupo que disminuye esta semana sus posesiones de BTC son los Shark, que son las direcciones que tienen entre 100 y 1000 BTC, en este colectivo se encuentran algunos de los inversores institucionales que están esperando ver la evolución del precio para actuar parte de esta clase media envió algunos sus BTC a los exchange (Humpback) para vender, el resto de los grupos están haciendo acopio de bitcoin porque esperan que este suba en el corto medio plazo.

Si observamos el número de direcciones de los Shark en la última semana se ve que han disminuido en 21 lo que corrobora esa venta de BTC por parte de algunos de ellos.

En general los Shark han mantenido sus tenencias de BTC estables en este periodo lateralizado que viene teniendo bitcoin desde el 19 de mayo.  

BTC price analysis, week of July 12-18, 2021. Why is BTC still in a bearish zone?

20 July 2021 at 01:05

Another week with the price of bitcoin lateralized to the downside. This stability is strange to us because the price of BTC has us accustomed to great volatility, so this chicha calm worries us.

We started the week with a price of $ 34,400 and ended it with $ 31,600, which represents a drop of 8%. During this week there have been practically no pronounced valleys or large peaks that delight traders and the trading volume has been very low.

This low volume is not good news because it denotes low demand, the price remains within the range but this drop in interest is worrisome.

This week and the next one must be aware of possible sales movements due to the unlocking of shares in GrayScale, this company that holds more than 650,000 BTC does not allow its shareholders to sell the shares for the first 6 months and just this past week and the next the sale is unlocked for many shareholders who bought half a year ago.

Why bitcoin is having a hard time continuing the bullish period

From our point of view there are four issues that are preventing the price from continuing to rise:

  • Regulatory problems of the Binance exchange

Personally, exchanges do not seem the best option to accumulate BTC but the truth is is that it is the priority way to buy and sell BTC for many of the bitcoin holders and all the actions that some countries are having with Binance are sowing many doubts and fear in investors that translate into sales of their bitcoin and disinterest.

  • Doubts about liquidity in Tether

The basis of centralized stablecoins is that each asset (USDT, USDC …) issued has a backing dollar, in the case of Tether these reserves are widely distributed (see the graph) they maintain very little money in cash and a large part in unknown investments, which has generated many doubts among their clients about their solvency.

These uncertainties negatively influence bitcoin and the rest of altcoins, although its operation is independent of stablecoins, it must be taken into account that many users use Tether to buy and sell BTC and altcoins.

  • Low institutional demand

The growth rate of BTC purchases by companies listed on the stock markets has slowed down, many of these companies have bought during the rise and this sharp decline and this long period of lateralization that we have been It has generated doubts and they are waiting to see how the market evolves. It is a matter of time before public institutions return to the market and drive the price up.   

  • Ban on mining in China

China does not want the digital Yuan to have any kind of competition and is in a process of renovating its image and one of its slogans is to convey an image of a green country, which is why it has banned bitcoin mining in some of the areas with the highest production, this has led to the migration of mining nodes and a sharp decline in the hashrate, causing sales of BTC.

Bitcoin distribution

The whales that own between 1,000 and 10,000 BTC sold bitcoin during the bull rally in March and April during the May price drop but as of May 19 they have been buying quietly and increasing their holdings by more of 200,000 BTC these accumulations are not enough to boost the price but they show us that strong hands think with respect to the current situation of bitcoin, that for them the time has come to start buying in a calm way.  

What about inflation

Inflation is on the rise in the USA andmany Bitcoin analysts are surprised because the increase in inflation is not leading to an increase in the price of BTC but this fact is not strange, Bitcoin is a booster against inflation in the medium and long term but not in the short term, its high volatility, its low liquidity, compared to gold, its use as a financial asset means that other factors than inflation have more weight in the price

The positive news

Paraguay votes your Bitcoin law. 

Investor Carl Icahn, a former Bitcoin skeptic, announces that he will make purchases worth 1.5 billion dollars.

Jack Dorsey, founder of Twitter and Square, will create a company aimed at launching a fully Open Source DeFi platform on top of Bitcoin and will be called TBD. 

The future They do

not just paint things well in the short term for the price of bitcoin, the low demand, the low purchase of BTC by public institutions and the negative news do not give the necessary confidence for investors to return to the buys. 

In the medium term and long term it is something else, the fundamentals have not changed, the growth in the use of Lightning Network, the possibility of DeFi reaching Bitcoin and an adoption continues to grow, they show us a very promising future. 

Análisis del precio BTC semana del 12 al 18 de julio del 2021. Por qué sigue BTC en zona bajista.

19 July 2021 at 22:39

Otra semana más con el precio del bitcoin lateralizado a la baja. Esta estabilidad se nos hace extraña porque el precio del BTC nos tiene acostumbrados a una gran volatilidad así que esta calma chicha nos inquieta.

Iniciamos la semana con un precio de 34400 $ y la acabamos con 31600 $ lo que supone una bajada de 8%. Durante esta semana prácticamente no ha habido valles pronunciados ni grandes picos que hagan las delicias de los traders y el volumen de negociación ha sido muy bajo.

Este bajo volumen no es una buena noticia porque denota una baja demanda el precio se mantiene dentro del rango pero esa bajada de interés es preocupante.

Esta semana y la siguiente hay que estar pendiente de posibles movimientos de venta por el desbloqueo de acciones de GrayScale, esta empresa que atesora más de 650000 BTC no permite que sus accionistas vendan las acciones durante los primeros 6 meses y justo esta semana pasada y la siguiente se desbloquea la venta para muchos accionistas que compraron hace medio año.

Por qué le está costando continuar el periodo alcista a bitcoin

Desde nuestro punto de vista hay cuatro temas que están impidiendo que el precio continúe al alza:

  • Los problemas regulatorios del exchange Binance

Personalmente los exchanges no me parece la mejor opción para acumular BTC pero lo cierto es que es la forma prioritaria para comprar y vender BTC para muchos de los tenedores de bitcoin y todas las actuaciones que algunos países están teniendo con Binance están sembrado muchas dudas y miedo en los inversores que se traducen en ventas de sus bitcoin y en desinterés.

  • Dudas de la liquidez en Tether

La base de las stablecoins centralizadas es que cada activo (USDT, USDC…) emitido tiene un dólar de respaldo, en el caso de Tether estas reservas están muy repartidas (ver el gráfico) mantienen muy poco dinero en cash y una gran parte en inversiones desconocidas lo que ha generado muchas dudas entre sus los clientes sobre su solvencia.

Estas incertidumbres influyen negativamente sobre bitcoin y el resto de altcoins aunque su funcionamiento sea independiente de las stablecoins hay que tener en cuenta que muchos usuarios utilizan Tether para comprar y vender BTC y altcoins.

  • Demanda institucional baja

El ritmo de crecimiento de las compras de BTC por parte de las empresas cotizadas en los mercados de valores se ha ralentizado, muchas de estas empresas han comprado durante la subida y el este fuerte retroceso y este largo periodo de lateralización que llevamos le ha generado dudas y están esperando a ver como evoluciona el mercado. Es cuestión de tiempo que las instituciones públicas vuelvan al mercado e impulsen el precio al alza.   

  • Prohibición de la minería en China

China no quiere que el Yuan digital tenga ningún tipo de competencia y está en un proceso de renovación de imagen y una de sus consignas es transmitir una imagen de país verde, por ello ha prohibido la minería de bitcoin en alguna de las zonas de mayor producción, esto ha llevado a la migración de los nodos mineros y a un fuerte descenso del hashrate provocando ventas de BTC.

Bitcoin distribución

Las ballenas que son los propietarios de entre 1000 y 10000 BTC vendieron bitcoin durante el rally alcista del marzo y abril durante la bajada de precio de mayo pero a partir del 19 de mayo han venido comprando de forma tranquila y aumentando sus tenencias en más de 200000 BTC estas acumulaciones no son suficientes para impulsar el precio pero nos muestran que piensan las manos fuertes con respecto a la situación actual del bitcoin, que para ellos ha llegado el momento de empezar a comprar de forma sosegada.  

Qué pasa con la inflación

La inflación está en crecimiento en USA y muchos analistas de Bitcoin están sorprendidos porque el aumento de la inflación no está llevando a un incremento en el precio de BTC pero este hecho no es extraño, Bitcoin es un revulsivo contra la inflación en el medio y en el largo plazo pero no en el corto, su alta volatilidad, su baja liquidez, comparado con el oro, su uso como activo financiero hace que en el precio tengan más peso otros factores que la inflación

Las noticias positivas

Paraguay vota su ley Bitcoin. 

El inversor Carl Icahn un antiguo escéptico de Bitcoin anuncia que va realizar compras por valor de 1.5 mil millones de dólares.

Jack Dorsey, fundador de Twitter y Square, creará una empresa destinada a lanzar una plataforma DeFi sobre Bitcoin totalmente Open Source y se llamará TBD. 

El futuro

No acaban de pintar bien las cosas en el corto plazo para el precio de bitcoin, la baja demanda, la escasa compra de BTC por parte de las instituciones públicas y las noticias negativas no dan la confianza necesaria para que los inversores vuelvan a la compra. 

En el medio plazo y largo plazo es otra cosa, los fundamentos no han cambiado, el crecimiento en el uso de Lightning Network, la posibilidad de que lleguen las DeFi a Bitcoin y una adopción sigue creciendo, nos muestran un futuro muy prometedor. 

Analysis of the price of bitcoin, the week of July 5 to 11, 2021

13 July 2021 at 00:06

We are still within the stability period that began on May 19 and that continues to this day. It seems that bitcoin is not in a hurry to get out of this channel and also the price variations are less and less. Investors are the ones who are impatient for the price to break out of these $ 30,000 to $ 40,000 margins so that there is greater volatility and they can maximize (or minimize) their gains (or losses). 

The week started with a price of $ 35,880 and ended at $ 34,478, which represents a decrease of 3.91% and although in other markets it could be a notable correction for bitcoin, it is not a relevant value.

BTC trading volume this week is very low, which is not good news and this poor move encourages price stabilization. A high trading volume tends to drive the price up or down, but from what it seems institutional investors who had entered strongly in the past are now neither buying nor selling BTC, which does not help the price rise. 

Price stability conforms to existing Greed and Fear sentiment posted at Fear and Greed Index where we move between 29% fear on Monday, July 5, and 20% on Sunday.

The biggest news of the week has a more negative than positive tint. 

  • Breaking news: Binance suspends bank transfers in euros amid regulatory pressure
  • China puts Binance on the list of banned websites in the country
  • Iran’s legal miners are asked stop the machines
  • TikTok will no longer allow cryptocurrency ads
  • The unlocking of some GrayScale actions that will occur this week which generates great uncertainty about how investors will act.

The indicator of the week, Liveliness

Liveliness is a metric that shows changes in savings behavior and indicates the long-term trends of hodlers with respect to the accumulation or spending of BTC.

The formula applied to calculate this indicator is the following:

Bitcoin Liveliness = (ΣCoin Days Destroyed) / (ΣCoin Days Created)

Where Coin Days Destroyed (CDD) indicates the total number of coin-days destroyed. 

Every day that a unit of currency is not spent, a “day of currency” is added. 

When that coin is finally spent, the accumulated coin days are zeroed (destroyed) and the CDD metric is recorded.

What the CDD indicator monitors is the life expectancy of spent bitcoins, a high CDD value means that older BTCs are moving / spending.

What the behavior of the Liveliness metric indicates: 

  • When Liveliness decreases, a high proportion of the BTC supply is idle (Hodl is being done) and that is because the global accumulation of coin-days exceeds the coin-days destroyed in the activity of chain.
  • When Liveliness has a lateral trend, the destroyed coin-days are equal to the accumulated coin-days from the circulating supply.
  • When Liveliness increases, long-term holders are spending old coin-days and they exceed the accrual rate of coin-days.

Glassnode’s Liveliness chart shows us that Liveliness is decreasing which means that we have entered a BTC accumulation zone and that it will be good for the price in the medium term. The low trading volume this past week helps Liveliness to be low.

On the tsypruyan website there is a graph of Liveliness behavior. 

Changes in the UTXO Realized Price Distribution (URPD)

In the graph “Bitcoin UTXO price histogram change, 30d” from @tsypruyan shows bitcoin purchase price ranges compared to 30 days ago.

The blue + pink bars indicate the current UTXO set and the blue + purple bars the situation 30 days ago.

Examining the chart, it is observed that a buy zone is being created, which will represent a price resistance zone around $ 33,000 and that has been fed mainly by UTXO in the $ 38,000 range. The fact that mainly the purple bars are to the right of the pinks assumes that bitcoin users are selling it at a loss as they bought more expensive and are selling cheaper as indicated by the SOPR metric. 

The Puell Multiple metric

We recall that the Puell Multiple indicator that historically has always shown us the good times of purchase is not 100% reliable in the current situation since the drop in the hashrate is produced by the migration of many of the miners from China by government order, it is not a decrease caused because they are entering losses due to a drop in price but because they are being forced to move the machines from China to other countries, such as the USA, Kazakhstan …

Logarithmic adjustments for the price of BTC

There are more logarithmic adjustments to the price of bitcoin than the famous Stock To Flow (S2F) such as the Bitcoin Rainbow Price that is based on making an adjustment of the price of BTC to a logarithmic curve, was initially carried out by Trolololo on October 22, 2014 and exposed it in the forum by Bitcoin Talk and although it was widely criticized for being excessively optimistic, it has been fulfilled like clockwork. Like the S2F there will come a time that will cease to be law but to date the price has followed this exponential trend. 

In the case of Bitcoin Rainbow, the yellow line shows us normality and the orange and red lines that BTC is oversold, which is why it is interesting to sell and the green and blue lines that are overbought and must be accumulated.

In the future

Patience is the mother of science, there is no rush for bitcoin to appreciate, at the moment the price is building at levels close to $ 35,000 and a resistance is forming that in the future can avoid it falls below this level. 

You have to watch the trading volume that this week has been very low, which may mean that bitcoin holders do not want to sell but in general it is not good news because a more lively market means more liquidity, more interest in the currency for part of investors and more chances of sudden rises and falls in the price.

Análisis del precio de bitcoin, semana del 5 al 11 de Julio del 2021

12 July 2021 at 22:51

Seguimos dentro del periodo de estabilidad que comenzó el 20 de mayo y que se mantiene hasta el día de hoy. Parece que bitcoin no tiene prisa por salir de este canal y además las variaciones del precio cada vez son menores. Son los inversores los que se muestran impacientes porque el precio se salga de estos márgenes que oscila entre los 30000 a los 40000 dólares para que exista una mayor volatilidad y puedan maximizar (o minimizar) sus ganancias (o pérdidas). 

La semana empezó con un precio 35880 $ y acabó a 34478 $ lo que supone un retroceso de un 3.91% y aunque en otros mercados pudiera ser una corrección reseñable para bitcoin no es un valor relevante.

El volumen de intercambio de BTC esta semana es muy bajo, lo cual no es una buena noticia y este pobre movimiento fomenta la estabilización del precio. Un volumen de negociación alto suele impulsar el precio al alza o a la baja pero por lo que parece los inversores institucionales que habían entrado con fuerza en el pasado ahora no están ni comprando ni vendiendo BTC lo que no ayuda a que el precio suba. 

La estabilidad en el precio se ajusta al sentimiento que existe de Greed and Fear que se publica en fear and greed index donde nos movemos entre el 29% de miedo del lunes 5 de julio y el 20% del domingo.

Las noticias más importantes de la semana tienen un tinte más negativo que positivo: 

  • Noticia de última hora: Binance suspende las transferencias bancarias en euros en medio de la presión regulatoria.
  • China pone en la lista de las webs prohibidas del país a Binance
  • Piden a los mineros legales de Irán que paren las máquinas
  • TikTok ya no permitirá anuncios de criptomonedas
  • Se acerca el desbloqueo de algunas acciones de GrayScale que se producirá esta semana lo que genera una gran incertidumbre sobre cómo van a actuar los inversores.

El indicador de la semana, Liveliness

Liveliness es una métrica que muestra los cambios de comportamiento en el ahorro e indica las tendencias de los hodlers a largo plazo con respecto a la acumulación o el gasto de BTC.

La fórmula que se aplica para calcular este indicador es la siguiente:

Bitcoin Liveliness = (ΣCoin Days Destroyed) / (ΣCoin Days Created)

Donde Coin Days Destroyed (CDD) indica el número total de monedas-días destruidas. 

Cada día que una unidad de moneda no se gasta, se añade un “día de moneda”. 

Cuando esa moneda finalmente se gasta, los días de monedas acumulados se ponen a cero (se destruyen) y se registra la métrica CDD.

Lo que monitoriza el indicador CDD es la esperanza de vida de los bitcoin gastados, un valor alto de CDD significa que se están moviendo/gastando BTC más antiguos.

Lo que indica el comportamiento de la métrica Liveliness: 

  • Cuando Liveliness disminuye, una alta proporción del suministro de BTC está inactivo (se está haciendo Hodl) y eso es porque la acumulación global de monedas-día supera las monedas-día destruidas en la actividad de la cadena.
  • Cuando Liveliness tiene una tendencia lateral, las monedas-día destruidas son iguales a las monedas-día acumuladas por el suministro circulante.
  • Cuando Liveliness aumenta, los titulares a largo plazo están gastando monedas-día antiguas y estas superan la tasa de acumulación de las monedas-día.

El gráfico de Liveliness de Glassnode nos muestra que el Liveliness está disminuyendo lo que significa que hemos entrado en una zona de acumulación de BTC y que será bueno para el precio a medio plazo. El bajo volumen de negociación que ha habido esta semana pasada ayuda a que el Liveliness tenga un valor bajo.

En la web de tsypruyan hay un gráfico del comportamiento del indicador Liveliness 

Cambios en el UTXO Realized Price Distribution (URPD)

En el gráfico “Bitcoin UTXO price histogram change, 30d” de @tsypruyan se muestran los rangos de precios de compra de bitcoin en comparación con los que había hace 30 días.

Las barras azules + rosas indican el conjunto de UTXO actuales y las barras azules + violetas la situación hace 30 días.

Examinando el gráfico se observa que se está creando una zona de compra, que supondrá una zona de resistencia del precio alrededor de los 33000 $ y que se ha nutrido principalmente de UTXO en el rango de 38000 $. El hecho de que principalmente las barras violetas estén a la derecha de las rosas supone que los usuarios de bitcoin lo están vendiendo en pérdidas ya que compraron más caro y están vendiendo más barato como indica la métrica SOPR. 

La métrica Puell Multiple

Volvemos a recordar que el indicador Puell Multiple que históricamente siempre nos ha mostrado los buenos momentos de compra no es 100% fiable en la situación actual ya que la caída del hashrate está producida por la migración de muchos de los mineros de China por orden gubernamental, no es una disminución provocada porque estén entrando en pérdidas por una bajada del precio sino porque se están viendo obligados a mover las máquinas de China a otros países, como USA, Kazakhstan…

Ajustes logarítmicos para el precio de BTC

Existen más ajustes logarítmicos al precio de bitcoin que el famoso Stock To Flow (S2F) como por ejemplo el Bitcoin Rainbow Price que se basa en realizar un ajuste del precio de BTC a una curva logarítmica, fue realizado inicialmente por Trolololo el 22 de Octubre del 2014 y lo expuso en el foro de Bitcoin Talk y aunque fue muy criticado por ser excesivamente optimista se ha ido cumpliendo como un reloj. Al igual que el S2F llegará un momento que dejará de ser ley pero hasta la fecha el precio ha seguido esta tendencia exponencial. 

En el caso de Bitcoin Rainbow la línea amarilla nos muestra la normalidad y la naranja y la roja que el BTC está sobrevendido por lo cual es interesante vender y la verde y la azul que está sobrecomprado y hay que acumular.

En el futuro

La paciencia es la madre de la ciencia, no hay prisa para que se aprecie el bitcoin, en estos momentos se está construyendo el precio en los niveles cercanos a los 35000 $ y se está formando una resistencia que en el futuro puede evitar que descienda por debajo de este nivel. 

Hay que vigilar el volumen de negociación que esta semana ha sido muy bajo, lo que puede suponer que los poseedores de bitcoin no quieren vender pero en general no es una buena noticia porque un mercado más vivo significa más liquidez, más interés en la moneda por parte de los inversores y más posibilidades de que se produzcan ascensos y descensos bruscos en el precio.

❌