# jmgarrocho/tfg_bitcoin architecture

> Architecture diagram of the GitHub repository jmgarrocho/tfg_bitcoin, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-01). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/jmgarrocho/tfg_bitcoin
- Repository: https://github.com/jmgarrocho/tfg_bitcoin

## Overview

1. **Repository shape**
   - This is a multi-stage Bitcoin analytics pipeline, organized by subsystem rather than by application layer: `ingestion/`, `processing/`, `storage/`, `ml/`, `orchestration/`, `visualization/`, and `tests/`.
   - The runtime is mostly Python 3.11, with Kafka, Spark, InfluxDB, Airflow, Grafana, Docker Compose, and container-specific Dockerfiles.

2. **Primary data sources**
   - The system ingests Bitcoin market data from the **CoinGecko REST API** in two modes:
     - **real-time** streaming collection,
     - **historical/backfill** bootstrap collection.
   - It also ingests two **exogenous daily signals**:
     - **S&P 500** from Yahoo Finance,
     - **Fear & Greed Index** from Alternative.me.

3. **Ingestion boundary**
   - The `ingestion/` package is split by use case:
     - `realtime/` produces live BTC observations,
     - `historical/` produces backfill/history into Kafka,
     - `backfill/` handles historical bootstrap jobs,
     - `exogenous/` handles daily non-BTC collectors and writes to storage.
   - This layer is responsible for pulling from external APIs and handing off data either to Kafka or directly to InfluxDB, depending on the source.

4. **Streaming transport**
   - **Apache Kafka** is the decoupling layer between collection and processing.
   - BTC stream data is published by the ingestion producers and consumed downstream by Spark.
   - This gives the architecture a clear split between source adapters and stream processing.

5. **Processing layer**
   - The `processing/spark_jobs/` package contains Spark-side streaming logic:
     - Kafka consumption,
     - normalization,
     - feature preparation.
   - Spark is the main transformation boundary: raw market events become cleaned, structured time-series records suitable for storage and ML.

6. **Time-series storage**
   - **InfluxDB** is the central persistence layer for the pipeline.
   - It stores:
     - processed BTC market data,
     - exogenous market indicators,
     - model predictions,
     - evaluation/operational metrics.
   - The `storage/influx/` package contains dedicated writers and maintenance utilities, so storage concerns are isolated from collectors and ML code.

7. **Machine learning subsystem**
   - The `ml/` package is split into:
     - training (`ml/training/`),
     - inference (`ml/inference/`),
     - model-specific wrappers (`ml/models/chronos/`),
     - evaluation (`ml/evaluation/`).
   - Two forecasting paths run in parallel:
     - **Random Forest** trained with Spark MLlib on engineered BTC features,
     - **Chronos-T5-tiny** zero-shot inference using Hugging Face / Chronos tooling.
   - The ML boundary is fed from InfluxDB and writes predictions back to InfluxDB.

8. **Feature and training flow**
   - Training pulls historical BTC data from storage via dataset extraction, then applies feature engineering before model fitting.
   - The feature set includes price lags, rolling statistics, volatility-related signals, and calendar/time features.
   - This means the ML subsystem is not just a model wrapper; it includes the full feature pipeline needed to reproduce training and inference behavior.

9. **Inference and live evaluation**
   - Hourly prediction jobs generate forecasts and immediately evaluate them against observed prices.
   - The `ml/inference/live_evaluator.py` and prediction modules indicate a closed loop: inference output is written to storage, then compared with actuals to track model quality over time.

10. **Orchestration**
   - **Apache Airflow** is the control plane.
   - DAGs in `orchestration/airflow/dags/` coordinate:
     - daily BTC pipeline ingestion,
     - hourly Random Forest prediction,
     - hourly Chronos prediction,
     - one-time bootstrap backfill,
     - daily S&P 500 ingestion,
     - daily Fear & Greed ingestion.
   - Airflow is the scheduling boundary that connects all subsystems into repeatable workflows.

11. **Visualization**
   - **Grafana** reads from InfluxDB and exposes three pre-provisioned dashboards:
     - market overview,
     - market context,
     - ML performance.
   - The `visualization/grafana/provisioning/` directory shows that dashboards and the InfluxDB datasource are configured as code.

12. **Deployment and runtime composition**
   - `docker-compose.yml` is the main infrastructure entry point, and the repo also includes Dockerfiles for Spark/processing and ingestion.
   - The architecture is intended to run as a local containerized platform with Kafka, Spark, InfluxDB, Airflow, and Grafana alongside the Python jobs.

13. **Operational and quality boundaries**
   - `tests/unit/`, `tests/integration/`, and `tests/e2e/` cover individual components, cross-service behavior, and full containerized pipeline execution.
   - The presence of dedicated tests for collectors, Spark jobs, DAGs, writers, and ML logic suggests each boundary is meant to be independently verifiable.

