← Voltar ao Hub

🔍 Tech Bubble Detector - Sistema Completo

Sistema matemático avançado para identificar bolhas tecnológicas integrando dados reais de múltiplas fontes.

📊 Arquitetura

┌─────────────────────────────────────────────────────────┐
│                    Frontend React                        │
│              (tech-bubble-detector.jsx)                  │
└───────────────────┬─────────────────────────────────────┘
                    │ HTTP/REST
┌───────────────────▼─────────────────────────────────────┐
│                   FastAPI Backend                        │
│               (backend_api.py)                           │
│                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │ Data Fetcher │  │   Calculator │  │  Cache Layer │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
└───────────┬───────────────┬──────────────┬─────────────┘
            │               │              │
    ┌───────▼───────┐ ┌────▼────┐  ┌─────▼──────┐
    │  PostgreSQL   │ │  Redis  │  │  External  │
    │   Database    │ │  Cache  │  │    APIs    │
    └───────────────┘ └─────────┘  └────────────┘

🎯 Componentes

1. Frontend Interativo

2. Backend API (Python/FastAPI)

3. Infraestrutura

🚀 Quick Start

Opção 1: Docker Compose (Recomendado)

1. Clone e configure

git clone cd bubble-detector

2. Configure variáveis de ambiente

cp .env.example .env

Edite .env com suas API keys

3. Inicie todos os serviços

docker-compose up -d

4. Acesse

API: http://localhost:8000

Docs: http://localhost:8000/docs

Opção 2: Instalação Local

1. Instale dependências Python

pip install -r requirements.txt

2. Configure banco de dados

createdb bubbledb psql bubbledb < init.sql

3. Inicie Redis

redis-server

4. Configure .env

cp .env.example .env

5. Inicie a API

python backend_api.py

📡 API Endpoints

Análise de Ativo

POST /api/analyze
Content-Type: application/json

{
  "crypto_id": "bitcoin",
  "github_owner": "bitcoin",
  "github_repo": "bitcoin",
  "subreddit": "Bitcoin",
  "npm_package": null
}
Resposta:
{
  "asset": "bitcoin",
  "metrics": {
    "adoption": 0.75,
    "hype": 0.82,
    "investment": 0.68,
    "network": 0.73,
    "feedback": 0.15,
    "bubble_index": 0.64,
    "divergence": 0.07,
    "risk_level": "Alto",
    "risk_color": "#ef4444",
    "timestamp": 1701234567890
  },
  "raw_data": { ... },
  "cached": false
}

Histórico

GET /api/historical/bitcoin?days=90

Presets

GET /api/presets

Health Check

GET /health

🔑 API Keys Necessárias

Obrigatórias (para funcionalidades básicas)

Recomendadas (para rate limits maiores)

- Sem token: 60 req/hora

- Com token: 5000 req/hora

Opcionais (para features avançadas)

🧮 Modelo Matemático

Métricas Principais

#### 1. Adoção Real (A)

A = w1·(stars/50k) + w2·(forks/10k) + w3·(commits/500) + w4·(downloads/10M)

#### 2. Hype (H)

H = w1·sentiment + w2·engagement + w3·price_velocity

#### 3. Investimento (I)

I = (avg_volume / max_volume) · momentum

#### 4. Efeitos de Rede (N)

N = A^1.5  (Metcalfe modificado)

#### 5. Feedback Loops (F)

F = γ(H·I + N·A + I·N) - δA²H²

#### 6. Índice de Bolha (B)

B = 0.25·D + 0.30·I^1.5 + 0.20·N² + 0.25·|F|

Onde D = |H-A| (divergência hype-adoção)

Classificação de Risco

| Índice | Nível | Descrição | |--------|-------|-----------| | 0-30% | Baixo | Crescimento saudável | | 30-50% | Moderado | Atenção recomendada | | 50-70% | Alto | Correção provável | | 70-100% | Crítico | Bolha iminente |

📊 Fontes de Dados

Market Data

Adoption Data

Sentiment/Hype

Network Effects

🔧 Configuração Avançada

Celery para Jobs Periódicos

tasks.py

from celery import Celery from celery.schedules import crontab celery = Celery('tasks', broker='redis://localhost:6379/0') @celery.task def auto_analyze_assets(): assets = ['bitcoin', 'ethereum', 'react'] for asset in assets: # Executar análise pass celery.conf.beat_schedule = { 'analyze-every-hour': { 'task': 'tasks.auto_analyze_assets', 'schedule': crontab(minute=0), # A cada hora } }

Alertas Automáticos

def check_bubble_alert(metrics):
    if metrics['bubble_index'] > 0.7:
        send_alert(
            level='critical',
            message=f"Bubble index crítico: {metrics['bubble_index']:.2%}"
        )

Custom Normalizers

class CustomNormalizer:
    @staticmethod
    def normalize_github_stars(stars: int) -> float:
        # Sua própria lógica de normalização
        return min(stars / 100000, 1.0)

📈 Casos de Uso

1. Análise de Criptomoeda

config = {
    "crypto_id": "bitcoin",
    "github_owner": "bitcoin",
    "github_repo": "bitcoin",
    "subreddit": "Bitcoin"
}

2. Framework JavaScript

config = {
    "github_owner": "facebook",
    "github_repo": "react",
    "npm_package": "react",
    "subreddit": "reactjs"
}

3. Tecnologia Emergente (AI)

config = {
    "github_owner": "openai",
    "github_repo": "gpt-3",
    "subreddit": "artificial",
    "npm_package": "openai"
}

🐛 Troubleshooting

Problema: Rate Limit GitHub

Solução: Configure GITHUB_TOKEN no .env

Problema: Redis Connection Failed

Solução: Verifique se Redis está rodando
redis-cli ping  # Deve retornar PONG

Problema: PostgreSQL Connection Error

Solução: Verifique credenciais no .env
psql -U bubbleuser -d bubbledb -h localhost

Problema: CoinGecko 429 (Too Many Requests)

Solução: Aumente o cache TTL ou use CoinGecko Pro API

📊 Monitoramento

Métricas Recomendadas

Prometheus metrics

from prometheus_client import Counter, Histogram api_requests = Counter('api_requests_total', 'Total API requests') response_time = Histogram('response_time_seconds', 'Response time') cache_hits = Counter('cache_hits_total', 'Cache hits')

Logging

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

🔒 Segurança

Rate Limiting

from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)

@app.get("/api/analyze")
@limiter.limit("60/minute")
async def analyze():
    pass

CORS

CORS_ORIGINS = [
    "http://localhost:3000",
    "https://yourdomain.com"
]

📚 Referências

Papers e Modelos

APIs Documentadas

🤝 Contribuindo

1. Fork o projeto

2. Crie uma branch

git checkout -b feature/nova-fonte-dados

3. Commit suas mudanças

git commit -m "Adiciona integração com Twitter"

4. Push

git push origin feature/nova-fonte-dados

5. Abra um Pull Request

📝 Roadmap

📄 Licença

MIT License - sinta-se livre para usar e modificar

👥 Autores

Desenvolvido para análise quantitativa de mercados tecnológicos ---

🆘 Suporte

Happy Bubble Hunting! 🎈🔍
← Voltar ao Hub de Documentação