Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix 3043 #3268

Merged
merged 17 commits into from
Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from .glassnode_view import display_active_addresses as active
from .glassnode_view import display_exchange_net_position_change as change
from .glassnode_view import display_exchange_balances as eb
from .glassnode_view import display_btc_rainbow as btcrb
from .glassnode_view import display_hashrate as hr
from .coinglass_view import display_open_interest as oi
from .pycoingecko_view import display_info as info
Expand Down
22 changes: 0 additions & 22 deletions openbb_terminal/cryptocurrency/due_diligence/glassnode_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,25 +570,3 @@ def get_exchange_net_position_change(
console.print(r.text)

return df


@log_start_end(log=logger)
def get_btc_rainbow(
start_date: str = "2010-01-01",
end_date: str = datetime.now().strftime("%Y-%m-%d"),
):
"""Get bitcoin price data
[Price data from source: https://glassnode.com]
[Inspired by: https://blockchaincenter.net]

Parameters
----------
start_date : str
Initial date, format YYYY-MM-DD
end_date : str
Final date, format YYYY-MM-DD
"""

df_data = get_close_price("BTC", start_date, end_date)

return df_data
126 changes: 0 additions & 126 deletions openbb_terminal/cryptocurrency/due_diligence/glassnode_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
from datetime import datetime, timedelta
from typing import List, Optional

import matplotlib
import numpy as np
import pandas as pd
from matplotlib import dates as mdates
from matplotlib import pyplot as plt
from matplotlib import ticker
from matplotlib.lines import Line2D
Expand All @@ -16,7 +13,6 @@
from openbb_terminal import config_plot as cfgPlot
from openbb_terminal.cryptocurrency.due_diligence.glassnode_model import (
get_active_addresses,
get_btc_rainbow,
get_exchange_balances,
get_exchange_net_position_change,
get_hashrate,
Expand All @@ -32,128 +28,6 @@
logger = logging.getLogger(__name__)


@log_start_end(log=logger)
@check_api_key(["API_GLASSNODE_KEY"])
def display_btc_rainbow(
start_date: str = "2010-01-01",
end_date: str = datetime.now().strftime("%Y-%m-%d"),
export: str = "",
external_axes: Optional[List[plt.Axes]] = None,
):
"""Displays bitcoin rainbow chart
[Price data from source: https://glassnode.com]
[Inspired by: https://blockchaincenter.net]

Parameters
----------
start_date : int
Initial date, format YYYY-MM-DD
end_date : int
Final date, format YYYY-MM-DD
export : str
Export dataframe data to csv,json,xlsx file
external_axes : Optional[List[plt.Axes]], optional
External axes (1 axis is expected in the list), by default None
"""

df_data = get_btc_rainbow(start_date, end_date)

if df_data.empty:
return

# This plot has 1 axis
if not external_axes:
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfgPlot.PLOT_DPI)
elif is_valid_axes_count(external_axes, 1):
(ax,) = external_axes
else:
return

d0 = datetime.strptime("2012-01-01", "%Y-%m-%d")
dend = datetime.strptime(end_date, "%Y-%m-%d")

x = range((df_data.index[0] - d0).days, (dend - d0).days + 1)

y0 = [10 ** ((2.90 * ln_x) - 19.463) for ln_x in [np.log(val + 1400) for val in x]]
y1 = [10 ** ((2.886 * ln_x) - 19.463) for ln_x in [np.log(val + 1375) for val in x]]
y2 = [10 ** ((2.872 * ln_x) - 19.463) for ln_x in [np.log(val + 1350) for val in x]]
y3 = [10 ** ((2.859 * ln_x) - 19.463) for ln_x in [np.log(val + 1320) for val in x]]
y4 = [
10 ** ((2.8445 * ln_x) - 19.463) for ln_x in [np.log(val + 1293) for val in x]
]
y5 = [
10 ** ((2.8295 * ln_x) - 19.463) for ln_x in [np.log(val + 1275) for val in x]
]
y6 = [10 ** ((2.815 * ln_x) - 19.463) for ln_x in [np.log(val + 1250) for val in x]]
y7 = [10 ** ((2.801 * ln_x) - 19.463) for ln_x in [np.log(val + 1225) for val in x]]
y8 = [10 ** ((2.788 * ln_x) - 19.463) for ln_x in [np.log(val + 1200) for val in x]]

x_dates = pd.date_range(df_data.index[0], dend, freq="d")

ax.fill_between(x_dates, y0, y1, color="red", alpha=0.7)
ax.fill_between(x_dates, y1, y2, color="orange", alpha=0.7)
ax.fill_between(x_dates, y2, y3, color="yellow", alpha=0.7)
ax.fill_between(x_dates, y3, y4, color="green", alpha=0.7)
ax.fill_between(x_dates, y4, y5, color="blue", alpha=0.7)
ax.fill_between(x_dates, y5, y6, color="violet", alpha=0.7)
ax.fill_between(x_dates, y6, y7, color="indigo", alpha=0.7)
ax.fill_between(x_dates, y7, y8, color="purple", alpha=0.7)

ax.semilogy(df_data.index, df_data["v"].values)
ax.set_xlim(df_data.index[0], dend)
ax.set_title("Bitcoin Rainbow Chart")
ax.set_ylabel("Price ($)")

ax.legend(
[
"Bubble bursting imminent!!",
"SELL!",
"Everyone FOMO'ing....",
"Is this a bubble??",
"Still cheap",
"Accumulate",
"BUY!",
"Basically a Fire Sale",
"Bitcoin Price",
],
prop={"size": 8},
)

sample_dates = np.array(
[
datetime(2012, 11, 28),
datetime(2016, 7, 9),
datetime(2020, 5, 11),
datetime(2024, 4, 4),
]
)
sample_dates = mdates.date2num(sample_dates)
ax.vlines(x=sample_dates, ymin=0, ymax=max(y0), color="grey")
for i, x in enumerate(sample_dates):
if mdates.date2num(d0) < x < mdates.date2num(dend):
ax.text(x, 1, f"Halving {i+1}", rotation=-90, verticalalignment="center")

ax.minorticks_off()
ax.yaxis.set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, _: int(x) if x >= 1 else x)
)
ax.yaxis.set_major_locator(
matplotlib.ticker.LogLocator(base=100, subs=[1.0, 2.0, 5.0, 10.0])
)