14. **Overall data flow**
   - External APIs feed collectors → collectors publish or write raw data → Kafka carries BTC streams → Spark normalizes and enriches → InfluxDB becomes the shared time-series store → Airflow schedules ingestion and inference → ML jobs write predictions back → Grafana visualizes prices, exogenous context, and forecast performance.

Main entry points: [`orchestration/airflow/dags`](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/orchestration/airflow/dags) (Airflow DAGs), [`storage/influx`](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx) (Predictions Store), [`ml/training`](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training) (RF Train/Eval), [`ml/models/chronos`](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/models/chronos) (Chronos Inference)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_ingestion["Ingestion"]
  node_coingecko_realtime["Realtime BTC<br/>collector/producer"]
  node_coingecko_history["Historical BTC<br/>collector/producer"]
  node_coingecko_backfill["Bootstrap Jobs<br/>backfill runner"]
  node_exogenous_collectors["Exogenous Signals<br/>daily collectors"]
end

subgraph group_stream["Stream + Store"]
  node_kafka_transport["Kafka<br/>event bus"]
  node_spark_consumer["Spark Consumer<br/>stream ingest"]
  node_spark_normalizer["Normalizer<br/>transform"]
  node_influx_writer[("Influx Writer<br/>time-series writer")]
  node_metrics_writer[("Metrics Store<br/>operational writer")]
  node_predictions_writer[("Predictions Store<br/>prediction writer")]
  node_influxdb[("InfluxDB<br/>time-series DB")]
end

subgraph group_ml["Machine Learning"]
  node_dataset_extractor["Dataset Extractor<br/>feature data"]
  node_feature_engineering["Feature Engineering<br/>features"]
  node_rf_train_eval["RF Train/Eval<br/>spark mllib"]
  node_chronos_infer["Chronos Inference<br/>zero-shot model"]
  node_live_evaluator["Live Evaluator<br/>online eval"]
end

subgraph group_control["Control + Viz"]
  node_airflow_dags["Airflow DAGs<br/>scheduler"]
  node_grafana_dashboards["Grafana Dashboards<br/>visualization"]
end

node_coingecko_realtime -->|"BTC stream"| node_kafka_transport
node_coingecko_history -->|"history batch"| node_kafka_transport
node_coingecko_backfill -->|"bootstrap"| node_kafka_transport
node_exogenous_collectors -->|"daily context"| node_influxdb
node_kafka_transport -->|"consume"| node_spark_consumer
node_spark_consumer -->|"normalize"| node_spark_normalizer
node_spark_normalizer -->|"persist BTC"| node_influx_writer
node_influx_writer -->|"write"| node_influxdb
node_metrics_writer -->|"metrics"| node_influxdb
node_predictions_writer -->|"forecasts"| node_influxdb
node_dataset_extractor -->|"prepare"| node_feature_engineering
node_feature_engineering -->|"train/eval"| node_rf_train_eval
node_dataset_extractor -->|"context"| node_chronos_infer
node_chronos_infer -->|"save forecast"| node_predictions_writer
node_rf_train_eval -->|"save forecast"| node_predictions_writer
node_predictions_writer -->|"compare"| node_live_evaluator
node_live_evaluator -->|"scores"| node_metrics_writer
node_airflow_dags -->|"schedule"| node_coingecko_realtime
node_airflow_dags -->|"bootstrap"| node_coingecko_backfill
node_airflow_dags -->|"daily runs"| node_exogenous_collectors
node_airflow_dags -->|"hourly RF"| node_rf_train_eval
node_airflow_dags -->|"hourly Chronos"| node_chronos_infer
node_influxdb -->|"read"| node_grafana_dashboards

