Full Code of Zaczero/CBBI for AI

main efd6dcf08b9b cached
26 files
89.5 KB
23.0k tokens
63 symbols
1 requests
Download .txt
Repository: Zaczero/CBBI
Branch: main
Commit: efd6dcf08b9b
Files: 26
Total size: 89.5 KB

Directory structure:
gitextract_j3fsxwr5/

├── .envrc
├── .gitattributes
├── .gitignore
├── .vscode/
│   └── launch.json
├── LICENSE
├── README.md
├── api/
│   ├── cbbiinfo_api.py
│   ├── coinmetrics_api.py
│   └── coinsoto_api.py
├── asciinema/
│   └── thumbnail.xcf
├── fetch_bitcoin_data.py
├── main.py
├── metrics/
│   ├── _common.py
│   ├── base_metric.py
│   ├── mvrv_z_score.py
│   ├── pi_cycle.py
│   ├── puell_multiple.py
│   ├── reserve_risk.py
│   ├── rhodl_ratio.py
│   ├── rupl.py
│   ├── trolololo.py
│   ├── two_year_moving_average.py
│   └── woobull_topcap_cvdd.py
├── pyproject.toml
├── shell.nix
└── utils.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .envrc
================================================
# shellcheck disable=SC2148

use nix


================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto


================================================
FILE: .gitignore
================================================
# Created by https://www.toptal.com/developers/gitignore/api/dotenv,python,pycharm,visualstudiocode,direnv
# Edit at https://www.toptal.com/developers/gitignore?templates=dotenv,python,pycharm,visualstudiocode,direnv

### direnv ###
.direnv

### dotenv ###
.env

### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# SonarLint plugin
.idea/sonarlint/

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

### PyCharm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr

# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/

# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml

# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/

# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$

# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml

# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
#   For a library or package, you might want to ignore these files since the code is
#   intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# poetry
#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
#   This is especially recommended for binary packages to ensure reproducibility, and is more
#   commonly ignored for libraries.
#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
#   in version control.
#   https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can
#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
#  and can be added to the global gitignore or merged into this file.  For a more nuclear
#  option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml

# ruff
.ruff_cache/

# LSP config files
pyrightconfig.json

### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets

# Local History for Visual Studio Code
.history/

# Built Visual Studio Code Extensions
*.vsix

### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide

# End of https://www.toptal.com/developers/gitignore/api/dotenv,python,pycharm,visualstudiocode,direnv

# filecache
*.cache.*
*.cache

# application specific
output
*.ignore


================================================
FILE: .vscode/launch.json
================================================
{
    "configurations": [
        {
            "console": "integratedTerminal",
            "name": "Python Debugger: Current File",
            "program": "${file}",
            "request": "launch",
            "type": "debugpy"
        },
        {
            "console": "integratedTerminal",
            "justMyCode": true,
            "name": "Python: main.py",
            "program": "${workspaceFolder}/main.py",
            "request": "launch",
            "type": "debugpy"
        }
    ],
    "version": "0.2.0"
}


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# ColinTalksCrypto Bitcoin Bull Run Index (CBBI)