theme.style_primary_axis(ax)

if not external_axes:
theme.visualize_output()

export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"rainbox",
df_data,
)


@log_start_end(log=logger)
@check_api_key(["API_GLASSNODE_KEY"])
def display_active_addresses(
Expand Down
35 changes: 35 additions & 0 deletions openbb_terminal/cryptocurrency/overview/glassnode_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from datetime import datetime
import logging

from openbb_terminal.decorators import log_start_end

from openbb_terminal.cryptocurrency.due_diligence.glassnode_model import get_close_price

# pylint: disable=unsupported-assignment-operation

logger = logging.getLogger(__name__)
# pylint: disable=unsupported-assignment-operation

api_url = "https://api.glassnode.com/v1/metrics/"


@log_start_end(log=logger)
def get_btc_rainbow(
start_date: str = "2010-01-01",
end_date: str = datetime.now().strftime("%Y-%m-%d"),
):
"""Get bitcoin price data
[Price data from source: https://glassnode.com]
[Inspired by: https://blockchaincenter.net]

Parameters
----------
start_date : str
Initial date, format YYYY-MM-DD
end_date : str
Final date, format YYYY-MM-DD
"""

df_data = get_close_price("BTC", start_date, end_date)

return df_data
147 changes: 147 additions & 0 deletions openbb_terminal/cryptocurrency/overview/glassnode_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import logging
import os
from datetime import datetime
from typing import List, Optional

import matplotlib
import numpy as np
import pandas as pd
from matplotlib import dates as mdates
from matplotlib import pyplot as plt

from openbb_terminal.config_terminal import theme
from openbb_terminal.decorators import check_api_key
from openbb_terminal import config_plot as cfgPlot
from openbb_terminal.cryptocurrency.overview.glassnode_model import (
get_btc_rainbow,
)
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import (
export_data,
plot_autoscale,
is_valid_axes_count,
)

logger = logging.getLogger(__name__)


@log_start_end(log=logger)
@check_api_key(["API_GLASSNODE_KEY"])
def display_btc_rainbow(
start_date: str = "2010-01-01",
end_date: str = datetime.now().strftime("%Y-%m-%d"),
export: str = "",
external_axes: Optional[List[plt.Axes]] = None,
):
"""Displays bitcoin rainbow chart
[Price data from source: https://glassnode.com]
[Inspired by: https://blockchaincenter.net]

Parameters
----------
start_date : int
Initial date, format YYYY-MM-DD
end_date : int
Final date, format YYYY-MM-DD
export : str
Export dataframe data to csv,json,xlsx file
external_axes : Optional[List[plt.Axes]], optional
External axes (1 axis is expected in the list), by default None
"""

df_data = get_btc_rainbow(start_date, end_date)

if df_data.empty:
return

# This plot has 1 axis
if not external_axes:
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfgPlot.PLOT_DPI)
elif is_valid_axes_count(external_axes, 1):
(ax,) = external_axes
else:
return