click node_coingecko_realtime "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/realtime"
click node_coingecko_history "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/historical"
click node_coingecko_backfill "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/backfill"
click node_exogenous_collectors "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/exogenous"
click node_spark_consumer "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/processing/spark_jobs"
click node_spark_normalizer "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/processing/spark_jobs"
click node_influx_writer "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx"
click node_metrics_writer "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx"
click node_predictions_writer "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx"
click node_dataset_extractor "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training"
click node_feature_engineering "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training"
click node_rf_train_eval "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training"
click node_chronos_infer "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/models/chronos"
click node_live_evaluator "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/inference"
click node_airflow_dags "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/orchestration/airflow/dags"
click node_grafana_dashboards "https://github.com/jmgarrocho/tfg_bitcoin/tree/main/visualization/grafana/provisioning"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_coingecko_realtime,node_coingecko_history,node_coingecko_backfill,node_exogenous_collectors toneBlue
class node_kafka_transport,node_spark_consumer,node_spark_normalizer,node_influx_writer,node_metrics_writer,node_predictions_writer,node_influxdb toneAmber
class node_dataset_extractor,node_feature_engineering,node_rf_train_eval,node_chronos_infer,node_live_evaluator toneMint
class node_airflow_dags,node_grafana_dashboards toneRose
```

## Components

### Ingestion

External API collectors and Kafka producers for Bitcoin and exogenous signals.

- [Realtime BTC](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/realtime): collector/producer · Streams live Bitcoin market observations from CoinGecko into Kafka. · `ingestion/realtime`
- [Historical BTC](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/historical): collector/producer · Backfills CoinGecko market history into Kafka for downstream processing. · `ingestion/historical`
- [Bootstrap Jobs](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/backfill): backfill runner · One-time bootstrap collection and history loading for initial pipeline state. · `ingestion/backfill`
- [Exogenous Signals](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ingestion/exogenous): daily collectors · Fetches S&P 500 and Fear & Greed daily signals and writes them to storage. · `ingestion/exogenous`

### Stream + Store

Kafka transport, Spark processing, and InfluxDB persistence.

- **Kafka**: event bus · Decouples BTC producers from Spark processing.
- [Spark Consumer](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/processing/spark_jobs): stream ingest · Consumes BTC events from Kafka and starts the processing flow. · `processing/spark_jobs`
- [Normalizer](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/processing/spark_jobs): transform · Cleans, normalizes, and structures market events into time-series records. · `processing/spark_jobs`
- [Influx Writer](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx): time-series writer · Persists processed BTC data and exogenous inputs into InfluxDB. · `storage/influx`
- [Metrics Store](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx): operational writer · Writes evaluation and operational metrics to InfluxDB. · `storage/influx`
- [Predictions Store](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/storage/influx): prediction writer · Stores model forecasts for later comparison and visualization. · `storage/influx`
- **InfluxDB**: time-series DB · Central persistence layer for market data, context signals, predictions, and metrics.

### Machine Learning

Training, inference, and evaluation workflows for forecasting.

- [Dataset Extractor](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training): feature data · Loads historical BTC data from storage for training and inference prep. · `ml/training`
- [Feature Engineering](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training): features · Builds lags, rolling stats, volatility signals, and calendar features. · `ml/training`
- [RF Train/Eval](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/training): spark mllib · Trains and evaluates the Random Forest forecasting path. · `ml/training`
- [Chronos Inference](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/models/chronos): zero-shot model · Runs Chronos-T5-tiny forecasting through Hugging Face/Chronos tooling. · `ml/models/chronos`
- [Live Evaluator](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/ml/inference): online eval · Compares forecasts against observed prices and tracks model quality over time. · `ml/inference`

### Control + Viz

Airflow scheduling and Grafana dashboards.

- [Airflow DAGs](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/orchestration/airflow/dags): scheduler · Coordinates ingestion, bootstrap, and hourly prediction workflows. · `orchestration/airflow/dags`
- [Grafana Dashboards](https://github.com/jmgarrocho/tfg_bitcoin/tree/main/visualization/grafana/provisioning): visualization · Reads InfluxDB to show market overview, market context, and ML performance. · `visualization/grafana/provisioning`

## Connections

- Realtime BTC → Kafka: BTC stream · Publishes live Bitcoin observations.
- Historical BTC → Kafka: history batch · Publishes historical BTC events for downstream consumption.
- Bootstrap Jobs → Kafka: bootstrap · Seeds the stream with historical bootstrap data.
- Exogenous Signals → InfluxDB: daily context · Writes S&P 500 and Fear & Greed values directly to storage.
- Kafka → Spark Consumer: consume · Spark reads BTC events from Kafka.
- Spark Consumer → Normalizer: normalize · Transforms raw events into structured market records.
- Normalizer → Influx Writer: persist BTC · Stores cleaned BTC time-series records.
- Influx Writer → InfluxDB: write · Persists processed market data to the shared store.
- Metrics Store → InfluxDB: metrics · Stores operational and evaluation metrics.
- Predictions Store → InfluxDB: forecasts · Stores model outputs for later evaluation and dashboards.
- Dataset Extractor → Feature Engineering: prepare · Builds model-ready features from historical storage data.
- Feature Engineering → RF Train/Eval: train/eval · Feeds engineered features into Random Forest training.
- Dataset Extractor → Chronos Inference: context · Provides historical context for inference jobs.
- Chronos Inference → Predictions Store: save forecast · Writes Chronos predictions to storage.
- RF Train/Eval → Predictions Store: save forecast · Writes trained model predictions to storage.
- Predictions Store → Live Evaluator: compare · Feeds forecasts into online evaluation against observed prices.
- Live Evaluator → Metrics Store: scores · Stores live model quality metrics.
- Airflow DAGs → Realtime BTC: schedule · Orchestrates the daily BTC ingestion workflow.
- Airflow DAGs → Bootstrap Jobs: bootstrap · Triggers initial backfill jobs.
- Airflow DAGs → Exogenous Signals: daily runs · Schedules S&P 500 and Fear & Greed collectors.
- Airflow DAGs → RF Train/Eval: hourly RF · Schedules Random Forest prediction/training workflow.
- Airflow DAGs → Chronos Inference: hourly Chronos · Schedules Chronos prediction workflow.
- InfluxDB → Grafana Dashboards: read · Grafana queries market, context, prediction, and metrics data.