![Python version](https://shields.monicz.dev/badge/python-v3.13-blue)
[![GitHub Repo stars](https://shields.monicz.dev/github/stars/Zaczero/CBBI?style=social)](https://github.com/Zaczero/CBBI)

The official Python implementation of the **ColinTalksCrypto Bitcoin Bull Run Index** (CBBI).

The CBBI is a Bitcoin index that utilizes advanced, real-time analysis of 9 metrics
to help us understand what stage of the Bitcoin bull run and bear market cycles we are in.
The CBBI is time-independent and price-independent.
It simply indicates whether it believes we are approaching the top/bottom of a Bitcoin cycle.

If you want to learn more, [check out this video](https://www.youtube.com/watch?v=bq7djf1n0j4).

## Visit our website

Bookmark it and receive latest CBBI updates.

- [CBBI.info](https://cbbi.info/)

## Script Demo

[![asciicast](https://raw.githubusercontent.com/Zaczero/CBBI/main/asciinema/thumbnail.webp)](https://asciinema.org/a/KFkbKPULf9PGvY8Fmh4QLn0FE)

## Docker Usage

To use the CBBI script with Docker, run the following command:

```sh
docker run --rm --pull=always zaczero/cbbi --help
docker run --rm --pull=always zaczero/cbbi
```

## Manual Usage

To use the CBBI script without Docker, follow these two simple steps:

### 1. Install nix

Before you jump in, make sure to install the [❄️ Nix](https://nixos.org/download) package manager. It's your shortcut to seamless dependency management and reproducible environment setup. It will save you lots of time and spare you from unnecessary stress.

### 2. Run the application

```sh
nix-shell --run "python main.py --help"
```

#### or with using interactive shell

```sh
nix-shell
python main.py --help
```

## Metrics

The current CBBI version _(November 2022)_ includes the following metrics:

| Name                         | Link                                                                  |
| ---------------------------- | --------------------------------------------------------------------- |
| Pi Cycle Top Indicator       | [Visit page](https://coinank.com/indexdata/piCycleTop)               |
| RUPL/NUPL Chart              | [Visit page](https://coinank.com/indexdata/realizedProf)             |
| RHODL Ratio                  | [Visit page](https://coinank.com/indexdata/rhodlRatio)               |
| Puell Multiple               | [Visit page](https://coinank.com/indexdata/puellMultiple)            |
| 2 Year Moving Average        | [Visit page](https://coinank.com/indexdata/year2MA)                  |
| Bitcoin Trolololo Trend Line | [Visit page](https://www.blockchaincenter.net/bitcoin-rainbow-chart/) |
| MVRV Z-Score                 | [Visit page](https://coinank.com/indexdata/score)                    |
| Reserve Risk                 | [Visit page](https://coinank.com/indexdata/reserveRisk)              |
| Woobull Top Cap vs CVDD      | [Visit page](https://woocharts.com/bitcoin-price-models/)             |

## Environment Variables

This project supports `.env` files, which provide a convenient way of setting environment variables.

To use this feature, create a file called `.env` in the project's root directory,
and add environment variables in the following format:

```sh
VARIABLE_NAME=value
```

### TELEGRAM_TOKEN, TELEGRAM_CHAT_ID

Define both variables to receive Telegram notifications about metric errors that occur during the execution.

#### Example usage

- TELEGRAM_TOKEN=REPLACE_ME
- TELEGRAM_CHAT_ID=123456

## Footer

### Contact me

<https://monicz.dev/#get-in-touch>

### License

This project is licensed under the GNU Affero General Public License v3.0.

The complete license text can be accessed in the repository at [LICENSE](https://github.com/Zaczero/CBBI/blob/main/LICENSE).


================================================
FILE: api/cbbiinfo_api.py
================================================
import polars as pl

from utils import HTTP


def cbbi_fetch(key: str):
    response = HTTP.get('https://colintalkscrypto.com/cbbi/data/latest.json')
    response.raise_for_status()
    response_data = response.json()[key]

    return (
        pl
        .DataFrame({
            'Date': pl.Series([int(k) for k in response_data], dtype=pl.Int64),
            'Value': pl.Series(list(response_data.values()), dtype=pl.Float64),
        })
        .with_columns(
            Date=(
                pl
                .from_epoch(pl.col('Date'), time_unit='s')
                .dt.cast_time_unit('us')
                .dt.replace_time_zone('UTC')
            ),
        )
        .select('Date', 'Value')
    )


================================================
FILE: api/coinmetrics_api.py
================================================
import polars as pl

from utils import HTTP


def cm_fetch_asset_metrics(
    *,
    asset: str,
    metrics: list[str],
    frequency: str = '1d',
    start_time: str,
    page_size: int = 10_000,
    null_as_zero: bool = False,
):
    """
    Fetch Coin Metrics Community time series asset metrics.

    Notes:
    - Coin Metrics returns numbers as strings. This helper casts metric columns to numeric.
    """
    response = HTTP.get(
        'https://community-api.coinmetrics.io/v4/timeseries/asset-metrics',
        params={
            'assets': asset,
            'metrics': ','.join(metrics),
            'frequency': frequency,
            'start_time': start_time,
            'paging_from': 'start',
            'page_size': page_size,
            'sort': 'time',
            'null_as_zero': str(null_as_zero).lower(),
        },
    )
    response.raise_for_status()
    response_json = response.json()
    data = response_json['data']

    while response_json.get('next_page_url'):
        response = HTTP.get(response_json['next_page_url'])
        response.raise_for_status()
        response_json = response.json()
        data.extend(response_json['data'])

    return (
        pl
        .from_dicts(data, infer_schema_length=None)
        .with_columns(
            *[pl.col(col).cast(pl.Float64) for col in metrics if col in data[0]],
            Date=pl.col('time').str.to_datetime(time_zone='UTC').dt.truncate('1d'),
        )
        .drop('time')
    )


================================================
FILE: api/coinsoto_api.py
================================================
import polars as pl

from utils import HTTP


def cs_fetch(path: str, data_selector: str, col_name: str):
    response = HTTP.get(f'https://api.coinank.com/indicatorapi/{path}')
    response.raise_for_status()
    data = response.json()['data']

    if 'timeList' not in data and 'line' in data:
        data = data['line']

    data_x = data['timeList']
    data_y = data[data_selector]

    return (
        pl
        .DataFrame({
            'Date': data_x[: len(data_y)],
            col_name: data_y,
        })
        .with_columns(
            Date=(
                pl
                .from_epoch(pl.col('Date'), time_unit='ms')
                .dt.cast_time_unit('us')
                .dt.replace_time_zone('UTC')
            )
        )
        .select('Date', col_name)
    )


================================================
FILE: fetch_bitcoin_data.py
================================================
import polars as pl

from api.coinmetrics_api import cm_fetch_asset_metrics
from utils import mark_days_since, mark_highs_lows


def fetch_coinmetrics_data():
    """
    Fetch historical Bitcoin blockchain data from Coin Metrics Community API.
    """
    df_cm = cm_fetch_asset_metrics(
        asset='btc',
        metrics=['BlkCnt', 'IssTotNtv', 'IssTotUSD', 'PriceUSD'],
        start_time='2009-01-03',
    )

    df = df_cm.select(
        Date=pl.col('Date'),
        TotalBlocks=pl.col('BlkCnt'),
        IssTotNtv=pl.col('IssTotNtv'),
        IssTotUSD=pl.col('IssTotUSD'),
        Price=pl.col('PriceUSD'),
    )

    avg_subsidy = (
        pl
        .when(pl.col('TotalBlocks') > 0)
        .then(pl.col('IssTotNtv') / pl.col('TotalBlocks'))
        .otherwise(None)
    )
    subsidy_floor = pl.lit(50.0) / (
        pl.lit(2.0) ** (pl.lit(50.0) / avg_subsidy).log(base=2).ceil()
    )

    df = df.with_columns(
        Halving=(
            subsidy_floor.is_not_null()
            & subsidy_floor.shift(1).is_not_null()
            & (subsidy_floor != subsidy_floor.shift(1))
        )
    )

    return df.select(
        'Date',
        'IssTotUSD',
        'Price',
        'Halving',
    )


def fetch_bitcoin_data():
    """
    Fetches historical Bitcoin data into a DataFrame.
    Very early data is discarded due to high volatility.
    """
    print('📈 Requesting historical Bitcoin data…')

    df = fetch_coinmetrics_data()

    df = df.with_columns(
        PuellMultiple=(
            pl.col('IssTotUSD')
            / pl.col('IssTotUSD').rolling_mean(window_size=365, min_samples=365)
        ),
        Price730DMA=pl.col('Price').rolling_mean(window_size=730, min_samples=1),
    )

    df = df.filter(pl.col('Date') >= pl.datetime(2011, 6, 27, time_zone='UTC'))
    df = df.with_columns(
        PriceLog=pl.col('Price').log(),
    )

    df = mark_highs_lows(df, 'Price', False, 365 * 2, 180)

    # move 2021' peak to the first price peak
    df = df.with_columns(
        PriceHigh=(
            pl
            .when(pl.col('Date') == pl.datetime(2021, 11, 8, time_zone='UTC'))
            .then(False)
            .when(pl.col('Date') == pl.datetime(2021, 4, 14, time_zone='UTC'))
            .then(True)
            .otherwise(pl.col('PriceHigh'))
        )
    )

    return mark_days_since(df, ['PriceLow', 'Halving'])


================================================
FILE: main.py
================================================
import asyncio
import math
import time
import traceback
from pathlib import Path

import fire
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib import pyplot as plt
from pyfiglet import figlet_format
from sty import bg, ef, fg, rs
from tqdm import tqdm

from fetch_bitcoin_data import fetch_bitcoin_data
from metrics.mvrv_z_score import MVRVMetric
from metrics.pi_cycle import PiCycleMetric
from metrics.puell_multiple import PuellMetric
from metrics.reserve_risk import ReserveRiskMetric
from metrics.rhodl_ratio import RHODLMetric
from metrics.rupl import RUPLMetric
from metrics.trolololo import TrolololoMetric
from metrics.two_year_moving_average import TwoYearMovingAverageMetric
from metrics.woobull_topcap_cvdd import WoobullMetric
from utils import format_percentage, get_color


def get_metrics():
    """
    Returns a list of available metrics to be calculated.
    """
    return [
        PiCycleMetric(),
        RUPLMetric(),
        RHODLMetric(),
        PuellMetric(),
        TwoYearMovingAverageMetric(),
        TrolololoMetric(),
        MVRVMetric(),
        ReserveRiskMetric(),
        WoobullMetric(),
    ]


def _json_number(value: float | None, *, precision: int = 4):
    if value is None or (isinstance(value, float) and math.isnan(value)):
        return 'null'

    s = f'{value:.{precision}f}'.rstrip('0')
    if s.endswith('.'):
        s += '0'
    return s


def _write_columns_orient_json(df: pl.DataFrame, path: Path, *, precision: int = 4):
    ts = df.get_column('Date').dt.epoch(time_unit='s').to_list()
    cols = [c for c in df.columns if c != 'Date']

    with path.open('w', encoding='utf-8') as f:
        f.write('{\n')
        for col_i, col in enumerate(cols):
            f.write(f'  "{col}":{{\n')
            values = df.get_column(col).to_list()
            for row_i, (t, v) in enumerate(zip(ts, values, strict=True)):
                comma = ',' if row_i < len(ts) - 1 else ''
                f.write(f'    "{t}":{_json_number(v, precision=precision)}{comma}\n')
            col_comma = ',' if col_i < len(cols) - 1 else ''
            f.write(f'  }}{col_comma}\n')
        f.write('}')


def _add_common_markers(
    ax, *, halvings: np.ndarray, highs: np.ndarray, lows: np.ndarray
):
    for dt in halvings:
        ax.axvline(x=dt, color='navy', linestyle=':', linewidth=0.5)
    for dt in highs:
        ax.axvline(x=dt, color='green', linestyle=':', linewidth=0.5)
    for dt in lows:
        ax.axvline(x=dt, color='red', linestyle=':', linewidth=0.5)


def _shade_metric_bounds(ax):
    ax.axhline(y=1, color='black', linewidth=0.5)
    ax.axhline(y=0, color='black', linewidth=0.5)

    y_min, y_max = ax.get_ylim()
    ax.fill_betweenx(
        y=[1, y_max],
        x1=0,
        x2=1,
        transform=ax.get_yaxis_transform(),
        color='black',
        alpha=0.1,
        edgecolor='none',
        zorder=0,
    )
    ax.fill_betweenx(
        y=[y_min, 0],
        x1=0,
        x2=1,
        transform=ax.get_yaxis_transform(),
        color='black',
        alpha=0.1,
        edgecolor='none',
        zorder=0,
    )


async def run(json_file: str, charts_file: str, output_dir: str | None):
    output_dir_path = Path.cwd() if output_dir is None else Path(output_dir)

    json_file_path = output_dir_path / Path(json_file)
    charts_file_path = output_dir_path / Path(charts_file)

    output_dir_path.mkdir(mode=0o755, parents=True, exist_ok=True)

    df_bitcoin = fetch_bitcoin_data()

    current_price = df_bitcoin.get_column('Price')[-1]
    print(
        'Current Bitcoin price: '
        + ef.b
        + fg.li_green
        + bg.da_green
        + f' $ {round(current_price):,} '
        + rs.all
    )

    metrics = get_metrics()
    metrics_cols = []
    metrics_descriptions = []

    sns.set_theme(
        font_scale=0.225,
        rc={
            'figure.titlesize': 12,
            'axes.titlesize': 7.5,
            'axes.labelsize': 6,
            'xtick.labelsize': 4,
            'ytick.labelsize': 4,
            'lines.linewidth': 0.5,
            'grid.linewidth': 0.3,
            'savefig.dpi': 1000,
            'figure.dpi': 300,
        },
    )

    x = df_bitcoin.get_column('Date').to_numpy()
    price_log = df_bitcoin.get_column('PriceLog').to_numpy()
    price = (price_log - price_log.min()) / (price_log.max() - price_log.min())

    halvings = x[df_bitcoin.get_column('Halving').to_numpy()]
    highs = x[df_bitcoin.get_column('PriceHigh').to_numpy()]
    lows = x[df_bitcoin.get_column('PriceLow').to_numpy()]

    axes_per_metric = 2
    fig, axes = plt.subplots(
        len(metrics), axes_per_metric, figsize=(4 * axes_per_metric, 3 * len(metrics))
    )
    axes = axes.reshape(-1, axes_per_metric)

    plt.tight_layout(pad=10)
    plt.subplots_adjust(top=0.98)
    plt.suptitle(
        'CBBI metric data input → output', fontsize=11.25, weight='bold', y=0.99508
    )

    for metric, ax_row in zip(metrics, axes, strict=True):
        ax_out = ax_row[1]
        ax_in = ax_row[0]

        sns.lineplot(x=x, y=price, alpha=0.4, color='orange', ax=ax_out)

        values = await metric.calculate(df_bitcoin, [ax_out, ax_in])

        _add_common_markers(ax_out, halvings=halvings, highs=highs, lows=lows)
        _add_common_markers(ax_in, halvings=halvings, highs=highs, lows=lows)

        _shade_metric_bounds(ax_out)

        ax_in.annotate(
            '',
            xy=(1.0967, 0.75),
            xycoords='axes fraction',
            xytext=(1.0367, 0.75),
            textcoords='axes fraction',
            arrowprops={
                'arrowstyle': '->',
                'color': 'darkgray',
                'lw': 1.5,
                'shrinkA': 0,
                'shrinkB': 0,
                'mutation_scale': 10,
            },
            ha='center',
            va='center',
        )

        values = values.clip(0, 1).rename(metric.name)
        df_bitcoin = df_bitcoin.with_columns(values)
        metrics_cols.append(metric.name)
        metrics_descriptions.append(metric.description)

    df_result = df_bitcoin.select('Date', 'Price', *metrics_cols).with_columns(
        Confidence=pl.mean_horizontal([pl.col(c).fill_nan(None) for c in metrics_cols])
    )

    print('Generating charts…')
    plt.savefig(charts_file_path)
    plt.close(fig)

    _write_columns_orient_json(df_result, json_file_path, precision=4)

    last = df_result.tail(1).row(0, named=True)
    confidence_details = {
        desc: last[name]
        for name, desc in zip(metrics_cols, metrics_descriptions, strict=True)
    }

    print('\n' + ef.b + ':: Confidence we are at the peak ::' + rs.all)
    print(
        fg.cyan
        + ef.bold
        + figlet_format(format_percentage(last['Confidence'], ''), font='univers')
        + rs.all,
        end='',
    )

    for description, value in confidence_details.items():
        if value is not None and not (isinstance(value, float) and np.isnan(value)):
            print(
                fg.white + get_color(value) + f'{format_percentage(value)} ' + rs.all,
                end='',
            )
            print(f' - {description}')

    print()
    print(
        'Source code: ' + ef.u + fg.li_blue + 'https://github.com/Zaczero/CBBI' + rs.all
    )
    print('License: ' + ef.b + 'AGPL-3.0' + rs.all)
    print()


def run_and_retry(
    json_file: str = 'latest.json',
    charts_file: str = 'charts.svg',
    output_dir: str | None = 'output',
    max_attempts: int = 3,
    sleep_seconds_on_error: int = 60,
):
    """
    Calculates the current CBBI confidence value alongside all the required metrics.
    Everything gets pretty printed to the current standard output and a clean copy
    is saved to a JSON file specified by the path in the ``json_file`` argument.
    A charts image is generated on the path specified by the ``charts_file`` argument
    which summarizes all individual metrics' historical data in a visual way.
    The execution is attempted multiple times in case an error occurs.

    Args:
        json_file: File path where the output is saved in the JSON format.
        charts_file: File path where the charts are saved (format inferred from file extension).
        output_dir: Directory path where the output is stored.
            If set to ``None`` then use the current working directory.
            If the directory does not exist, it will be created.
        max_attempts: Maximum number of attempts before termination. An attempt is counted when an error occurs.
        sleep_seconds_on_error: Duration of the sleep in seconds before attempting again after an error occurs.
    """
    assert max_attempts > 0, 'Value of the max_attempts argument must be positive'
    assert sleep_seconds_on_error >= 0, (
        'Value of the sleep_seconds_on_error argument must be non-negative'
    )

    for _ in range(max_attempts):
        try:
            asyncio.run(run(json_file, charts_file, output_dir))
            exit(0)

        except Exception:
            print(fg.black + bg.yellow + ' An error has occurred! ' + rs.all)
            traceback.print_exc()

            print(f'\nRetrying in {sleep_seconds_on_error} seconds…', flush=True)
            for _ in tqdm(range(sleep_seconds_on_error)):
                time.sleep(1)

    print(f'Max attempts limit has been reached ({max_attempts}).')
    print('Better luck next time!')
    exit(-1)


if __name__ == '__main__':
    fire.Fire(run_and_retry)


================================================
FILE: metrics/_common.py
================================================
import numpy as np
import polars as pl


def join_left_on_date(df: pl.DataFrame, other: pl.DataFrame):
    return df.join(other, on='Date', how='left', maintain_order='left')


def linreg_predict(
    x_train: np.ndarray, y_train: np.ndarray, x_all: np.ndarray
) -> np.ndarray:
    x_train = x_train.astype(np.float64)
    y_train = y_train.astype(np.float64)

    x_mean = x_train.mean()
    y_mean = y_train.mean()

    x_centered = x_train - x_mean
    slope = (x_centered * (y_train - y_mean)).sum() / (x_centered * x_centered).sum()
    intercept = y_mean - slope * x_mean

    return intercept + slope * x_all.astype(np.float64)


================================================
FILE: metrics/base_metric.py
================================================
import traceback
from abc import ABC, abstractmethod

import polars as pl
from matplotlib.axes import Axes
from sty import bg, fg, rs

from api.cbbiinfo_api import cbbi_fetch
from utils import send_error_notification


class BaseMetric(ABC):
    @property
    @abstractmethod
    def name(self) -> str:
        pass

    @property
    @abstractmethod
    def description(self) -> str:
        pass

    @abstractmethod
    def _calculate(self, df: pl.DataFrame, ax: list[Axes]) -> pl.Series:
        pass

    def _fallback(self, df: pl.DataFrame):
        return (
            df
            .join(cbbi_fetch(self.name), on='Date', how='left', maintain_order='left')
            .with_columns(pl.col('Value').forward_fill())
            .get_column('Value')
        )

    async def calculate(self, df: pl.DataFrame, ax: list[Axes]):
        try:
            return self._calculate(df, ax)
        except Exception as ex:
            traceback.print_exc()
            await send_error_notification(ex)

            print(
                fg.black
                + bg.yellow
                + f' Requesting fallback values for {self.name} (from CBBI.info) '
                + rs.all
            )
            return self._fallback(df)


================================================
FILE: metrics/mvrv_z_score.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from api.coinsoto_api import cs_fetch
from metrics._common import join_left_on_date, linreg_predict
from metrics.base_metric import BaseMetric


class MVRVMetric(BaseMetric):
    @property
    def name(self):
        return 'MVRV'

    @property
    def description(self):
        return 'MVRV Z-Score'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        bull_days_shift = 6
        low_model_adjust = 0.26

        df = join_left_on_date(
            df,
            cs_fetch(
                path='chain/index/charts?type=/charts/mvrv-zscore/',
                data_selector='value4',
                col_name='MVRV',
            ),
        )

        df = df.with_columns(
            MVRV=(
                pl
                .when(pl.col('DaysSinceHalving') < pl.col('DaysSincePriceLow'))
                .then(pl.col('MVRV').shift(bull_days_shift))
                .otherwise(pl.col('MVRV'))
            )
        )
        df = df.with_columns(MVRV=(pl.col('MVRV').forward_fill() + 1).log())

        row_nr = np.arange(df.height)
        high_idx = row_nr[df.get_column('PriceHigh').to_numpy()]
        low_idx = row_nr[df.get_column('PriceLow').to_numpy()]

        mvrv = df.get_column('MVRV').to_numpy()
        high_model = linreg_predict(high_idx, mvrv[high_idx], row_nr)
        low_model = linreg_predict(low_idx, mvrv[low_idx], row_nr) + low_model_adjust

        x = df.get_column('Date').to_numpy()
        mvrv_index = (mvrv - low_model) / (high_model - low_model)
        y_out = np.nan_to_num(mvrv_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('MVRVIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('MVRV')
        sns.lineplot(x=x, y=mvrv, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=low_model, ax=ax[1])

        return pl.Series(mvrv_index)


================================================
FILE: metrics/pi_cycle.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from metrics._common import linreg_predict
from metrics.base_metric import BaseMetric
from utils import mark_highs_lows


class PiCycleMetric(BaseMetric):
    @property
    def name(self):
        return 'PiCycle'

    @property
    def description(self):
        return 'Pi Cycle Top Indicator'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        dma_111 = pl.col('Price').rolling_mean(window_size=111, min_samples=111)
        dma_350x2 = pl.col('Price').rolling_mean(window_size=350, min_samples=350) * 2

        df = df.with_columns(
            dma_111.alias('111DMA'),
            dma_350x2.alias('350DMAx2'),
        ).with_columns(PiCycleDiff=pl.col('111DMA').log() - pl.col('350DMAx2').log())

        diff = df.get_column('PiCycleDiff').to_numpy()
        df = mark_highs_lows(df, 'PiCycleDiff', True, 365 * 2, 365)

        crossed = diff > 0
        crossed_idx = np.flatnonzero(crossed)
        uncrossed_idx = np.flatnonzero(~crossed)
        crossed_segments = (
            np.split(crossed_idx, np.where(np.diff(crossed_idx) > 1)[0] + 1)
            if crossed_idx.size
            else []
        )
        uncrossed_segments = (
            np.split(uncrossed_idx, np.where(np.diff(uncrossed_idx) > 1)[0] + 1)
            if uncrossed_idx.size
            else []
        )

        distance_floor = np.zeros(df.height, dtype=np.float64)
        distance_from_zero = np.abs(diff)
        for i, crossed_seg in enumerate(crossed_segments):
            seg_distance = distance_from_zero[crossed_seg]
            max_pos = int(np.nanargmax(seg_distance))
            max_idx = int(crossed_seg[max_pos])
            max_distance = float(seg_distance[max_pos])

            distance_floor[max_idx + 1 :] = max_distance

            uncrossed_seg = (
                uncrossed_segments[i + 1] if i + 1 < len(uncrossed_segments) else None
            )
            if uncrossed_seg is not None and uncrossed_seg.size:
                above = uncrossed_seg[distance_from_zero[uncrossed_seg] >= max_distance]
                if above.size:
                    distance_floor[int(above.min()) :] = 0

            crossed_next = (
                crossed_segments[i + 1] if i + 1 < len(crossed_segments) else None
            )
            if crossed_next is not None and crossed_next.size:
                distance_floor[int(crossed_next.min()) :] = 0

        high_idx = np.flatnonzero(df.get_column('PiCycleDiffHigh').to_numpy())
        row_nr = np.arange(df.height)
        low_idx = np.flatnonzero(df.get_column('PiCycleDiffLow').to_numpy())

        target = np.zeros(df.height, dtype=np.float64)
        if high_idx.size >= 3:
            target = np.minimum(
                linreg_predict(high_idx, diff[high_idx], row_nr),
                0.0,
            )

        finite_idx = np.flatnonzero(np.isfinite(diff))
        cold_model = np.full(df.height, np.nan, dtype=np.float64)

        cycle_starts = np.array([int(finite_idx[0]), *low_idx], dtype=np.int64)
        for i, start in enumerate(cycle_starts):
            end = (
                int(cycle_starts[i + 1] - 1)
                if i + 1 < cycle_starts.size
                else df.height - 1
            )
            cold_model[start : end + 1] = diff[start]

        distance = np.maximum(np.maximum(target - diff, 0.0), distance_floor)
        index = 1 - distance / np.abs(target - cold_model)

        x = df.get_column('Date').to_numpy()
        y_out = np.nan_to_num(index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('PiCycleIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('PiCycleDiff')
        sns.lineplot(x=x, y=diff, ax=ax[1])
        sns.lineplot(x=x, y=target, ax=ax[1])
        sns.lineplot(x=x, y=cold_model, ax=ax[1])
        sns.lineplot(x=x, y=target - distance_floor, ax=ax[1], linestyle='--')

        return pl.Series('PiCycleIndex', index)


================================================
FILE: metrics/puell_multiple.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from metrics._common import linreg_predict
from metrics.base_metric import BaseMetric


class PuellMetric(BaseMetric):
    @property
    def name(self):
        return 'Puell'

    @property
    def description(self):
        return 'Puell Multiple'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        puell_log = (
            df
            .get_column('PuellMultiple')
            .forward_fill()
            .log()
            .rolling_mean(window_size=3, min_samples=1)
            .to_numpy()
        )

        row_nr = np.arange(df.height)
        high_idx = row_nr[df.get_column('PriceHigh').to_numpy()]

        high_model = linreg_predict(high_idx, puell_log[high_idx], row_nr)
        low_model = -1.0

        x = df.get_column('Date').to_numpy()
        puell_index = (puell_log - low_model) / (high_model - low_model)
        y_out = np.nan_to_num(puell_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('PuellIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('PuellLog')
        sns.lineplot(x=x, y=puell_log, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=np.full(df.height, low_model, dtype=np.float64), ax=ax[1])

        return pl.Series(puell_index)


================================================
FILE: metrics/reserve_risk.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from api.coinsoto_api import cs_fetch
from metrics._common import join_left_on_date, linreg_predict
from metrics.base_metric import BaseMetric


class ReserveRiskMetric(BaseMetric):
    @property
    def name(self):
        return 'ReserveRisk'

    @property
    def description(self):
        return 'Reserve Risk'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        days_shift = 1

        df = join_left_on_date(
            df,
            cs_fetch(
                path='chain/index/charts?type=/charts/reserve-risk/',
                data_selector='value4',
                col_name='Risk',
            ),
        )
        df = df.with_columns(Risk=pl.col('Risk').shift(days_shift).forward_fill())

        row_nr = np.arange(df.height)
        high_idx = row_nr[df.get_column('PriceHigh').to_numpy()]
        low_idx = row_nr[df.get_column('PriceLow').to_numpy()][1:]

        risk_log = np.log(df.get_column('Risk').to_numpy())
        high_model = linreg_predict(high_idx, risk_log[high_idx], row_nr) - 0.15
        low_model = linreg_predict(low_idx, risk_log[low_idx], row_nr)

        x = df.get_column('Date').to_numpy()
        risk_index = (risk_log - low_model) / (high_model - low_model)
        y_out = np.nan_to_num(risk_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('RiskIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('RiskLog')
        sns.lineplot(x=x, y=risk_log, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=low_model, ax=ax[1])

        return pl.Series(risk_index)


================================================
FILE: metrics/rhodl_ratio.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from api.coinsoto_api import cs_fetch
from metrics._common import join_left_on_date, linreg_predict
from metrics.base_metric import BaseMetric


class RHODLMetric(BaseMetric):
    @property
    def name(self):
        return 'RHODL'

    @property
    def description(self):
        return 'RHODL Ratio'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        remote_df = cs_fetch(
            path='chain/index/charts?type=/charts/rhodl-ratio/',
            data_selector='value1',
            col_name='RHODL',
        )

        df = join_left_on_date(df, remote_df).with_columns(
            RHODL=pl.col('RHODL').forward_fill()
        )

        row_nr = np.arange(df.height)
        high_mask = df.get_column('PriceHigh').to_numpy() | (
            df.get_column('Date').to_numpy() == np.datetime64('2024-12-18')
        )
        high_idx = row_nr[high_mask]
        low_idx = row_nr[df.get_column('PriceLow').to_numpy()][1:]

        rhodl = df.get_column('RHODL').to_numpy()
        rhodl_log = np.log(rhodl)

        high_model = linreg_predict(high_idx, rhodl_log[high_idx], row_nr)
        low_model = linreg_predict(low_idx, rhodl_log[low_idx], row_nr)

        x = df.get_column('Date').to_numpy()
        rhodl_index = (rhodl_log - low_model) / (high_model - low_model)
        y_out = np.nan_to_num(rhodl_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('RHODLIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('RHODLLog')
        sns.lineplot(x=x, y=rhodl_log, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=low_model, ax=ax[1])

        return pl.Series(rhodl_index)


================================================
FILE: metrics/rupl.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from api.coinsoto_api import cs_fetch
from metrics._common import join_left_on_date, linreg_predict
from metrics.base_metric import BaseMetric


class RUPLMetric(BaseMetric):
    @property
    def name(self):
        return 'RUPL'

    @property
    def description(self):
        return 'RUPL/NUPL Chart'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        df = join_left_on_date(
            df,
            cs_fetch(
                path='chain/index/charts?type=/charts/relative-unrealized-prof/',
                data_selector='value1',
                col_name='RUPL',
            ),
        )

        df = df.with_columns(RUPL=pl.col('RUPL').forward_fill())

        row_nr = np.arange(df.height)
        high_idx = row_nr[df.get_column('PriceHigh').to_numpy()]
        low_idx = row_nr[df.get_column('PriceLow').to_numpy()][1:]

        rupl = df.get_column('RUPL').to_numpy()
        x_all = row_nr

        high_model = linreg_predict(high_idx, rupl[high_idx], x_all)
        low_model = linreg_predict(low_idx, rupl[low_idx], x_all)

        x = df.get_column('Date').to_numpy()
        rupl_index = (rupl - low_model) / (high_model - low_model)
        y_out = np.nan_to_num(rupl_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('RUPLIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('RUPL')
        sns.lineplot(x=x, y=rupl, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=low_model, ax=ax[1])

        return pl.Series(rupl_index)


================================================
FILE: metrics/trolololo.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from metrics._common import linreg_predict
from metrics.base_metric import BaseMetric


class TrolololoMetric(BaseMetric):
    @property
    def name(self):
        return 'Trolololo'

    @property
    def description(self):
        return 'Bitcoin Trolololo Trend Line'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        x = df.get_column('Date').to_numpy()
        price_log = df.get_column('PriceLog').to_numpy()

        begin_date = np.datetime64('2012-01-01T00:00:00')
        days_since_begin = (x - begin_date) / np.timedelta64(1, 'D')

        trolo_top_log = np.log(10.0) * (
            2.900 * np.log(days_since_begin + 1400) - 19.463
        )
        trolo_bottom_log = np.log(10.0) * (
            2.788 * np.log(days_since_begin + 1200) - 19.463
        )

        overshoot_actual = price_log - trolo_top_log
        undershoot_actual = price_log - trolo_bottom_log

        row_nr = np.arange(df.height)
        after_begin = days_since_begin >= 0
        high_mask = df.get_column('PriceHigh').to_numpy() & after_begin
        low_mask = df.get_column('PriceLow').to_numpy() & after_begin

        high_idx = row_nr[high_mask]
        low_idx = row_nr[low_mask]

        high_y = overshoot_actual[high_idx].copy()
        high_y[0] *= 0.6  # the first value seems too high

        overshoot_model = linreg_predict(high_idx, high_y, row_nr)
        undershoot_model = linreg_predict(low_idx, undershoot_actual[low_idx], row_nr)

        high_model = trolo_top_log + overshoot_model
        low_model = trolo_bottom_log + undershoot_model
        trolo_index = (price_log - low_model) / (high_model - low_model)

        y_out = np.nan_to_num(trolo_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('TroloIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('PriceLog')
        sns.lineplot(x=x, y=price_log, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=low_model, ax=ax[1])

        return pl.Series(trolo_index)


================================================
FILE: metrics/two_year_moving_average.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from metrics._common import linreg_predict
from metrics.base_metric import BaseMetric


class TwoYearMovingAverageMetric(BaseMetric):
    @property
    def name(self):
        return '2YMA'

    @property
    def description(self):
        return '2 Year Moving Average'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        row_nr = np.arange(df.height)
        high_idx = row_nr[df.get_column('PriceHigh').to_numpy()]
        low_idx = row_nr[df.get_column('PriceLow').to_numpy()]

        price_log = df.get_column('PriceLog').to_numpy()
        two_yma = df.get_column('Price730DMA').to_numpy()
        two_yma_log = np.log(two_yma)
        log_diff = price_log - two_yma_log

        overshoot_model = linreg_predict(high_idx, log_diff[high_idx], row_nr)
        undershoot_model = linreg_predict(low_idx, log_diff[low_idx], row_nr)

        x = df.get_column('Date').to_numpy()
        two_yma_high_model = overshoot_model + two_yma_log
        two_yma_low_model = undershoot_model + two_yma_log
        two_yma_index = (price_log - two_yma_low_model) / (
            two_yma_high_model - two_yma_low_model
        )
        y_out = np.nan_to_num(two_yma_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('2YMAIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('PriceLog')
        sns.lineplot(x=x, y=price_log, ax=ax[1])
        sns.lineplot(x=x, y=two_yma_high_model, ax=ax[1])
        sns.lineplot(x=x, y=two_yma_low_model, ax=ax[1])

        return pl.Series(two_yma_index)


================================================
FILE: metrics/woobull_topcap_cvdd.py
================================================
import numpy as np
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes

from metrics._common import join_left_on_date, linreg_predict
from metrics.base_metric import BaseMetric
from utils import HTTP


def _woocharts_xy_ms_df(*, x: list[object], y: list[object], y_name: str):
    return (
        pl
        .DataFrame({
            'Date': pl.Series(x, dtype=pl.Int64),
            y_name: pl.Series(y, dtype=pl.Float64),
        })
        .with_columns(
            Date=(
                pl
                .from_epoch(pl.col('Date'), time_unit='ms')
                .dt.cast_time_unit('us')
                .dt.replace_time_zone('UTC')
            )
        )
        .select('Date', y_name)
    )


def _fetch_df():
    response = HTTP.get('https://woocharts.com/bitcoin-price-models/data/chart.json')
    response.raise_for_status()
    data = response.json()

    df_top = _woocharts_xy_ms_df(
        x=data['top_']['x'],
        y=data['top_']['y'],
        y_name='Top',
    )
    df_cvdd = _woocharts_xy_ms_df(
        x=data['cvdd']['x'],
        y=data['cvdd']['y'],
        y_name='CVDD',
    )

    return df_top.join(df_cvdd, on='Date', how='inner', maintain_order='left')


class WoobullMetric(BaseMetric):
    @property
    def name(self):
        return 'Woobull'

    @property
    def description(self):
        return 'Woobull Top Cap vs CVDD'

    def _calculate(self, df: pl.DataFrame, ax: list[Axes]):
        df = join_left_on_date(df, _fetch_df())

        row_nr = np.arange(df.height)
        high_idx = row_nr[df.get_column('PriceHigh').to_numpy()]
        low_idx = row_nr[df.get_column('PriceLow').to_numpy()][1:]

        top_log = np.log(df.get_column('Top').to_numpy())
        cvdd_log = np.log(df.get_column('CVDD').to_numpy())
        price_log = df.get_column('PriceLog').to_numpy()
        woobull = (price_log - cvdd_log) / (top_log - cvdd_log)

        high_model = linreg_predict(high_idx, woobull[high_idx], row_nr) - 0.025
        low_model = linreg_predict(low_idx, woobull[low_idx], row_nr)

        x = df.get_column('Date').to_numpy()
        woobull_index = (woobull - low_model) / (high_model - low_model)
        y_out = np.nan_to_num(woobull_index, nan=0.0)

        ax[0].set_title(self.description)
        ax[0].set_xlabel('Date')
        ax[0].set_ylabel('WoobullIndex')
        sns.lineplot(x=x, y=y_out, ax=ax[0])

        ax[1].set_xlabel('Date')
        ax[1].set_ylabel('Woobull')
        sns.lineplot(x=x, y=woobull, ax=ax[1])
        sns.lineplot(x=x, y=high_model, ax=ax[1])
        sns.lineplot(x=x, y=low_model, ax=ax[1])

        return pl.Series(woobull_index)


================================================
FILE: pyproject.toml
================================================
[project]
name = "cbbi"
version = "0.0.0"
requires-python = "~=3.14.0"
dependencies = [
  "fire",
  "httpx[brotli,zstd]",
  "matplotlib",
  "numpy",
  "polars",
  "pyfiglet",
  "python-telegram-bot",
  "seaborn",
  "sty",
  "tqdm",
]

[tool.ruff]
indent-width = 4
line-length = 88
target-version = "py314"

[tool.ruff.lint]
ignore = [
  "S101",  # assert
]
# see https://docs.astral.sh/ruff/rules/ for rules documentation
select = [
  "A",  # flake8-builtins
  "ARG",  # flake8-unused-argumentsf
  "ASYNC",  # flake8-async
  "B",  # flake8-bugbear
  # "COM", # flake8-commas
  "C4",  # flake8-comprehensions
  "E4",  # pycodestyle
  "E7",
  "E9",
  "F",  # pyflakes
  # "FBT", # flake8-boolean-trap
  "FLY",  # flynt
  # "FURB", # refurb (preview)
  "G",  # flake8-logging-format
  "I",  # isort
  "INT",  # flake8-gettext
  # "LOG", # flake8-logging (preview)
  "N",  # pep8-naming
  "NPY",  # numpy
  "PERF",  # perflint
  "PGH",  # pygrep-hooks
  "PIE",  # flake8-pie
  "Q",  # flake8-quotes
  "UP",  # pyupgrade
  # "PL", # pylint
  "PT",  # flake8-pytest-style
  "PTH",  # flake8-use-pathlib
  "PYI",  # flake8-pyi
  "RSE",  # flake8-raise
  "RUF",  # ruff
  "S",  # flake8-bandit
  "SIM",  # flake8-simplify
  "SLF",  # flake8-self
  "SLOT",  # flake8-slots
  "T10",  # flake8-debugger
  # "T20", # flake8-print
  # "TRY", # tryceratops
  "YTT",  # flake8-2020
]
fixable = ["ALL"]
unfixable = []

[tool.ruff.lint.flake8-builtins]
builtins-ignorelist = ["id", "open", "type"]

[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "single"
multiline-quotes = "double"

[tool.ruff.lint.pylint]
max-args = 10

[tool.ruff.format]
indent-style = "space"
line-ending = "lf"
quote-style = "single"
skip-magic-trailing-comma = false
preview = true

[tool.setuptools]
packages = ["."]

[tool.uv]
package = false
python-downloads = "never"
python-preference = "only-system"


================================================
FILE: shell.nix
================================================
{ }:

let
  # Update with `nixpkgs-update` command
  pkgs =
    import
      (fetchTarball "https://github.com/NixOS/nixpkgs/archive/68a8af93ff4297686cb68880845e61e5e2e41d92.tar.gz")
      { };

  pythonLibs = with pkgs; [
    stdenv.cc.cc.lib
    zlib.out
  ];
  python' =
    with pkgs;
    (symlinkJoin {
      name = "python";
      paths = [ python314 ];
      buildInputs = [ makeWrapper ];
      postBuild = ''
        wrapProgram "$out/bin/python3.14" --prefix LD_LIBRARY_PATH : "${lib.makeLibraryPath pythonLibs}"
      '';
    });

  packages' = with pkgs; [
    python'
    coreutils
    curl
    gnused
    jq
    ruff
    uv

    (writeShellScriptBin "nixpkgs-update" ''
      set -e
      hash=$(
        curl -fsSL \
          https://prometheus.nixos.org/api/v1/query \
          -d 'query=channel_revision{channel="nixpkgs-unstable"}' |
          jq -r ".data.result[0].metric.revision"
      )
      sed -i "s|nixpkgs/archive/[0-9a-f]\\{40\\}|nixpkgs/archive/$hash|" shell.nix
      echo "Nixpkgs updated to $hash"
    '')
    (writeShellScriptBin "docker-build-push" ''
      set -e
      if command -v podman &> /dev/null; then docker() { podman "$@"; } fi
      docker push $(docker load < $(nix-build --no-out-link) | sed -En 's/Loaded image: (\S+)/\1/p')
    '')
  ];

  shell' = ''
    export SSL_CERT_FILE=${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt
    export PYTHONNOUSERSITE=1
    export PYTHONPATH=""
    export TZ=UTC

    if [ -f .env ]; then
      echo "Loading .env file"
      set -a; . .env; set +a
    else
      echo "Skipped loading .env file (not found)"
    fi

    current_python=$(readlink -e .venv/bin/python || echo "")
    current_python=''${current_python%/bin/*}
    [ "$current_python" != "${python'}" ] && rm -rf .venv/

    echo "Installing Python dependencies"
    export UV_PYTHON="${python'}/bin/python"
    uv sync --frozen
    source .venv/bin/activate
    export UV_PYTHON="$VIRTUAL_ENV/bin/python"
  '';
in
pkgs.mkShell {
  buildInputs = packages';
  shellHook = shell';
}


================================================
FILE: utils.py
================================================
import os
import traceback
from math import ceil

import numpy as np
import polars as pl
import telegram
from httpx import Client
from sty import bg

HTTP = Client(
    headers={
        'User-Agent': 'Mozilla/5.0 (Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0'
    },
    timeout=60,
    follow_redirects=True,
)


def mark_highs_lows(
    df: pl.DataFrame,
    col: str,
    begin_with_high: bool,
    window_size: int,
    ignore_last_rows: int,
):
    """
    Marks highs and lows (peaks) of the column values inside the given DataFrame.
    Marked points are indicated by `True` inside their corresponding, newly added, `col + "High"` and `col + "Low"` columns.

    Args:
        df: DataFrame from which the column values are selected and to which marked points columns are added.
        col: Column name of which values are selected inside the given DataFrame.
        begin_with_high: Indicates whether the first peak is high or low.
        window_size: Window size for the algorithm to consider.
                     Too low value will mark too many peaks, whereas, too high value will mark too little peaks.
        ignore_last_rows: Amount of trailing DataFrame rows for which highs and lows should not be marked.

    Returns:
        Modified input DataFrame with columns, indicating the marked points, added.
    """
    col_high = col + 'High'
    col_low = col + 'Low'

    values = df.get_column(col).to_numpy()
    high_marks = np.zeros(len(values), dtype=np.bool_)
    low_marks = np.zeros(len(values), dtype=np.bool_)

    searching_high = begin_with_high
    current_index = 0

    while True:
        window_end = min(current_index + window_size, len(values) - 1)
        window = values[current_index : window_end + 1]

        if sum(~np.isnan(window)) == 0 and window.shape[0] > 1:
            current_index += window.shape[0]
            continue

        if window.shape[0] <= 1:
            break

        window_index = current_index + (
            np.nanargmax(window) if searching_high else np.nanargmin(window)
        )

        if window_index == current_index:
            if searching_high:
                high_marks[window_index] = True
            else:
                low_marks[window_index] = True
            searching_high = not searching_high
            window_index = window_index + 1

        current_index = window_index

    if ignore_last_rows > 0:
        high_marks[-ignore_last_rows:] = False
        low_marks[-ignore_last_rows:] = False

    # stabilize the algorithm until a next major update
    stabilize_mask = df.get_column('Date').to_numpy() >= np.datetime64('2025-10-07')
    high_marks[stabilize_mask] = False
    low_marks[stabilize_mask] = False

    return df.with_columns(
        pl.Series(col_high, high_marks, dtype=pl.Boolean),
        pl.Series(col_low, low_marks, dtype=pl.Boolean),
    )


def mark_days_since(df: pl.DataFrame, cols: list[str]):
    """
    This function takes a DataFrame and a list of column names
    and calculates the number of days since the last `True` value for each column in the list.

    The resulting DataFrame will have new columns for each input column, with the column name prefixed by 'DaysSince'.
    The value in these new columns will be the number of days since the last `True` value in the corresponding input column.

    Args:
        df: The input DataFrame.
        cols: The list of boolean marker columns to calculate the days since the last `True` value.

    Returns:
        The modified DataFrame with the new columns added.
    """
    df = df.with_row_index(name='_row_nr')

    exprs: dict[str, pl.Expr] = {}
    for col in cols:
        last_event_idx = (
            pl.when(pl.col(col)).then(pl.col('_row_nr')).otherwise(None).forward_fill()
        )
        exprs[f'DaysSince{col}'] = pl.col('_row_nr') - last_event_idx

    return df.with_columns(**exprs).drop('_row_nr')


def format_percentage(val: float, suffix: str = ' %'):
    """
    Formats a percentage value (0.0 - 1.0) in the standardized way.
    Returned value has a constant width and a trailing '%' sign.

    Args:
        val: Percentage value to be formatted.
        suffix: String to be appended to the result.

    Returns:
        Formatted percentage value with a constant width and trailing '%' sign.

    Examples:
        >>> print(format_percentage(0.359))
        str(' 36 %')

        >>> print(format_percentage(1.1))
        str('110 %')
    """

    return f'{ceil(val * 100): >3d}{suffix}'


def get_color(val: float):
    """
    Maps a percentage value (0.0 - 1.0) to its corresponding color.
    The color is used to indicate whether the value is low (0.0) or high (1.0).
    Returned value is a valid sty-package color string.

    Args:
        val: Percentage value to be mapped into a color.

    Returns:
        Valid sty-package color string.
    """

    config = [
        bg.da_red,
        0.3,
        bg.da_yellow,
        0.65,
        bg.da_green,
        0.85,
        bg.da_cyan,
        0.97,
        bg.da_magenta,
    ]

    bin_index = np.digitize([round(val, 2)], config[1::2])[0]
    return config[::2][bin_index]


async def send_error_notification(exception: Exception):
    """
    This function sends a notification to a Telegram chat with details of the provided exception.

    Args:
        exception: The exception to be reported.

    Returns:
        A boolean indicating whether the notification was sent successfully.
    """
    telegram_token = os.getenv('TELEGRAM_TOKEN')
    telegram_chat_id = os.getenv('TELEGRAM_CHAT_ID')
    if not telegram_token or not telegram_chat_id:
        return False

    async with telegram.Bot(telegram_token) as bot:
        await bot.send_message(
            telegram_chat_id,
            f'🚨 An error has occurred: <b>{exception!s}</b>\n'
            f'\n'
            f'🔍️ <b>Stack trace</b>\n'
            f'<pre>{"".join(traceback.format_exception(exception))}</pre>',
            parse_mode='HTML',
        )
    return True
Download .txt
gitextract_j3fsxwr5/

├── .envrc
├── .gitattributes
├── .gitignore
├── .vscode/
│   └── launch.json
├── LICENSE
├── README.md
├── api/
│   ├── cbbiinfo_api.py
│   ├── coinmetrics_api.py
│   └── coinsoto_api.py
├── asciinema/
│   └── thumbnail.xcf
├── fetch_bitcoin_data.py
├── main.py
├── metrics/
│   ├── _common.py
│   ├── base_metric.py
│   ├── mvrv_z_score.py
│   ├── pi_cycle.py
│   ├── puell_multiple.py
│   ├── reserve_risk.py
│   ├── rhodl_ratio.py
│   ├── rupl.py
│   ├── trolololo.py
│   ├── two_year_moving_average.py
│   └── woobull_topcap_cvdd.py
├── pyproject.toml
├── shell.nix
└── utils.py
Download .txt
SYMBOL INDEX (63 symbols across 17 files)

FILE: api/cbbiinfo_api.py
  function cbbi_fetch (line 6) | def cbbi_fetch(key: str):

FILE: api/coinmetrics_api.py
  function cm_fetch_asset_metrics (line 6) | def cm_fetch_asset_metrics(

FILE: api/coinsoto_api.py
  function cs_fetch (line 6) | def cs_fetch(path: str, data_selector: str, col_name: str):

FILE: fetch_bitcoin_data.py
  function fetch_coinmetrics_data (line 7) | def fetch_coinmetrics_data():
  function fetch_bitcoin_data (line 51) | def fetch_bitcoin_data():

FILE: main.py
  function get_metrics (line 29) | def get_metrics():
  function _json_number (line 46) | def _json_number(value: float | None, *, precision: int = 4):
  function _write_columns_orient_json (line 56) | def _write_columns_orient_json(df: pl.DataFrame, path: Path, *, precisio...
  function _add_common_markers (line 73) | def _add_common_markers(
  function _shade_metric_bounds (line 84) | def _shade_metric_bounds(ax):
  function run (line 111) | async def run(json_file: str, charts_file: str, output_dir: str | None):
  function run_and_retry (line 247) | def run_and_retry(

FILE: metrics/_common.py
  function join_left_on_date (line 5) | def join_left_on_date(df: pl.DataFrame, other: pl.DataFrame):
  function linreg_predict (line 9) | def linreg_predict(

FILE: metrics/base_metric.py
  class BaseMetric (line 12) | class BaseMetric(ABC):
    method name (line 15) | def name(self) -> str:
    method description (line 20) | def description(self) -> str:
    method _calculate (line 24) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]) -> pl.Series:
    method _fallback (line 27) | def _fallback(self, df: pl.DataFrame):
    method calculate (line 35) | async def calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/mvrv_z_score.py
  class MVRVMetric (line 11) | class MVRVMetric(BaseMetric):
    method name (line 13) | def name(self):
    method description (line 17) | def description(self):
    method _calculate (line 20) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/pi_cycle.py
  class PiCycleMetric (line 11) | class PiCycleMetric(BaseMetric):
    method name (line 13) | def name(self):
    method description (line 17) | def description(self):
    method _calculate (line 20) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/puell_multiple.py
  class PuellMetric (line 10) | class PuellMetric(BaseMetric):
    method name (line 12) | def name(self):
    method description (line 16) | def description(self):
    method _calculate (line 19) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/reserve_risk.py
  class ReserveRiskMetric (line 11) | class ReserveRiskMetric(BaseMetric):
    method name (line 13) | def name(self):
    method description (line 17) | def description(self):
    method _calculate (line 20) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/rhodl_ratio.py
  class RHODLMetric (line 11) | class RHODLMetric(BaseMetric):
    method name (line 13) | def name(self):
    method description (line 17) | def description(self):
    method _calculate (line 20) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/rupl.py
  class RUPLMetric (line 11) | class RUPLMetric(BaseMetric):
    method name (line 13) | def name(self):
    method description (line 17) | def description(self):
    method _calculate (line 20) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/trolololo.py
  class TrolololoMetric (line 10) | class TrolololoMetric(BaseMetric):
    method name (line 12) | def name(self):
    method description (line 16) | def description(self):
    method _calculate (line 19) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/two_year_moving_average.py
  class TwoYearMovingAverageMetric (line 10) | class TwoYearMovingAverageMetric(BaseMetric):
    method name (line 12) | def name(self):
    method description (line 16) | def description(self):
    method _calculate (line 19) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: metrics/woobull_topcap_cvdd.py
  function _woocharts_xy_ms_df (line 11) | def _woocharts_xy_ms_df(*, x: list[object], y: list[object], y_name: str):
  function _fetch_df (line 30) | def _fetch_df():
  class WoobullMetric (line 49) | class WoobullMetric(BaseMetric):
    method name (line 51) | def name(self):
    method description (line 55) | def description(self):
    method _calculate (line 58) | def _calculate(self, df: pl.DataFrame, ax: list[Axes]):

FILE: utils.py
  function mark_highs_lows (line 20) | def mark_highs_lows(
  function mark_days_since (line 92) | def mark_days_since(df: pl.DataFrame, cols: list[str]):
  function format_percentage (line 119) | def format_percentage(val: float, suffix: str = ' %'):
  function get_color (line 142) | def get_color(val: float):
  function send_error_notification (line 171) | async def send_error_notification(exception: Exception):
Condensed preview — 26 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (96K chars).
[
  {
    "path": ".envrc",
    "chars": 37,
    "preview": "# shellcheck disable=SC2148\n\nuse nix\n"
  },
  {
    "path": ".gitattributes",
    "chars": 66,
    "preview": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": ".gitignore",
    "chars": 6564,
    "preview": "# Created by https://www.toptal.com/developers/gitignore/api/dotenv,python,pycharm,visualstudiocode,direnv\n# Edit at htt"
  },
  {
    "path": ".vscode/launch.json",
    "chars": 526,
    "preview": "{\n    \"configurations\": [\n        {\n            \"console\": \"integratedTerminal\",\n            \"name\": \"Python Debugger: C"
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 3767,
    "preview": "# ColinTalksCrypto Bitcoin Bull Run Index (CBBI)\n\n![Python version](https://shields.monicz.dev/badge/python-v3.13-blue)\n"
  },
  {
    "path": "api/cbbiinfo_api.py",
    "chars": 710,
    "preview": "import polars as pl\n\nfrom utils import HTTP\n\n\ndef cbbi_fetch(key: str):\n    response = HTTP.get('https://colintalkscrypt"
  },
  {
    "path": "api/coinmetrics_api.py",
    "chars": 1479,
    "preview": "import polars as pl\n\nfrom utils import HTTP\n\n\ndef cm_fetch_asset_metrics(\n    *,\n    asset: str,\n    metrics: list[str],"
  },
  {
    "path": "api/coinsoto_api.py",
    "chars": 789,
    "preview": "import polars as pl\n\nfrom utils import HTTP\n\n\ndef cs_fetch(path: str, data_selector: str, col_name: str):\n    response ="
  },
  {
    "path": "fetch_bitcoin_data.py",
    "chars": 2360,
    "preview": "import polars as pl\n\nfrom api.coinmetrics_api import cm_fetch_asset_metrics\nfrom utils import mark_days_since, mark_high"
  },
  {
    "path": "main.py",
    "chars": 9472,
    "preview": "import asyncio\nimport math\nimport time\nimport traceback\nfrom pathlib import Path\n\nimport fire\nimport numpy as np\nimport "
  },
  {
    "path": "metrics/_common.py",
    "chars": 635,
    "preview": "import numpy as np\nimport polars as pl\n\n\ndef join_left_on_date(df: pl.DataFrame, other: pl.DataFrame):\n    return df.joi"
  },
  {
    "path": "metrics/base_metric.py",
    "chars": 1236,
    "preview": "import traceback\nfrom abc import ABC, abstractmethod\n\nimport polars as pl\nfrom matplotlib.axes import Axes\nfrom sty impo"
  },
  {
    "path": "metrics/mvrv_z_score.py",
    "chars": 2054,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom api.coinsoto_api imp"
  },
  {
    "path": "metrics/pi_cycle.py",
    "chars": 4089,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom metrics._common impo"
  },
  {
    "path": "metrics/puell_multiple.py",
    "chars": 1453,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom metrics._common impo"
  },
  {
    "path": "metrics/reserve_risk.py",
    "chars": 1784,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom api.coinsoto_api imp"
  },
  {
    "path": "metrics/rhodl_ratio.py",
    "chars": 1864,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom api.coinsoto_api imp"
  },
  {
    "path": "metrics/rupl.py",
    "chars": 1728,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom api.coinsoto_api imp"
  },
  {
    "path": "metrics/trolololo.py",
    "chars": 2215,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom metrics._common impo"
  },
  {
    "path": "metrics/two_year_moving_average.py",
    "chars": 1722,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom metrics._common impo"
  },
  {
    "path": "metrics/woobull_topcap_cvdd.py",
    "chars": 2655,
    "preview": "import numpy as np\nimport polars as pl\nimport seaborn as sns\nfrom matplotlib.axes import Axes\n\nfrom metrics._common impo"
  },
  {
    "path": "pyproject.toml",
    "chars": 1891,
    "preview": "[project]\nname = \"cbbi\"\nversion = \"0.0.0\"\nrequires-python = \"~=3.14.0\"\ndependencies = [\n  \"fire\",\n  \"httpx[brotli,zstd]\""
  },
  {
    "path": "shell.nix",
    "chars": 2029,
    "preview": "{ }:\n\nlet\n  # Update with `nixpkgs-update` command\n  pkgs =\n    import\n      (fetchTarball \"https://github.com/NixOS/nix"
  },
  {
    "path": "utils.py",
    "chars": 6033,
    "preview": "import os\nimport traceback\nfrom math import ceil\n\nimport numpy as np\nimport polars as pl\nimport telegram\nfrom httpx impo"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the Zaczero/CBBI GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 26 files (89.5 KB), approximately 23.0k tokens, and a symbol index with 63 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!