d0 = datetime.strptime("2012-01-01", "%Y-%m-%d")
dend = datetime.strptime(end_date, "%Y-%m-%d")

x = range((df_data.index[0] - d0).days, (dend - d0).days + 1)

y0 = [10 ** ((2.90 * ln_x) - 19.463) for ln_x in [np.log(val + 1400) for val in x]]
y1 = [10 ** ((2.886 * ln_x) - 19.463) for ln_x in [np.log(val + 1375) for val in x]]
y2 = [10 ** ((2.872 * ln_x) - 19.463) for ln_x in [np.log(val + 1350) for val in x]]
y3 = [10 ** ((2.859 * ln_x) - 19.463) for ln_x in [np.log(val + 1320) for val in x]]
y4 = [
10 ** ((2.8445 * ln_x) - 19.463) for ln_x in [np.log(val + 1293) for val in x]
]
y5 = [
10 ** ((2.8295 * ln_x) - 19.463) for ln_x in [np.log(val + 1275) for val in x]
]
y6 = [10 ** ((2.815 * ln_x) - 19.463) for ln_x in [np.log(val + 1250) for val in x]]
y7 = [10 ** ((2.801 * ln_x) - 19.463) for ln_x in [np.log(val + 1225) for val in x]]
y8 = [10 ** ((2.788 * ln_x) - 19.463) for ln_x in [np.log(val + 1200) for val in x]]

x_dates = pd.date_range(df_data.index[0], dend, freq="d")

ax.fill_between(x_dates, y0, y1, color="red", alpha=0.7)
ax.fill_between(x_dates, y1, y2, color="orange", alpha=0.7)
ax.fill_between(x_dates, y2, y3, color="yellow", alpha=0.7)
ax.fill_between(x_dates, y3, y4, color="green", alpha=0.7)
ax.fill_between(x_dates, y4, y5, color="blue", alpha=0.7)
ax.fill_between(x_dates, y5, y6, color="violet", alpha=0.7)
ax.fill_between(x_dates, y6, y7, color="indigo", alpha=0.7)
ax.fill_between(x_dates, y7, y8, color="purple", alpha=0.7)

ax.semilogy(df_data.index, df_data["v"].values)
ax.set_xlim(df_data.index[0], dend)
ax.set_title("Bitcoin Rainbow Chart")
ax.set_ylabel("Price [USD]")

ax.legend(
[
"Bubble bursting imminent!!",
"SELL!",
"Everyone FOMO'ing....",
"Is this a bubble??",
"Still cheap",
"Accumulate",
"BUY!",
"Basically a Fire Sale",
"Bitcoin Price",
],
prop={"size": 8},
)

sample_dates = np.array(
[
datetime(2012, 11, 28),
datetime(2016, 7, 9),
datetime(2020, 5, 11),
datetime(2024, 4, 4),
]
)
sample_dates = mdates.date2num(sample_dates)
ax.vlines(x=sample_dates, ymin=0, ymax=max(y0), color="grey")
for i, x in enumerate(sample_dates):
if mdates.date2num(d0) < x < mdates.date2num(dend):
ax.text(x, 1, f"Halving {i+1}", rotation=-90, verticalalignment="center")

ax.minorticks_off()
ax.yaxis.set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, _: int(x) if x >= 1 else x)
)
ax.yaxis.set_major_locator(
matplotlib.ticker.LogLocator(base=100, subs=[1.0, 2.0, 5.0, 10.0])
)

theme.style_primary_axis(ax)

if not external_axes:
theme.visualize_output()

export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"btcrb",
df_data,
)
2 changes: 1 addition & 1 deletion openbb_terminal/cryptocurrency/overview/overview_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from .coinbase_view import display_trading_pairs as cbpairs
from .cryptopanic_view import display_news as news
from .tokenterminal_view import display_fundamental_metrics as fun

from .glassnode_view import display_btc_rainbow as btcrb

# Models
models = _models(os.path.abspath(os.path.dirname(__file__)))
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from openbb_terminal.custom_prompt_toolkit import NestedCompleter

from openbb_terminal import feature_flags as obbff
from openbb_terminal.cryptocurrency.due_diligence.glassnode_view import (
from openbb_terminal.cryptocurrency.overview.glassnode_view import (
display_btc_rainbow,
)
from openbb_terminal.cryptocurrency.overview import (
Expand Down
Loading