This is page 1 of 39. Use http://codebase.md/wshobson/maverick-mcp?lines=true&page={x} to view the full context.
# Directory Structure
```
├── .dockerignore
├── .env.example
├── .github
│ ├── dependabot.yml
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE
│ │ ├── bug_report.md
│ │ ├── config.yml
│ │ ├── feature_request.md
│ │ ├── question.md
│ │ └── security_report.md
│ ├── pull_request_template.md
│ └── workflows
│ ├── claude-code-review.yml
│ └── claude.yml
├── .gitignore
├── .python-version
├── .vscode
│ ├── launch.json
│ └── settings.json
├── alembic
│ ├── env.py
│ ├── script.py.mako
│ └── versions
│ ├── 001_initial_schema.py
│ ├── 003_add_performance_indexes.py
│ ├── 006_rename_metadata_columns.py
│ ├── 008_performance_optimization_indexes.py
│ ├── 009_rename_to_supply_demand.py
│ ├── 010_self_contained_schema.py
│ ├── 011_remove_proprietary_terms.py
│ ├── 013_add_backtest_persistence_models.py
│ ├── 014_add_portfolio_models.py
│ ├── 08e3945a0c93_merge_heads.py
│ ├── 9374a5c9b679_merge_heads_for_testing.py
│ ├── abf9b9afb134_merge_multiple_heads.py
│ ├── adda6d3fd84b_merge_proprietary_terms_removal_with_.py
│ ├── e0c75b0bdadb_fix_financial_data_precision_only.py
│ ├── f0696e2cac15_add_essential_performance_indexes.py
│ └── fix_database_integrity_issues.py
├── alembic.ini
├── CLAUDE.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── DATABASE_SETUP.md
├── docker-compose.override.yml.example
├── docker-compose.yml
├── Dockerfile
├── docs
│ ├── api
│ │ └── backtesting.md
│ ├── BACKTESTING.md
│ ├── COST_BASIS_SPECIFICATION.md
│ ├── deep_research_agent.md
│ ├── exa_research_testing_strategy.md
│ ├── PORTFOLIO_PERSONALIZATION_PLAN.md
│ ├── PORTFOLIO.md
│ ├── SETUP_SELF_CONTAINED.md
│ └── speed_testing_framework.md
├── examples
│ ├── complete_speed_validation.py
│ ├── deep_research_integration.py
│ ├── llm_optimization_example.py
│ ├── llm_speed_demo.py
│ ├── monitoring_example.py
│ ├── parallel_research_example.py
│ ├── speed_optimization_demo.py
│ └── timeout_fix_demonstration.py
├── LICENSE
├── Makefile
├── MANIFEST.in
├── maverick_mcp
│ ├── __init__.py
│ ├── agents
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── circuit_breaker.py
│ │ ├── deep_research.py
│ │ ├── market_analysis.py
│ │ ├── optimized_research.py
│ │ ├── supervisor.py
│ │ └── technical_analysis.py
│ ├── api
│ │ ├── __init__.py
│ │ ├── api_server.py
│ │ ├── connection_manager.py
│ │ ├── dependencies
│ │ │ ├── __init__.py
│ │ │ ├── stock_analysis.py
│ │ │ └── technical_analysis.py
│ │ ├── error_handling.py
│ │ ├── inspector_compatible_sse.py
│ │ ├── inspector_sse.py
│ │ ├── middleware
│ │ │ ├── error_handling.py
│ │ │ ├── mcp_logging.py
│ │ │ ├── rate_limiting_enhanced.py
│ │ │ └── security.py
│ │ ├── openapi_config.py
│ │ ├── routers
│ │ │ ├── __init__.py
│ │ │ ├── agents.py
│ │ │ ├── backtesting.py
│ │ │ ├── data_enhanced.py
│ │ │ ├── data.py
│ │ │ ├── health_enhanced.py
│ │ │ ├── health_tools.py
│ │ │ ├── health.py
│ │ │ ├── intelligent_backtesting.py
│ │ │ ├── introspection.py
│ │ │ ├── mcp_prompts.py
│ │ │ ├── monitoring.py
│ │ │ ├── news_sentiment_enhanced.py
│ │ │ ├── performance.py
│ │ │ ├── portfolio.py
│ │ │ ├── research.py
│ │ │ ├── screening_ddd.py
│ │ │ ├── screening_parallel.py
│ │ │ ├── screening.py
│ │ │ ├── technical_ddd.py
│ │ │ ├── technical_enhanced.py
│ │ │ ├── technical.py
│ │ │ └── tool_registry.py
│ │ ├── server.py
│ │ ├── services
│ │ │ ├── __init__.py
│ │ │ ├── base_service.py
│ │ │ ├── market_service.py
│ │ │ ├── portfolio_service.py
│ │ │ ├── prompt_service.py
│ │ │ └── resource_service.py
│ │ ├── simple_sse.py
│ │ └── utils
│ │ ├── __init__.py
│ │ ├── insomnia_export.py
│ │ └── postman_export.py
│ ├── application
│ │ ├── __init__.py
│ │ ├── commands
│ │ │ └── __init__.py
│ │ ├── dto
│ │ │ ├── __init__.py
│ │ │ └── technical_analysis_dto.py
│ │ ├── queries
│ │ │ ├── __init__.py
│ │ │ └── get_technical_analysis.py
│ │ └── screening
│ │ ├── __init__.py
│ │ ├── dtos.py
│ │ └── queries.py
│ ├── backtesting
│ │ ├── __init__.py
│ │ ├── ab_testing.py
│ │ ├── analysis.py
│ │ ├── batch_processing_stub.py
│ │ ├── batch_processing.py
│ │ ├── model_manager.py
│ │ ├── optimization.py
│ │ ├── persistence.py
│ │ ├── retraining_pipeline.py
│ │ ├── strategies
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── ml
│ │ │ │ ├── __init__.py
│ │ │ │ ├── adaptive.py
│ │ │ │ ├── ensemble.py
│ │ │ │ ├── feature_engineering.py
│ │ │ │ └── regime_aware.py
│ │ │ ├── ml_strategies.py
│ │ │ ├── parser.py
│ │ │ └── templates.py
│ │ ├── strategy_executor.py
│ │ ├── vectorbt_engine.py
│ │ └── visualization.py
│ ├── config
│ │ ├── __init__.py
│ │ ├── constants.py
│ │ ├── database_self_contained.py
│ │ ├── database.py
│ │ ├── llm_optimization_config.py
│ │ ├── logging_settings.py
│ │ ├── plotly_config.py
│ │ ├── security_utils.py
│ │ ├── security.py
│ │ ├── settings.py
│ │ ├── technical_constants.py
│ │ ├── tool_estimation.py
│ │ └── validation.py
│ ├── core
│ │ ├── __init__.py
│ │ ├── technical_analysis.py
│ │ └── visualization.py
│ ├── data
│ │ ├── __init__.py
│ │ ├── cache_manager.py
│ │ ├── cache.py
│ │ ├── django_adapter.py
│ │ ├── health.py
│ │ ├── models.py
│ │ ├── performance.py
│ │ ├── session_management.py
│ │ └── validation.py
│ ├── database
│ │ ├── __init__.py
│ │ ├── base.py
│ │ └── optimization.py
│ ├── dependencies.py
│ ├── domain
│ │ ├── __init__.py
│ │ ├── entities
│ │ │ ├── __init__.py
│ │ │ └── stock_analysis.py
│ │ ├── events
│ │ │ └── __init__.py
│ │ ├── portfolio.py
│ │ ├── screening
│ │ │ ├── __init__.py
│ │ │ ├── entities.py
│ │ │ ├── services.py
│ │ │ └── value_objects.py
│ │ ├── services
│ │ │ ├── __init__.py
│ │ │ └── technical_analysis_service.py
│ │ ├── stock_analysis
│ │ │ ├── __init__.py
│ │ │ └── stock_analysis_service.py
│ │ └── value_objects
│ │ ├── __init__.py
│ │ └── technical_indicators.py
│ ├── exceptions.py
│ ├── infrastructure
│ │ ├── __init__.py
│ │ ├── cache
│ │ │ └── __init__.py
│ │ ├── caching
│ │ │ ├── __init__.py
│ │ │ └── cache_management_service.py
│ │ ├── connection_manager.py
│ │ ├── data_fetching
│ │ │ ├── __init__.py
│ │ │ └── stock_data_service.py
│ │ ├── health
│ │ │ ├── __init__.py
│ │ │ └── health_checker.py
│ │ ├── persistence
│ │ │ ├── __init__.py
│ │ │ └── stock_repository.py
│ │ ├── providers
│ │ │ └── __init__.py
│ │ ├── screening
│ │ │ ├── __init__.py
│ │ │ └── repositories.py
│ │ └── sse_optimizer.py
│ ├── langchain_tools
│ │ ├── __init__.py
│ │ ├── adapters.py
│ │ └── registry.py
│ ├── logging_config.py
│ ├── memory
│ │ ├── __init__.py
│ │ └── stores.py
│ ├── monitoring
│ │ ├── __init__.py
│ │ ├── health_check.py
│ │ ├── health_monitor.py
│ │ ├── integration_example.py
│ │ ├── metrics.py
│ │ ├── middleware.py
│ │ └── status_dashboard.py
│ ├── providers
│ │ ├── __init__.py
│ │ ├── dependencies.py
│ │ ├── factories
│ │ │ ├── __init__.py
│ │ │ ├── config_factory.py
│ │ │ └── provider_factory.py
│ │ ├── implementations
│ │ │ ├── __init__.py
│ │ │ ├── cache_adapter.py
│ │ │ ├── macro_data_adapter.py
│ │ │ ├── market_data_adapter.py
│ │ │ ├── persistence_adapter.py
│ │ │ └── stock_data_adapter.py
│ │ ├── interfaces
│ │ │ ├── __init__.py
│ │ │ ├── cache.py
│ │ │ ├── config.py
│ │ │ ├── macro_data.py
│ │ │ ├── market_data.py
│ │ │ ├── persistence.py
│ │ │ └── stock_data.py
│ │ ├── llm_factory.py
│ │ ├── macro_data.py
│ │ ├── market_data.py
│ │ ├── mocks
│ │ │ ├── __init__.py
│ │ │ ├── mock_cache.py
│ │ │ ├── mock_config.py
│ │ │ ├── mock_macro_data.py
│ │ │ ├── mock_market_data.py
│ │ │ ├── mock_persistence.py
│ │ │ └── mock_stock_data.py
│ │ ├── openrouter_provider.py
│ │ ├── optimized_screening.py
│ │ ├── optimized_stock_data.py
│ │ └── stock_data.py
│ ├── README.md
│ ├── tests
│ │ ├── __init__.py
│ │ ├── README_INMEMORY_TESTS.md
│ │ ├── test_cache_debug.py
│ │ ├── test_fixes_validation.py
│ │ ├── test_in_memory_routers.py
│ │ ├── test_in_memory_server.py
│ │ ├── test_macro_data_provider.py
│ │ ├── test_mailgun_email.py
│ │ ├── test_market_calendar_caching.py
│ │ ├── test_mcp_tool_fixes_pytest.py
│ │ ├── test_mcp_tool_fixes.py
│ │ ├── test_mcp_tools.py
│ │ ├── test_models_functional.py
│ │ ├── test_server.py
│ │ ├── test_stock_data_enhanced.py
│ │ ├── test_stock_data_provider.py
│ │ └── test_technical_analysis.py
│ ├── tools
│ │ ├── __init__.py
│ │ ├── performance_monitoring.py
│ │ ├── portfolio_manager.py
│ │ ├── risk_management.py
│ │ └── sentiment_analysis.py
│ ├── utils
│ │ ├── __init__.py
│ │ ├── agent_errors.py
│ │ ├── batch_processing.py
│ │ ├── cache_warmer.py
│ │ ├── circuit_breaker_decorators.py
│ │ ├── circuit_breaker_services.py
│ │ ├── circuit_breaker.py
│ │ ├── data_chunking.py
│ │ ├── database_monitoring.py
│ │ ├── debug_utils.py
│ │ ├── fallback_strategies.py
│ │ ├── llm_optimization.py
│ │ ├── logging_example.py
│ │ ├── logging_init.py
│ │ ├── logging.py
│ │ ├── mcp_logging.py
│ │ ├── memory_profiler.py
│ │ ├── monitoring_middleware.py
│ │ ├── monitoring.py
│ │ ├── orchestration_logging.py
│ │ ├── parallel_research.py
│ │ ├── parallel_screening.py
│ │ ├── quick_cache.py
│ │ ├── resource_manager.py
│ │ ├── shutdown.py
│ │ ├── stock_helpers.py
│ │ ├── structured_logger.py
│ │ ├── tool_monitoring.py
│ │ ├── tracing.py
│ │ └── yfinance_pool.py
│ ├── validation
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── data.py
│ │ ├── middleware.py
│ │ ├── portfolio.py
│ │ ├── responses.py
│ │ ├── screening.py
│ │ └── technical.py
│ └── workflows
│ ├── __init__.py
│ ├── agents
│ │ ├── __init__.py
│ │ ├── market_analyzer.py
│ │ ├── optimizer_agent.py
│ │ ├── strategy_selector.py
│ │ └── validator_agent.py
│ ├── backtesting_workflow.py
│ └── state.py
├── PLANS.md
├── pyproject.toml
├── pyrightconfig.json
├── README.md
├── scripts
│ ├── dev.sh
│ ├── INSTALLATION_GUIDE.md
│ ├── load_example.py
│ ├── load_market_data.py
│ ├── load_tiingo_data.py
│ ├── migrate_db.py
│ ├── README_TIINGO_LOADER.md
│ ├── requirements_tiingo.txt
│ ├── run_stock_screening.py
│ ├── run-migrations.sh
│ ├── seed_db.py
│ ├── seed_sp500.py
│ ├── setup_database.sh
│ ├── setup_self_contained.py
│ ├── setup_sp500_database.sh
│ ├── test_seeded_data.py
│ ├── test_tiingo_loader.py
│ ├── tiingo_config.py
│ └── validate_setup.py
├── SECURITY.md
├── server.json
├── setup.py
├── tests
│ ├── __init__.py
│ ├── conftest.py
│ ├── core
│ │ └── test_technical_analysis.py
│ ├── data
│ │ └── test_portfolio_models.py
│ ├── domain
│ │ ├── conftest.py
│ │ ├── test_portfolio_entities.py
│ │ └── test_technical_analysis_service.py
│ ├── fixtures
│ │ └── orchestration_fixtures.py
│ ├── integration
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── README.md
│ │ ├── run_integration_tests.sh
│ │ ├── test_api_technical.py
│ │ ├── test_chaos_engineering.py
│ │ ├── test_config_management.py
│ │ ├── test_full_backtest_workflow_advanced.py
│ │ ├── test_full_backtest_workflow.py
│ │ ├── test_high_volume.py
│ │ ├── test_mcp_tools.py
│ │ ├── test_orchestration_complete.py
│ │ ├── test_portfolio_persistence.py
│ │ ├── test_redis_cache.py
│ │ ├── test_security_integration.py.disabled
│ │ └── vcr_setup.py
│ ├── performance
│ │ ├── __init__.py
│ │ ├── test_benchmarks.py
│ │ ├── test_load.py
│ │ ├── test_profiling.py
│ │ └── test_stress.py
│ ├── providers
│ │ └── test_stock_data_simple.py
│ ├── README.md
│ ├── test_agents_router_mcp.py
│ ├── test_backtest_persistence.py
│ ├── test_cache_management_service.py
│ ├── test_cache_serialization.py
│ ├── test_circuit_breaker.py
│ ├── test_database_pool_config_simple.py
│ ├── test_database_pool_config.py
│ ├── test_deep_research_functional.py
│ ├── test_deep_research_integration.py
│ ├── test_deep_research_parallel_execution.py
│ ├── test_error_handling.py
│ ├── test_event_loop_integrity.py
│ ├── test_exa_research_integration.py
│ ├── test_exception_hierarchy.py
│ ├── test_financial_search.py
│ ├── test_graceful_shutdown.py
│ ├── test_integration_simple.py
│ ├── test_langgraph_workflow.py
│ ├── test_market_data_async.py
│ ├── test_market_data_simple.py
│ ├── test_mcp_orchestration_functional.py
│ ├── test_ml_strategies.py
│ ├── test_optimized_research_agent.py
│ ├── test_orchestration_integration.py
│ ├── test_orchestration_logging.py
│ ├── test_orchestration_tools_simple.py
│ ├── test_parallel_research_integration.py
│ ├── test_parallel_research_orchestrator.py
│ ├── test_parallel_research_performance.py
│ ├── test_performance_optimizations.py
│ ├── test_production_validation.py
│ ├── test_provider_architecture.py
│ ├── test_rate_limiting_enhanced.py
│ ├── test_runner_validation.py
│ ├── test_security_comprehensive.py.disabled
│ ├── test_security_cors.py
│ ├── test_security_enhancements.py.disabled
│ ├── test_security_headers.py
│ ├── test_security_penetration.py
│ ├── test_session_management.py
│ ├── test_speed_optimization_validation.py
│ ├── test_stock_analysis_dependencies.py
│ ├── test_stock_analysis_service.py
│ ├── test_stock_data_fetching_service.py
│ ├── test_supervisor_agent.py
│ ├── test_supervisor_functional.py
│ ├── test_tool_estimation_config.py
│ ├── test_visualization.py
│ └── utils
│ ├── test_agent_errors.py
│ ├── test_logging.py
│ ├── test_parallel_screening.py
│ └── test_quick_cache.py
├── tools
│ ├── check_orchestration_config.py
│ ├── experiments
│ │ ├── validation_examples.py
│ │ └── validation_fixed.py
│ ├── fast_dev.sh
│ ├── hot_reload.py
│ ├── quick_test.py
│ └── templates
│ ├── new_router_template.py
│ ├── new_tool_template.py
│ ├── screening_strategy_template.py
│ └── test_template.py
└── uv.lock
```
# Files
--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------
```
1 | 3.12
2 |
```
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
```
1 | # Python
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 | *.so
6 | .Python
7 | .venv/
8 | venv/
9 | ENV/
10 | env/
11 | *.egg-info/
12 | dist/
13 | build/
14 | .pytest_cache/
15 | .coverage
16 | .mypy_cache/
17 | .ruff_cache/
18 |
19 | # Environment files
20 | .env
21 | .env.*
22 | !.env.example
23 |
24 | # Git
25 | .git/
26 | .gitignore
27 |
28 | # Docker
29 | Dockerfile
30 | docker-compose.yml
31 | .dockerignore
32 |
33 | # IDE
34 | .vscode/
35 | .idea/
36 | *.swp
37 | *.swo
38 | *~
39 |
40 | # OS
41 | .DS_Store
42 | Thumbs.db
43 |
44 | # Project specific
45 | *.log
46 | *.db
47 | *.sqlite
48 | *.sqlite3
49 | test_cache_debug.py
50 | test_market_calendar_caching.py
51 |
52 | # Documentation
53 | *.md
54 | !README.md
55 | docs/
56 |
57 | # CI/CD
58 | .github/
59 | .gitlab-ci.yml
60 | .travis.yml
```
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
1 | # Python bytecode
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # Distribution / packaging
7 | .Python
8 | build/
9 | develop-eggs/
10 | dist/
11 | downloads/
12 | eggs/
13 | .eggs/
14 | parts/
15 | sdist/
16 | var/
17 | wheels/
18 | *.egg-info/
19 | .installed.cfg
20 | *.egg
21 |
22 | # Unit test / coverage reports
23 | htmlcov/
24 | .tox/
25 | .coverage
26 | .coverage.*
27 | .cache
28 | nosetests.xml
29 | coverage.xml
30 | *.cover
31 | .hypothesis/
32 | .pytest_cache/
33 | tests/output/
34 | .ruff_cache/
35 |
36 | # Static analysis outputs
37 | pyright_analysis.txt
38 |
39 | # Jupyter Notebook
40 | .ipynb_checkpoints
41 |
42 | # Virtual environments
43 | .env
44 | .env.prod
45 | .env.local
46 | .venv
47 | env/
48 | venv/
49 | ENV/
50 | env.bak/
51 | venv.bak/
52 |
53 | # IDE files
54 | .idea/
55 | *.swp
56 | *.swo
57 |
58 | # OS specific files
59 | .DS_Store
60 | Thumbs.db
61 |
62 | # Project specific
63 | *.log
64 |
65 | # Test files in root (should be in tests/)
66 | /test_*.py
67 |
68 | # Generated API clients
69 | /generated/
70 | /openapi-spec.json
71 |
72 | # database
73 | *.db
74 | # Docker local overrides
75 | docker-compose.override.yml
76 |
```
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
```
1 | # MaverickMCP Environment Configuration Example
2 | # Copy this file to .env and update with your values
3 | # Personal stock analysis MCP server - no authentication or billing required
4 |
5 | # Application Settings
6 | APP_NAME=MaverickMCP
7 | ENVIRONMENT=development
8 | LOG_LEVEL=info
9 | API_VERSION=v1
10 |
11 | # API Settings
12 | API_HOST=0.0.0.0
13 | API_PORT=8000
14 | API_DEBUG=false
15 |
16 | # Database Settings (for stock data caching and storage)
17 | # For simple setup, use SQLite: sqlite:///maverick_mcp.db
18 | # For more performance, use PostgreSQL: postgresql://localhost/maverick_mcp_development
19 | DATABASE_URL=sqlite:///maverick_mcp.db
20 |
21 | # Redis Configuration (for caching market data)
22 | REDIS_HOST=localhost
23 | REDIS_PORT=6379
24 | REDIS_DB=0
25 | REDIS_PASSWORD=
26 | REDIS_SSL=false
27 |
28 | # Cache Configuration
29 | CACHE_TTL_SECONDS=604800 # 7 days
30 | CACHE_ENABLED=true
31 |
32 | # CORS Configuration (for local development)
33 | ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
34 |
35 | # Monitoring & Analytics (optional)
36 | SENTRY_DSN=https://[email protected]/project_id
37 |
38 | # Required API Keys
39 | # Get free Tiingo key at https://tiingo.com (500 requests/day free)
40 | TIINGO_API_KEY=your_tiingo_api_key_here
41 |
42 | # Optional API Keys
43 | # FRED_API_KEY=your_fred_api_key_here
44 | # OPENAI_API_KEY=your_openai_api_key_here
45 | # ANTHROPIC_API_KEY=your_anthropic_api_key_here
46 |
47 | # Web Search API Keys (for DeepResearchAgent)
48 | # Get Exa API key at https://exa.ai (free tier available)
49 | EXA_API_KEY=your_exa_api_key_here
50 | # Get Tavily API key at https://tavily.com (free tier available)
51 | TAVILY_API_KEY=your_tavily_api_key_here
52 |
53 | # OpenRouter API Key (for 400+ AI models with intelligent cost optimization)
54 | # Get key at https://openrouter.ai (pay-as-you-go pricing)
55 | OPENROUTER_API_KEY=your_openrouter_api_key_here
56 |
57 | # Yahoo Finance Configuration
58 | YFINANCE_TIMEOUT_SECONDS=30
59 |
60 | # Data Provider Settings
61 | DATA_PROVIDER_USE_CACHE=true
62 | DATA_PROVIDER_CACHE_DIR=/tmp/maverick_mcp/cache
63 | DATA_PROVIDER_CACHE_EXPIRY=86400
64 | DATA_PROVIDER_RATE_LIMIT=5
65 |
66 | # Rate Limiting (basic protection)
67 | RATE_LIMIT_PER_IP=100 # requests per minute
68 |
69 | # Feature Flags
70 | MAINTENANCE_MODE=false
```
--------------------------------------------------------------------------------
/maverick_mcp/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # Maverick-MCP Directory Structure
2 |
3 | ## Overview
4 |
5 | **⚠️ IMPORTANT FINANCIAL DISCLAIMER**: This software is for educational and informational purposes only. It is NOT financial advice. Always consult with a qualified financial advisor before making investment decisions.
6 |
7 | The Maverick-MCP package is organized into the following modules:
8 |
9 | - **core/**: Core client functionality and rate limiting
10 | - **api/**: MCP API server and client
11 | - **tools/**: Financial analysis tools
12 | - **providers/**: Data providers for stocks, market, and macro data
13 | - **data/**: Data handling utilities, including caching
14 | - **config/**: Configuration constants and settings
15 | - **cli/**: Command-line interface tools
16 | - **examples/**: Example scripts and usage patterns
17 |
18 | ## Module Details
19 |
20 | ### core/
21 |
22 | - `client.py` - Base Anthropic client implementation with rate limiting
23 | - `rate_limiter.py` - Anthropic API rate limiter
24 |
25 | ### api/
26 |
27 | - `mcp_client.py` - MCP protocol client implementation
28 | - `server.py` - FastMCP server implementation
29 |
30 | ### tools/
31 |
32 | - `portfolio_manager.py` - Portfolio management and optimization tools
33 |
34 | ### providers/
35 |
36 | - `stock_data.py` - Stock data provider utilities
37 | - `market_data.py` - Market data provider utilities
38 | - `macro_data.py` - Macroeconomic data provider utilities
39 |
40 | ### data/
41 |
42 | - `cache.py` - Cache implementation (Redis and in-memory)
43 |
44 | ### config/
45 |
46 | - `constants.py` - Configuration constants and environment variable handling
47 |
48 | ### cli/
49 |
50 | - `server.py` - Server CLI implementation
51 |
52 | ### examples/
53 |
54 | - Various example scripts showing how to use the Maverick-MCP tools
55 |
56 | ## Usage
57 |
58 | **Personal Use Only**: This server is designed for individual educational use with Claude Desktop.
59 |
60 | To start the Maverick-MCP server:
61 |
62 | ```bash
63 | # Recommended: Use the Makefile
64 | make dev
65 |
66 | # Alternative: Direct FastMCP server
67 | python -m maverick_mcp.api.server --transport streamable-http --port 8003
68 |
69 | # Development mode with hot reload
70 | ./scripts/dev.sh
71 | ```
72 |
73 | Note: The server will start using streamable-http transport on port 8003. The streamable-http transport is compatible with mcp-remote, while SSE transport is not (SSE requires GET requests but mcp-remote sends POST requests).
74 |
75 | When the server starts, you can access it at:
76 |
77 | - http://localhost:8003
78 |
79 | You can also start the server programmatically:
80 |
81 | ```python
82 | from maverick_mcp.api.server import mcp
83 |
84 | # Start the server with SSE transport
85 | # NOTE: All financial analysis tools include appropriate disclaimers
86 | mcp.run(transport="sse")
87 | ```
88 |
89 | ## Financial Analysis Tools
90 |
91 | MaverickMCP provides comprehensive financial analysis capabilities:
92 |
93 | ### Stock Data Tools
94 | - Historical price data with intelligent caching
95 | - Real-time quotes and market data
96 | - Company information and fundamentals
97 |
98 | ### Technical Analysis Tools
99 | - 20+ technical indicators (RSI, MACD, Bollinger Bands, etc.)
100 | - Support and resistance level identification
101 | - Trend analysis and pattern recognition
102 |
103 | ### Portfolio Tools
104 | - Risk assessment and correlation analysis
105 | - Portfolio optimization using Modern Portfolio Theory
106 | - Position sizing and risk management
107 |
108 | ### Screening Tools
109 | - Momentum-based stock screening
110 | - Breakout pattern identification
111 | - Custom filtering and ranking systems
112 |
113 | **All tools include appropriate financial disclaimers and are for educational purposes only.**
114 |
```
--------------------------------------------------------------------------------
/tests/integration/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # Integration Tests for MaverickMCP Orchestration
2 |
3 | This directory contains comprehensive integration tests for the multi-agent orchestration system implemented in MaverickMCP.
4 |
5 | ## Files
6 |
7 | - **`test_orchestration_complete.py`** - Comprehensive integration test suite with 18+ test scenarios
8 | - **`run_integration_tests.sh`** - Test runner script with environment setup
9 | - **`README.md`** - This documentation file
10 |
11 | ## Test Coverage
12 |
13 | ### Orchestration Tools Tested
14 |
15 | 1. **`agents_orchestrated_analysis`** - Multi-agent financial analysis with intelligent routing
16 | 2. **`agents_deep_research_financial`** - Web search-powered research with AI analysis
17 | 3. **`agents_compare_multi_agent_analysis`** - Multi-perspective agent comparison
18 |
19 | ### Test Categories
20 |
21 | - **Functional Tests** (12 scenarios) - Core functionality validation
22 | - **Error Handling** (3 scenarios) - Graceful error response testing
23 | - **Concurrent Execution** (3 scenarios) - Performance under concurrent load
24 | - **Performance Benchmarks** - Execution time and memory usage monitoring
25 |
26 | ## Usage
27 |
28 | ### Quick Test Run
29 |
30 | ```bash
31 | # From tests/integration directory
32 | ./run_integration_tests.sh
33 |
34 | # Or run directly
35 | python test_orchestration_complete.py
36 | ```
37 |
38 | ### From Project Root
39 |
40 | ```bash
41 | # Run integration tests
42 | cd tests/integration && ./run_integration_tests.sh
43 |
44 | # Run specific test with uv
45 | uv run python tests/integration/test_orchestration_complete.py
46 | ```
47 |
48 | ## Test Scenarios
49 |
50 | ### Orchestrated Analysis (4 tests)
51 | - Conservative LLM-powered routing
52 | - Aggressive rule-based routing
53 | - Moderate hybrid routing
54 | - Day trader fast execution
55 |
56 | ### Deep Research Financial (4 tests)
57 | - Basic company research
58 | - Standard sector research
59 | - Comprehensive market research
60 | - Exhaustive crypto research
61 |
62 | ### Multi-Agent Comparison (3 tests)
63 | - Market vs supervisor stock analysis
64 | - Conservative multi-agent portfolio
65 | - Aggressive growth strategy
66 |
67 | ### Error Handling (3 tests)
68 | - Invalid parameters for each tool
69 | - Graceful error response validation
70 | - Exception handling verification
71 |
72 | ### Performance Tests (3 tests)
73 | - Concurrent execution stress test
74 | - Memory usage monitoring
75 | - Response time benchmarking
76 |
77 | ## Expected Results
78 |
79 | **Successful Test Run:**
80 | ```
81 | 🎉 ALL TESTS PASSED! (18/18)
82 | Total Execution Time: 45.67s
83 | Average execution time: 2340ms
84 | ```
85 |
86 | **Performance Benchmarks:**
87 | - Orchestrated Analysis: ~1500ms average
88 | - Deep Research: ~25000ms average (includes web search)
89 | - Multi-Agent Comparison: ~3000ms average
90 |
91 | ## Test Configuration
92 |
93 | Tests are configured in `test_orchestration_complete.py`:
94 |
95 | ```python
96 | TEST_CONFIG = {
97 | "timeout_seconds": 300, # 5 minutes max per test
98 | "concurrent_limit": 3, # Maximum concurrent tests
99 | "performance_monitoring": True,
100 | "detailed_validation": True,
101 | "save_results": True,
102 | }
103 | ```
104 |
105 | ## Output Files
106 |
107 | - **Log file**: `integration_test_YYYYMMDD_HHMMSS.log`
108 | - **Results file**: `integration_test_results_YYYYMMDD_HHMMSS.json`
109 |
110 | ## Requirements
111 |
112 | - Python 3.12+
113 | - All MaverickMCP dependencies installed
114 | - Optional: OPENAI_API_KEY for real LLM calls
115 | - Optional: EXA_API_KEY, TAVILY_API_KEY for web search testing
116 |
117 | ## Troubleshooting
118 |
119 | **Import Errors:**
120 | - Ensure you're running from the correct directory
121 | - Check that all dependencies are installed: `uv sync`
122 |
123 | **API Errors:**
124 | - Tests use mock responses if API keys aren't configured
125 | - Add API keys to `.env` file for full functionality testing
126 |
127 | **Timeout Errors:**
128 | - Increase `timeout_seconds` in TEST_CONFIG for slower systems
129 | - Some tests (especially deep research) take 20-30 seconds
130 |
131 | ## Integration with CI/CD
132 |
133 | The test suite returns proper exit codes:
134 | - `0` - All tests passed
135 | - `1` - Some tests failed
136 | - `2` - Test suite execution failed
137 | - `130` - Interrupted by user (SIGINT)
138 |
139 | Example CI usage:
140 | ```yaml
141 | - name: Run Integration Tests
142 | run: |
143 | cd tests/integration
144 | ./run_integration_tests.sh
145 | ```
```
--------------------------------------------------------------------------------
/tests/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # MaverickMCP Test Suite
2 |
3 | This comprehensive test suite covers both **Phase 5.1 (End-to-End Integration Tests)** and **Phase 5.2 (Performance Testing Suite)** for the VectorBT backtesting system.
4 |
5 | ## Overview
6 |
7 | The test suite includes:
8 |
9 | ### Phase 5.1: End-to-End Integration Tests
10 | - **Complete workflow integration** from data fetch to results visualization
11 | - **All 15 strategies testing** (9 traditional + 6 ML strategies)
12 | - **Parallel execution capabilities** with concurrency testing
13 | - **Cache behavior optimization** and performance validation
14 | - **MCP tools integration** for Claude Desktop interaction
15 | - **High-volume production scenarios** with 100+ symbols
16 | - **Chaos engineering** for resilience testing
17 |
18 | ### Phase 5.2: Performance Testing Suite
19 | - **Load testing** for 10, 50, and 100 concurrent users
20 | - **Benchmark testing** against performance targets
21 | - **Stress testing** for resource usage monitoring
22 | - **Profiling** for bottleneck identification
23 |
24 | ## Test Structure
25 |
26 | ```
27 | tests/
28 | ├── integration/ # Phase 5.1: Integration Tests
29 | │ ├── test_full_backtest_workflow_advanced.py
30 | │ ├── test_mcp_tools.py
31 | │ ├── test_high_volume.py
32 | │ └── test_chaos_engineering.py
33 | ├── performance/ # Phase 5.2: Performance Tests
34 | │ ├── test_load.py
35 | │ ├── test_benchmarks.py
36 | │ ├── test_stress.py
37 | │ └── test_profiling.py
38 | ├── conftest.py # Shared fixtures and configuration
39 | └── README.md # This file
40 | ```
41 |
42 | ## Quick Start
43 |
44 | ### Running All Tests
45 |
46 | ```bash
47 | # Run all integration and performance tests
48 | make test-full
49 |
50 | # Run only integration tests
51 | pytest tests/integration/ -v
52 |
53 | # Run only performance tests
54 | pytest tests/performance/ -v
55 | ```
56 |
57 | ### Running Specific Test Categories
58 |
59 | ```bash
60 | # Integration tests
61 | pytest tests/integration/test_full_backtest_workflow_advanced.py -v
62 | pytest tests/integration/test_mcp_tools.py -v
63 | pytest tests/integration/test_high_volume.py -v
64 | pytest tests/integration/test_chaos_engineering.py -v
65 |
66 | # Performance tests
67 | pytest tests/performance/test_load.py -v
68 | pytest tests/performance/test_benchmarks.py -v
69 | pytest tests/performance/test_stress.py -v
70 | pytest tests/performance/test_profiling.py -v
71 | ```
72 |
73 | ## Test Categories Detailed
74 |
75 | ### Integration Tests
76 |
77 | #### 1. Advanced Full Backtest Workflow (`test_full_backtest_workflow_advanced.py`)
78 | - **All 15 strategies integration testing** (traditional + ML)
79 | - **Parallel execution capabilities** with async performance
80 | - **Cache behavior optimization** and hit rate validation
81 | - **Database persistence integration** with PostgreSQL
82 | - **Visualization integration** with chart generation
83 | - **Error recovery mechanisms** across the workflow
84 | - **Resource management** and cleanup testing
85 | - **Memory leak prevention** validation
86 |
87 | **Key Tests:**
88 | - `test_all_15_strategies_integration()` - Tests all available strategies
89 | - `test_parallel_execution_capabilities()` - Concurrent backtest execution
90 | - `test_cache_behavior_and_optimization()` - Cache efficiency validation
91 | - `test_resource_management_comprehensive()` - Memory and thread management
92 |
93 | #### 2. MCP Tools Integration (`test_mcp_tools.py`)
94 | - **All MCP tool registrations** for Claude Desktop
95 | - **Tool parameter validation** and error handling
96 | - **Tool response formats** and data integrity
97 | - **Claude Desktop simulation** with realistic usage patterns
98 | - **Performance and timeout handling** for MCP calls
99 |
100 | **Key Tests:**
101 | - `test_all_mcp_tools_registration()` - Validates all tools are registered
102 | - `test_run_backtest_tool_comprehensive()` - Core backtesting tool validation
103 | - `test_claude_desktop_simulation()` - Realistic usage pattern simulation
104 |
105 | #### 3. High Volume Production Scenarios (`test_high_volume.py`)
106 | - **Large symbol set backtesting** (100+ symbols)
107 | - **Multi-year historical data** processing
108 | - **Memory management under load** with leak detection
109 | - **Concurrent user scenarios** simulation
110 | - **Database performance under load** testing
111 | - **Cache efficiency** with large datasets
112 |
113 | **Key Tests:**
114 | - `test_large_symbol_set_backtesting()` - 100+ symbol processing
115 | - `test_concurrent_user_scenarios()` - Multi-user simulation
116 | - `test_memory_management_large_datasets()` - Memory leak prevention
117 |
118 | #### 4. Chaos Engineering (`test_chaos_engineering.py`)
119 | - **API failures and recovery** mechanisms
120 | - **Database connection drops** and reconnection
121 | - **Cache failures and fallback** behavior
122 | - **Circuit breaker behavior** under load
123 | - **Network instability** injection
124 | - **Memory pressure scenarios** testing
125 | - **CPU overload situations** handling
126 | - **Cascading failure recovery** validation
127 |
128 | **Key Tests:**
129 | - `test_api_failures_and_recovery()` - API resilience testing
130 | - `test_circuit_breaker_behavior()` - Circuit breaker validation
131 | - `test_cascading_failure_recovery()` - Multi-component failure handling
132 |
133 | ### Performance Tests
134 |
135 | #### 1. Load Testing (`test_load.py`)
136 | - **Concurrent user load testing** (10, 50, 100 users)
137 | - **Response time and throughput** measurement
138 | - **Memory usage under load** monitoring
139 | - **Database performance** with multiple connections
140 | - **System stability** under sustained load
141 |
142 | **Performance Targets:**
143 | - 10 users: ≥2.0 req/s, ≤5.0s avg response time
144 | - 50 users: ≥5.0 req/s, ≤8.0s avg response time
145 | - 100 users: ≥3.0 req/s, ≤15.0s avg response time
146 |
147 | **Key Tests:**
148 | - `test_concurrent_users_10()`, `test_concurrent_users_50()`, `test_concurrent_users_100()`
149 | - `test_load_scalability_analysis()` - Performance scaling analysis
150 | - `test_sustained_load_stability()` - Long-duration stability testing
151 |
152 | #### 2. Benchmark Testing (`test_benchmarks.py`)
153 | - **Backtest execution < 2 seconds** per backtest
154 | - **Memory usage < 500MB** per backtest
155 | - **Cache hit rate > 80%** efficiency
156 | - **API failure rate < 0.1%** reliability
157 | - **Database query performance < 100ms** speed
158 | - **Response time SLA compliance** validation
159 |
160 | **Key Benchmarks:**
161 | - Execution time targets
162 | - Memory efficiency targets
163 | - Cache performance targets
164 | - Database performance targets
165 | - SLA compliance targets
166 |
167 | **Key Tests:**
168 | - `test_backtest_execution_time_benchmark()` - Speed validation
169 | - `test_memory_usage_benchmark()` - Memory efficiency
170 | - `test_cache_hit_rate_benchmark()` - Cache performance
171 | - `test_comprehensive_benchmark_suite()` - Full benchmark report
172 |
173 | #### 3. Stress Testing (`test_stress.py`)
174 | - **Sustained load testing** (15+ minutes)
175 | - **Memory leak detection** over time
176 | - **CPU utilization monitoring** under stress
177 | - **Database connection pool** exhaustion testing
178 | - **File descriptor limits** testing
179 | - **Queue overflow scenarios** handling
180 |
181 | **Key Tests:**
182 | - `test_sustained_load_15_minutes()` - Extended load testing
183 | - `test_memory_leak_detection()` - Memory leak validation
184 | - `test_cpu_stress_resilience()` - CPU stress handling
185 | - `test_database_connection_stress()` - DB connection pool testing
186 |
187 | #### 4. Profiling and Bottleneck Identification (`test_profiling.py`)
188 | - **CPU profiling** with cProfile integration
189 | - **Memory allocation hotspots** identification
190 | - **Database query performance** analysis
191 | - **I/O vs CPU-bound** operation analysis
192 | - **Optimization recommendations** generation
193 |
194 | **Key Tests:**
195 | - `test_profile_backtest_execution()` - CPU bottleneck identification
196 | - `test_profile_database_query_performance()` - DB query analysis
197 | - `test_profile_memory_allocation_patterns()` - Memory optimization
198 | - `test_comprehensive_profiling_suite()` - Full profiling report
199 |
200 | ## Performance Targets
201 |
202 | ### Execution Performance
203 | - **Backtest execution**: < 2 seconds per backtest
204 | - **Data loading**: < 0.5 seconds average
205 | - **Database saves**: < 50ms average
206 | - **Database queries**: < 20ms average
207 |
208 | ### Throughput Targets
209 | - **Sequential**: ≥ 2.0 backtests/second
210 | - **Concurrent**: ≥ 5.0 backtests/second
211 | - **10 concurrent users**: ≥ 2.0 requests/second
212 | - **50 concurrent users**: ≥ 5.0 requests/second
213 |
214 | ### Resource Efficiency
215 | - **Memory usage**: < 500MB per backtest
216 | - **Memory growth**: < 100MB/hour sustained
217 | - **Cache hit rate**: > 80%
218 | - **API failure rate**: < 0.1%
219 |
220 | ### Response Time SLA
221 | - **50th percentile**: < 1.5 seconds
222 | - **95th percentile**: < 3.0 seconds
223 | - **99th percentile**: < 5.0 seconds
224 | - **SLA compliance**: > 95% of requests
225 |
226 | ## Test Configuration
227 |
228 | ### Environment Setup
229 | All tests use containerized PostgreSQL and Redis for consistency:
230 |
231 | ```python
232 | # Automatic container setup in conftest.py
233 | @pytest.fixture(scope="session")
234 | def postgres_container():
235 | with PostgresContainer("postgres:15-alpine") as postgres:
236 | yield postgres
237 |
238 | @pytest.fixture(scope="session")
239 | def redis_container():
240 | with RedisContainer("redis:7-alpine") as redis:
241 | yield redis
242 | ```
243 |
244 | ### Mock Data Providers
245 | Tests use optimized mock data providers for consistent, fast testing:
246 |
247 | ```python
248 | # Realistic stock data generation
249 | def generate_stock_data(symbol: str) -> pd.DataFrame:
250 | # 3 years of realistic OHLCV data
251 | # Different market regimes (bull, sideways, bear)
252 | # Deterministic but varied based on symbol hash
253 | ```
254 |
255 | ### Parallel Execution
256 | Tests are designed for parallel execution where possible:
257 |
258 | ```python
259 | # Concurrent backtest execution
260 | async def run_parallel_backtests(symbols, strategies):
261 | semaphore = asyncio.Semaphore(8) # Control concurrency
262 | tasks = [run_with_semaphore(backtest) for backtest in all_backtests]
263 | results = await asyncio.gather(*tasks, return_exceptions=True)
264 | ```
265 |
266 | ## Running Tests in CI/CD
267 |
268 | ### GitHub Actions Configuration
269 | ```yaml
270 | - name: Run Integration Tests
271 | run: |
272 | pytest tests/integration/ -v --tb=short --timeout=600
273 |
274 | - name: Run Performance Tests
275 | run: |
276 | pytest tests/performance/ -v --tb=short --timeout=1800
277 | ```
278 |
279 | ### Test Markers
280 | ```bash
281 | # Run only fast tests
282 | pytest -m "not slow"
283 |
284 | # Run only integration tests
285 | pytest -m integration
286 |
287 | # Run only performance tests
288 | pytest -m performance
289 |
290 | # Run stress tests (extended duration)
291 | pytest -m stress
292 | ```
293 |
294 | ## Expected Test Results
295 |
296 | ### Integration Test Results
297 | - **Strategy Coverage**: All 15 strategies (9 traditional + 6 ML) tested
298 | - **Success Rate**: ≥ 80% success rate across all tests
299 | - **Parallel Efficiency**: ≥ 2x speedup with concurrent execution
300 | - **Error Recovery**: Graceful handling of all failure scenarios
301 |
302 | ### Performance Test Results
303 | - **Load Testing**: Successful handling of 100 concurrent users
304 | - **Benchmark Compliance**: ≥ 80% of benchmarks passed
305 | - **Stress Testing**: Stable operation under extended load
306 | - **Profiling**: Identification of optimization opportunities
307 |
308 | ## Troubleshooting
309 |
310 | ### Common Issues
311 |
312 | #### Test Timeouts
313 | ```bash
314 | # Increase timeout for long-running tests
315 | pytest tests/performance/test_stress.py --timeout=1800
316 | ```
317 |
318 | #### Memory Issues
319 | ```bash
320 | # Monitor memory usage during tests
321 | pytest tests/integration/test_high_volume.py -s --tb=short
322 | ```
323 |
324 | #### Database Connection Issues
325 | ```bash
326 | # Check container status
327 | docker ps | grep postgres
328 | docker logs <container_id>
329 | ```
330 |
331 | #### Performance Assertion Failures
332 | Check the test output for specific performance metrics that failed and compare against targets.
333 |
334 | ### Debug Mode
335 | ```bash
336 | # Run with detailed logging
337 | pytest tests/ -v -s --log-cli-level=INFO
338 |
339 | # Run specific test with profiling
340 | pytest tests/performance/test_profiling.py::test_comprehensive_profiling_suite -v -s
341 | ```
342 |
343 | ## Contributing
344 |
345 | When adding new tests:
346 |
347 | 1. **Follow the existing patterns** for fixtures and mocks
348 | 2. **Add appropriate performance assertions** with clear targets
349 | 3. **Include comprehensive logging** for debugging
350 | 4. **Document expected behavior** and performance characteristics
351 | 5. **Use realistic test data** that represents production scenarios
352 |
353 | ### Test Categories
354 | - Mark integration tests with `@pytest.mark.integration`
355 | - Mark slow tests with `@pytest.mark.slow`
356 | - Mark performance tests with `@pytest.mark.performance`
357 | - Mark stress tests with `@pytest.mark.stress`
358 |
359 | ## Results and Reporting
360 |
361 | ### Test Reports
362 | All tests generate comprehensive reports including:
363 | - Performance metrics and benchmarks
364 | - Resource usage analysis
365 | - Error rates and success rates
366 | - Optimization recommendations
367 |
368 | ### Performance Dashboards
369 | Key metrics are logged for dashboard visualization:
370 | - Execution times and throughput
371 | - Memory usage patterns
372 | - Database performance
373 | - Cache hit rates
374 | - Error rates and recovery times
375 |
376 | This comprehensive test suite ensures the MaverickMCP backtesting system meets all performance and reliability requirements for production use.
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # MaverickMCP - Personal Stock Analysis MCP Server
2 |
3 | [](https://opensource.org/licenses/MIT)
4 | [](https://www.python.org/downloads/)
5 | [](https://github.com/jlowin/fastmcp)
6 | [](https://github.com/wshobson/maverick-mcp)
7 | [](https://github.com/wshobson/maverick-mcp/issues)
8 | [](https://github.com/wshobson/maverick-mcp/network/members)
9 |
10 | **MaverickMCP** is a personal-use FastMCP 2.0 server that provides professional-grade financial data analysis, technical indicators, and portfolio optimization tools directly to your Claude Desktop interface. Built for individual traders and investors, it offers comprehensive stock analysis capabilities without any authentication or billing complexity.
11 |
12 | The server comes pre-seeded with all 520 S&P 500 stocks and provides advanced screening recommendations across multiple strategies. It runs locally with HTTP/SSE/STDIO transport options for seamless integration with Claude Desktop and other MCP clients.
13 |
14 | ## Why MaverickMCP?
15 |
16 | MaverickMCP provides professional-grade financial analysis tools directly within your Claude Desktop interface. Perfect for individual traders and investors who want comprehensive stock analysis capabilities without the complexity of expensive platforms or commercial services.
17 |
18 | **Key Benefits:**
19 |
20 | - **No Setup Complexity**: Simple `make dev` command gets you running (or `uv sync` + `make dev`)
21 | - **Modern Python Tooling**: Built with `uv` for lightning-fast dependency management
22 | - **Claude Desktop Integration**: Native MCP support for seamless AI-powered analysis
23 | - **Comprehensive Analysis**: 29+ financial tools covering technical indicators, screening, and portfolio optimization
24 | - **Smart Caching**: Redis-powered performance with graceful fallbacks
25 | - **Fast Development**: Hot reload, smart error handling, and parallel processing
26 | - **Open Source**: MIT licensed, community-driven development
27 | - **Educational Focus**: Perfect for learning financial analysis and MCP development
28 |
29 | ## Features
30 |
31 | - **Pre-seeded Database**: 520 S&P 500 stocks with comprehensive screening recommendations
32 | - **Advanced Backtesting**: VectorBT-powered engine with 15+ built-in strategies and ML algorithms
33 | - **Fast Development**: Comprehensive Makefile, smart error handling, hot reload, and parallel processing
34 | - **Stock Data Access**: Historical and real-time stock data with intelligent caching
35 | - **Technical Analysis**: 20+ indicators including SMA, EMA, RSI, MACD, Bollinger Bands, and more
36 | - **Stock Screening**: Multiple strategies (Maverick Bullish/Bearish, Trending Breakouts) with parallel processing
37 | - **Portfolio Tools**: Correlation analysis, returns calculation, and optimization
38 | - **Market Data**: Sector performance, market movers, and earnings information
39 | - **Smart Caching**: Redis-powered performance with automatic fallback to in-memory storage
40 | - **Database Support**: SQLAlchemy integration with PostgreSQL/SQLite (defaults to SQLite)
41 | - **Multi-Transport Support**: HTTP, SSE, and STDIO transports for all MCP clients
42 |
43 | ## Quick Start
44 |
45 | ### Prerequisites
46 |
47 | - **Python 3.12+**: Core runtime environment
48 | - **[uv](https://docs.astral.sh/uv/)**: Modern Python package manager (recommended)
49 | - **TA-Lib**: Technical analysis library for advanced indicators
50 | - Redis (optional, for enhanced caching)
51 | - PostgreSQL or SQLite (optional, for data persistence)
52 |
53 | #### Installing TA-Lib
54 |
55 | TA-Lib is required for technical analysis calculations.
56 |
57 | **macOS and Linux (Homebrew):**
58 | ```bash
59 | brew install ta-lib
60 | ```
61 |
62 | **Windows (Multiple Options):**
63 |
64 | **Option 1: Conda/Anaconda (Recommended - Easiest)**
65 | ```bash
66 | conda install -c conda-forge ta-lib
67 | ```
68 |
69 | **Option 2: Pre-compiled Wheels**
70 | 1. Download the appropriate wheel for your Python version from:
71 | - [cgohlke/talib-build releases](https://github.com/cgohlke/talib-build/releases)
72 | - Choose the file matching your Python version (e.g., `TA_Lib-0.4.28-cp312-cp312-win_amd64.whl` for Python 3.12 64-bit)
73 | 2. Install using pip:
74 | ```bash
75 | pip install path/to/downloaded/TA_Lib-X.X.X-cpXXX-cpXXX-win_amd64.whl
76 | ```
77 |
78 | **Option 3: Alternative Pre-compiled Package**
79 | ```bash
80 | pip install TA-Lib-Precompiled
81 | ```
82 |
83 | **Option 4: Build from Source (Advanced)**
84 | If other methods fail, you can build from source:
85 | 1. Install Microsoft C++ Build Tools
86 | 2. Download and extract ta-lib C library to `C:\ta-lib`
87 | 3. Build using Visual Studio tools
88 | 4. Run `pip install ta-lib`
89 |
90 | **Verification:**
91 | Test your installation:
92 | ```bash
93 | python -c "import talib; print(talib.__version__)"
94 | ```
95 |
96 | #### Installing uv (Recommended)
97 |
98 | ```bash
99 | # macOS/Linux
100 | curl -LsSf https://astral.sh/uv/install.sh | sh
101 |
102 | # Windows
103 | powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
104 |
105 | # Alternative: via pip
106 | pip install uv
107 | ```
108 |
109 | ### Installation
110 |
111 | #### Option 1: Using uv (Recommended - Fastest)
112 |
113 | ```bash
114 | # Clone the repository
115 | git clone https://github.com/wshobson/maverick-mcp.git
116 | cd maverick-mcp
117 |
118 | # Install dependencies and create virtual environment in one command
119 | uv sync
120 |
121 | # Copy environment template
122 | cp .env.example .env
123 | # Add your Tiingo API key (free at tiingo.com)
124 | ```
125 |
126 | #### Option 2: Using pip (Traditional)
127 |
128 | ```bash
129 | # Clone the repository
130 | git clone https://github.com/wshobson/maverick-mcp.git
131 | cd maverick-mcp
132 |
133 | # Create virtual environment and install
134 | python -m venv .venv
135 | source .venv/bin/activate # On Windows: .venv\Scripts\activate
136 | pip install -e .
137 |
138 | # Copy environment template
139 | cp .env.example .env
140 | # Add your Tiingo API key (free at tiingo.com)
141 | ```
142 |
143 | ### Start the Server
144 |
145 | ```bash
146 | # One command to start everything (includes S&P 500 data seeding on first run)
147 | make dev
148 |
149 | # The server is now running with:
150 | # - HTTP endpoint: http://localhost:8003/mcp/
151 | # - SSE endpoint: http://localhost:8003/sse/
152 | # - 520 S&P 500 stocks pre-loaded with screening data
153 | ```
154 |
155 | ### Connect to Claude Desktop
156 |
157 | **Recommended: SSE Connection (Stable and Reliable)**
158 |
159 | This configuration provides stable tool registration and prevents tools from disappearing:
160 |
161 | ```json
162 | {
163 | "mcpServers": {
164 | "maverick-mcp": {
165 | "command": "npx",
166 | "args": ["-y", "mcp-remote", "http://localhost:8003/sse/"]
167 | }
168 | }
169 | }
170 | ```
171 |
172 | > **Important**: Note the trailing slash in `/sse/` - this is REQUIRED to prevent redirect issues!
173 |
174 | **Config File Location:**
175 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
176 | - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
177 |
178 | **Why This Configuration Works Best:**
179 | - Stable tool registration - tools don't disappear after initial connection
180 | - Reliable connection management through SSE transport
181 | - Proper session persistence for long-running analysis tasks
182 | - All 29+ financial tools available consistently
183 |
184 | **Alternative: Direct STDIO Connection (Development Only)**
185 |
186 | ```json
187 | {
188 | "mcpServers": {
189 | "maverick-mcp": {
190 | "command": "uv",
191 | "args": [
192 | "run",
193 | "python",
194 | "-m",
195 | "maverick_mcp.api.server",
196 | "--transport",
197 | "stdio"
198 | ],
199 | "cwd": "/path/to/maverick-mcp"
200 | }
201 | }
202 | }
203 | ```
204 |
205 | > **Important**: Always **restart Claude Desktop** after making configuration changes. The SSE configuration via mcp-remote has been tested and confirmed to provide stable, persistent tool access without connection drops.
206 |
207 | That's it! MaverickMCP tools will now be available in your Claude Desktop interface.
208 |
209 | #### Claude Desktop (Most Popular) - Recommended Configuration
210 |
211 | **Config Location**:
212 |
213 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
214 | - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
215 |
216 | #### Cursor IDE - STDIO and SSE
217 |
218 | **Option 1: STDIO (via mcp-remote)**:
219 |
220 | ```json
221 | {
222 | "mcpServers": {
223 | "maverick-mcp": {
224 | "command": "npx",
225 | "args": ["-y", "mcp-remote", "http://localhost:8003/sse/"]
226 | }
227 | }
228 | }
229 | ```
230 |
231 | **Option 2: Direct SSE**:
232 |
233 | ```json
234 | {
235 | "mcpServers": {
236 | "maverick-mcp": {
237 | "url": "http://localhost:8003/sse/"
238 | }
239 | }
240 | }
241 | ```
242 |
243 | **Config Location**: Cursor → Settings → MCP Servers
244 |
245 | #### Claude Code CLI - All Transports
246 |
247 | **HTTP Transport (Recommended)**:
248 |
249 | ```bash
250 | claude mcp add --transport http maverick-mcp http://localhost:8003/mcp/
251 | ```
252 |
253 | **SSE Transport (Alternative)**:
254 |
255 | ```bash
256 | claude mcp add --transport sse maverick-mcp http://localhost:8003/sse/
257 | ```
258 |
259 | **STDIO Transport (Development)**:
260 |
261 | ```bash
262 | claude mcp add maverick-mcp uv run python -m maverick_mcp.api.server --transport stdio
263 | ```
264 |
265 | #### Windsurf IDE - STDIO and SSE
266 |
267 | **Option 1: STDIO (via mcp-remote)**:
268 |
269 | ```json
270 | {
271 | "mcpServers": {
272 | "maverick-mcp": {
273 | "command": "npx",
274 | "args": ["-y", "mcp-remote", "http://localhost:8003/mcp/"]
275 | }
276 | }
277 | }
278 | ```
279 |
280 | **Option 2: Direct SSE**:
281 |
282 | ```json
283 | {
284 | "mcpServers": {
285 | "maverick-mcp": {
286 | "serverUrl": "http://localhost:8003/sse/"
287 | }
288 | }
289 | }
290 | ```
291 |
292 | **Config Location**: Windsurf → Settings → Advanced Settings → MCP Servers
293 |
294 | #### Why mcp-remote is Needed
295 |
296 | The `mcp-remote` tool bridges the gap between STDIO-only clients (like Claude Desktop) and HTTP/SSE servers. Without it, these clients cannot connect to remote MCP servers:
297 |
298 | - **Without mcp-remote**: Client tries STDIO → Server expects HTTP → Connection fails
299 | - **With mcp-remote**: Client uses STDIO → mcp-remote converts to HTTP → Server receives HTTP → Success
300 |
301 | ## Available Tools
302 |
303 | MaverickMCP provides 39+ financial analysis tools organized into focused categories, including advanced AI-powered research agents:
304 |
305 | ### Development Commands
306 |
307 | ```bash
308 | # Start the server (one command!)
309 | make dev
310 |
311 | # Alternative startup methods
312 | ./scripts/start-backend.sh --dev # Script-based startup
313 | ./tools/fast_dev.sh # Ultra-fast startup (< 3 seconds)
314 | uv run python tools/hot_reload.py # Auto-restart on file changes
315 |
316 | # Server will be available at:
317 | # - HTTP endpoint: http://localhost:8003/mcp/ (streamable-http - use with mcp-remote)
318 | # - SSE endpoint: http://localhost:8003/sse/ (SSE - direct connection only, not mcp-remote)
319 | # - Health check: http://localhost:8003/health
320 | ```
321 |
322 | ### Testing
323 |
324 | ```bash
325 | # Quick test commands
326 | make test # Run unit tests (5-10 seconds)
327 | make test-specific TEST=test_name # Run specific test
328 | make test-watch # Auto-run tests on file changes
329 |
330 | # Using uv (recommended)
331 | uv run pytest # Unit tests only
332 | uv run pytest --cov=maverick_mcp # With coverage
333 | uv run pytest -m "" # All tests (requires PostgreSQL/Redis)
334 |
335 | # Alternative: Direct pytest (if activated in venv)
336 | pytest # Unit tests only
337 | pytest --cov=maverick_mcp # With coverage
338 | pytest -m "" # All tests (requires PostgreSQL/Redis)
339 | ```
340 |
341 | ### Code Quality
342 |
343 | ```bash
344 | # Quick quality commands
345 | make lint # Check code quality (ruff)
346 | make format # Auto-format code (ruff)
347 | make typecheck # Run type checking (ty)
348 |
349 | # Using uv (recommended)
350 | uv run ruff check . # Linting
351 | uv run ruff format . # Formatting
352 | uv run ty check . # Type checking (Astral's modern type checker)
353 |
354 | # Alternative: Direct commands (if activated in venv)
355 | ruff check . # Linting
356 | ruff format . # Formatting
357 | ty check . # Type checking
358 |
359 | # Ultra-fast one-liner (no installation needed)
360 | uvx ty check . # Run ty directly without installing
361 | ```
362 |
363 | ## Configuration
364 |
365 | Configure MaverickMCP via `.env` file or environment variables:
366 |
367 | **Essential Settings:**
368 |
369 | - `REDIS_HOST`, `REDIS_PORT` - Redis cache (optional, defaults to localhost:6379)
370 | - `DATABASE_URL` - PostgreSQL connection or `sqlite:///maverick_mcp.db` for SQLite (default)
371 | - `LOG_LEVEL` - Logging verbosity (INFO, DEBUG, ERROR)
372 | - S&P 500 data automatically seeds on first startup
373 |
374 | **Required API Keys:**
375 |
376 | - `TIINGO_API_KEY` - Stock data provider (free tier available at [tiingo.com](https://tiingo.com))
377 |
378 | **Optional API Keys:**
379 |
380 | - `OPENROUTER_API_KEY` - **Strongly Recommended for Research**: Access to 400+ AI models with intelligent cost optimization (40-60% cost savings)
381 | - `EXA_API_KEY` - **Recommended for Research**: Web search capabilities for comprehensive research
382 | - `OPENAI_API_KEY` - Direct OpenAI access (fallback)
383 | - `ANTHROPIC_API_KEY` - Direct Anthropic access (fallback)
384 | - `FRED_API_KEY` - Federal Reserve economic data
385 | - `TAVILY_API_KEY` - Alternative web search provider
386 |
387 | **Performance:**
388 |
389 | - `CACHE_ENABLED=true` - Enable Redis caching
390 | - `CACHE_TTL_SECONDS=3600` - Cache duration
391 |
392 | ## Usage Examples
393 |
394 | ### Backtesting Example
395 |
396 | Once connected to Claude Desktop, you can use natural language to run backtests:
397 |
398 | ```
399 | "Run a backtest on AAPL using the momentum strategy for the last 6 months"
400 |
401 | "Compare the performance of mean reversion vs trend following strategies on SPY"
402 |
403 | "Optimize the RSI strategy parameters for TSLA with walk-forward analysis"
404 |
405 | "Show me the Sharpe ratio and maximum drawdown for a portfolio of tech stocks using the adaptive ML strategy"
406 |
407 | "Generate a detailed backtest report for the ensemble strategy on the S&P 500 sectors"
408 | ```
409 |
410 | ### Technical Analysis Example
411 |
412 | ```
413 | "Show me the RSI and MACD analysis for NVDA"
414 |
415 | "Identify support and resistance levels for MSFT"
416 |
417 | "Get full technical analysis for the top 5 momentum stocks"
418 | ```
419 |
420 | ### Portfolio Management Example (NEW)
421 |
422 | ```
423 | "Add 10 shares of AAPL I bought at $150.50"
424 |
425 | "Show me my portfolio with current prices"
426 |
427 | "Compare my portfolio holdings" # No tickers needed!
428 |
429 | "Analyze correlation in my portfolio" # Auto-detects your positions
430 |
431 | "Remove 5 shares of MSFT"
432 | ```
433 |
434 | ### Portfolio Optimization Example
435 |
436 | ```
437 | "Optimize a portfolio of AAPL, GOOGL, MSFT, and AMZN for maximum Sharpe ratio"
438 |
439 | "Calculate the correlation matrix for my tech portfolio"
440 |
441 | "Analyze the risk-adjusted returns for energy sector stocks"
442 | ```
443 |
444 | ## Tools
445 |
446 | MaverickMCP provides 39+ financial analysis tools organized by category, including advanced AI-powered research agents:
447 |
448 | ### Stock Data Tools
449 |
450 | - `fetch_stock_data` - Get historical stock data with intelligent caching
451 | - `fetch_stock_data_batch` - Fetch data for multiple tickers simultaneously
452 | - `get_news_sentiment` - Analyze news sentiment for any ticker
453 | - `clear_cache` / `get_cache_info` - Cache management utilities
454 |
455 | ### Technical Analysis Tools
456 |
457 | - `get_rsi_analysis` - RSI calculation with buy/sell signals
458 | - `get_macd_analysis` - MACD analysis with trend identification
459 | - `get_support_resistance` - Identify key price levels
460 | - `get_full_technical_analysis` - Comprehensive technical analysis
461 | - `get_stock_chart_analysis` - Visual chart generation
462 |
463 | ### Portfolio Management Tools (NEW) - Personal Portfolio Tracking
464 |
465 | - `portfolio_add_position` - Add or update positions with automatic cost basis averaging
466 | - `portfolio_get_my_portfolio` - View portfolio with live P&L calculations
467 | - `portfolio_remove_position` - Remove partial or full positions
468 | - `portfolio_clear_portfolio` - Clear all positions with safety confirmation
469 |
470 | **Portfolio Features:**
471 | - **Persistent Storage**: Track your actual holdings with cost basis
472 | - **Automatic Averaging**: Cost basis updates automatically on repeat purchases
473 | - **Live P&L**: Real-time unrealized gains/losses on all positions
474 | - **Portfolio Resource**: `portfolio://my-holdings` provides AI context automatically
475 | - **Multi-Portfolio Support**: Track multiple portfolios (IRA, 401k, taxable, etc.)
476 | - **Fractional Shares**: Full support for partial share positions
477 |
478 | ### Portfolio Analysis Tools
479 |
480 | - `risk_adjusted_analysis` - Risk-based position sizing with position awareness
481 | - `compare_tickers` - Side-by-side ticker comparison (auto-uses your portfolio)
482 | - `portfolio_correlation_analysis` - Correlation matrix analysis (auto-analyzes your holdings)
483 |
484 | **Smart Integration:**
485 | - All analysis tools auto-detect your portfolio positions
486 | - No need to manually enter tickers you already own
487 | - Position-aware recommendations (averaging up/down, profit taking)
488 |
489 | ### Stock Screening Tools (Pre-seeded with S&P 500)
490 |
491 | - `get_maverick_stocks` - Bullish momentum screening from 520 S&P 500 stocks
492 | - `get_maverick_bear_stocks` - Bearish setup identification from pre-analyzed data
493 | - `get_trending_breakout_stocks` - Strong uptrend phase screening with supply/demand analysis
494 | - `get_all_screening_recommendations` - Combined screening results across all strategies
495 | - Database includes comprehensive screening data updated regularly
496 |
497 | ### Advanced Research Tools (NEW) - AI-Powered Deep Analysis
498 |
499 | - `research_comprehensive` - Full parallel research with multiple AI agents (7-256x faster)
500 | - `research_company` - Company-specific deep research with financial analysis
501 | - `analyze_market_sentiment` - Multi-source sentiment analysis with confidence tracking
502 | - `coordinate_agents` - Multi-agent supervisor for complex research orchestration
503 |
504 | **Research Features:**
505 | - **Parallel Execution**: 7-256x speedup with intelligent agent orchestration
506 | - **Adaptive Timeouts**: 120s-600s based on research depth and complexity
507 | - **Smart Model Selection**: Automatic selection from 400+ models via OpenRouter
508 | - **Cost Optimization**: 40-60% cost reduction through intelligent model routing
509 | - **Early Termination**: Confidence-based early stopping to save time and costs
510 | - **Content Filtering**: High-credibility source prioritization
511 | - **Error Recovery**: Circuit breakers and comprehensive error handling
512 |
513 | ### Backtesting Tools (NEW) - Production-Ready Strategy Testing
514 |
515 | - `run_backtest` - Execute backtests with VectorBT engine for any strategy
516 | - `compare_strategies` - A/B testing framework for strategy comparison
517 | - `optimize_strategy` - Walk-forward optimization with parameter tuning
518 | - `analyze_backtest_results` - Comprehensive performance metrics and risk analysis
519 | - `get_backtest_report` - Generate detailed HTML reports with visualizations
520 |
521 | **Backtesting Features:**
522 | - **15+ Built-in Strategies**: Including ML-powered adaptive, ensemble, and regime-aware algorithms
523 | - **VectorBT Integration**: High-performance vectorized backtesting engine
524 | - **Parallel Processing**: 7-256x speedup for multi-strategy evaluation
525 | - **Advanced Metrics**: Sharpe, Sortino, Calmar ratios, maximum drawdown, win rate
526 | - **Walk-Forward Optimization**: Out-of-sample testing and validation
527 | - **Monte Carlo Simulations**: Robustness testing with confidence intervals
528 | - **Multi-Timeframe Support**: From 1-minute to monthly data
529 | - **Custom Strategy Development**: Easy-to-use templates for custom strategies
530 |
531 | ### Market Data Tools
532 |
533 | - Market overview, sector performance, earnings calendars
534 | - Economic indicators and Federal Reserve data
535 | - Real-time market movers and sentiment analysis
536 |
537 | ## Resources
538 |
539 | - `stock://{ticker}` - Latest year of stock data
540 | - `stock://{ticker}/{start_date}/{end_date}` - Custom date range
541 | - `stock_info://{ticker}` - Basic stock information
542 |
543 | ## Prompts
544 |
545 | - `stock_analysis(ticker)` - Comprehensive stock analysis prompt
546 | - `market_comparison(tickers)` - Compare multiple stocks
547 | - `portfolio_optimization(tickers, risk_profile)` - Portfolio optimization guidance
548 |
549 | ## Test Examples - Validate All Features
550 |
551 | Test the comprehensive research capabilities and parallel processing improvements with these examples:
552 |
553 | ### Core Research Features
554 |
555 | 1. **Basic Research with Timeout Protection**
556 | ```
557 | "Research the current state of the AI semiconductor industry and identify the top 3 investment opportunities"
558 | ```
559 | - Tests: Basic research, adaptive timeouts, industry analysis
560 |
561 | 2. **Comprehensive Company Research with Parallel Agents**
562 | ```
563 | "Provide comprehensive research on NVDA including fundamental analysis, technical indicators, competitive positioning, and market sentiment using multiple research approaches"
564 | ```
565 | - Tests: Parallel orchestration, multi-agent coordination, company research
566 |
567 | 3. **Cost-Optimized Quick Research**
568 | ```
569 | "Give me a quick overview of AAPL's recent earnings and stock performance"
570 | ```
571 | - Tests: Intelligent model selection, cost optimization, quick analysis
572 |
573 | ### Performance Testing
574 |
575 | 4. **Parallel Performance Benchmark**
576 | ```
577 | "Research and compare MSFT, GOOGL, and AMZN simultaneously focusing on cloud computing revenue growth"
578 | ```
579 | - Tests: Parallel execution speedup (7-256x), multi-company analysis
580 |
581 | 5. **Deep Research with Early Termination**
582 | ```
583 | "Conduct exhaustive research on Tesla's autonomous driving technology and its impact on the stock valuation"
584 | ```
585 | - Tests: Deep research depth, confidence tracking, early termination (0.85 threshold)
586 |
587 | ### Error Handling & Recovery
588 |
589 | 6. **Error Recovery and Circuit Breaker Test**
590 | ```
591 | "Research 10 penny stocks with unusual options activity and provide risk assessments for each"
592 | ```
593 | - Tests: Circuit breaker activation, error handling, fallback mechanisms
594 |
595 | 7. **Supervisor Agent Coordination**
596 | ```
597 | "Analyze the renewable energy sector using both technical and fundamental analysis approaches, then synthesize the findings into actionable investment recommendations"
598 | ```
599 | - Tests: Supervisor routing, agent coordination, result synthesis
600 |
601 | ### Advanced Features
602 |
603 | 8. **Sentiment Analysis with Content Filtering**
604 | ```
605 | "Analyze market sentiment for Bitcoin and cryptocurrency stocks over the past week, filtering for high-credibility sources only"
606 | ```
607 | - Tests: Sentiment analysis, content filtering, source credibility
608 |
609 | 9. **Timeout Stress Test**
610 | ```
611 | "Research the entire S&P 500 technology sector companies and rank them by growth potential"
612 | ```
613 | - Tests: Timeout management, large-scale analysis, performance under load
614 |
615 | 10. **Multi-Modal Research Integration**
616 | ```
617 | "Research AMD using technical analysis, then find recent news about their AI chips, analyze competitor Intel's position, and provide a comprehensive investment thesis with risk assessment"
618 | ```
619 | - Tests: All research modes, integration, synthesis, risk assessment
620 |
621 | ### Bonus Edge Case Tests
622 |
623 | 11. **Empty/Invalid Query Handling**
624 | ```
625 | "Research [intentionally leave blank or use symbol that doesn't exist like XYZABC]"
626 | ```
627 | - Tests: Error messages, helpful fix suggestions
628 |
629 | 12. **Token Budget Optimization**
630 | ```
631 | "Provide the most comprehensive possible analysis of the entire semiconductor industry including all major players, supply chain dynamics, geopolitical factors, and 5-year projections"
632 | ```
633 | - Tests: Progressive token allocation, budget management, depth vs breadth
634 |
635 | ### Expected Performance Metrics
636 |
637 | When running these tests, you should observe:
638 | - **Parallel Speedup**: 7-256x faster for multi-entity queries
639 | - **Response Times**: Simple queries ~10s, complex research 30-120s
640 | - **Cost Efficiency**: 60-80% reduction vs premium-only models
641 | - **Confidence Scores**: Early termination when confidence > 0.85
642 | - **Error Recovery**: Graceful degradation without crashes
643 | - **Model Selection**: Automatic routing to optimal models per task
644 |
645 | ## Docker (Optional)
646 |
647 | For containerized deployment:
648 |
649 | ```bash
650 | # Copy and configure environment
651 | cp .env.example .env
652 |
653 | # Using uv in Docker (recommended for faster builds)
654 | docker build -t maverick_mcp .
655 | docker run -p 8003:8003 --env-file .env maverick_mcp
656 |
657 | # Or start with docker-compose
658 | docker-compose up -d
659 | ```
660 |
661 | **Note**: The Dockerfile uses `uv` for fast dependency installation and smaller image sizes.
662 |
663 | ## Troubleshooting
664 |
665 | ### Common Issues
666 |
667 | **Tools Disappearing in Claude Desktop:**
668 | - **Solution**: Ensure SSE endpoint has trailing slash: `http://localhost:8003/sse/`
669 | - The 307 redirect from `/sse` to `/sse/` causes tool registration to fail
670 | - Always use the exact configuration with trailing slash shown above
671 |
672 | **Research Tool Timeouts:**
673 | - Research tools have adaptive timeouts (120s-600s)
674 | - Deep research may take 2-10 minutes depending on complexity
675 | - Monitor progress in server logs with `make tail-log`
676 |
677 | **OpenRouter Not Working:**
678 | - Ensure `OPENROUTER_API_KEY` is set in `.env`
679 | - Check API key validity at [openrouter.ai](https://openrouter.ai)
680 | - System falls back to direct providers if OpenRouter unavailable
681 |
682 | ```bash
683 | # Common development issues
684 | make tail-log # View server logs
685 | make stop # Stop services if ports are in use
686 | make clean # Clean up cache files
687 |
688 | # Quick fixes:
689 | # Port 8003 in use → make stop
690 | # Redis connection refused → brew services start redis
691 | # Tests failing → make test (unit tests only)
692 | # Slow startup → ./tools/fast_dev.sh
693 | # Missing S&P 500 data → uv run python scripts/seed_sp500.py
694 | # Research timeouts → Check logs, increase timeout settings
695 | ```
696 |
697 | ## Extending MaverickMCP
698 |
699 | Add custom financial analysis tools with simple decorators:
700 |
701 | ```python
702 | @mcp.tool()
703 | def my_custom_indicator(ticker: str, period: int = 14):
704 | """Calculate custom technical indicator."""
705 | # Your analysis logic here
706 | return {"ticker": ticker, "signal": "buy", "confidence": 0.85}
707 |
708 | @mcp.resource("custom://analysis/{ticker}")
709 | def custom_analysis(ticker: str):
710 | """Custom analysis resource."""
711 | # Your resource logic here
712 | return f"Custom analysis for {ticker}"
713 | ```
714 |
715 | ## Development Tools
716 |
717 | ### Quick Development Workflow
718 |
719 | ```bash
720 | make dev # Start everything
721 | make stop # Stop services
722 | make tail-log # Follow server logs
723 | make test # Run tests quickly
724 | make experiment # Test custom analysis scripts
725 | ```
726 |
727 | ### Smart Error Handling
728 |
729 | MaverickMCP includes helpful error diagnostics:
730 |
731 | - DataFrame column case sensitivity → Shows correct column name
732 | - Connection failures → Provides specific fix commands
733 | - Import errors → Shows exact install commands
734 | - Database issues → Suggests SQLite fallback
735 |
736 | ### Fast Development Options
737 |
738 | - **Hot Reload**: `uv run python tools/hot_reload.py` - Auto-restart on changes
739 | - **Fast Startup**: `./tools/fast_dev.sh` - < 3 second startup
740 | - **Quick Testing**: `uv run python tools/quick_test.py --test stock` - Test specific features
741 | - **Experiment Harness**: Drop .py files in `tools/experiments/` for auto-execution
742 |
743 | ### Performance Features
744 |
745 | - **Parallel Screening**: 4x faster stock analysis with ProcessPoolExecutor
746 | - **Smart Caching**: `@quick_cache` decorator for instant re-runs
747 | - **Optimized Tests**: Unit tests complete in 5-10 seconds
748 |
749 | ## Getting Help
750 |
751 | For issues or questions:
752 |
753 | 1. **Check Documentation**: Start with this README and [CLAUDE.md](CLAUDE.md)
754 | 2. **Search Issues**: Look through existing [GitHub issues](https://github.com/wshobson/maverick-mcp/issues)
755 | 3. **Report Bugs**: Create a new [issue](https://github.com/wshobson/maverick-mcp/issues/new) with details
756 | 4. **Request Features**: Suggest improvements via GitHub issues
757 | 5. **Contribute**: See our [Contributing Guide](CONTRIBUTING.md) for development setup
758 |
759 | ## Recent Updates
760 |
761 | ### Production-Ready Backtesting Framework (NEW)
762 |
763 | - **VectorBT Integration**: High-performance vectorized backtesting engine for institutional-grade performance
764 | - **15+ Built-in Strategies**: Including ML-powered adaptive, ensemble, and regime-aware algorithms
765 | - **Parallel Processing**: 7-256x speedup for multi-strategy evaluation and optimization
766 | - **Advanced Analytics**: Comprehensive metrics including Sharpe, Sortino, Calmar ratios, and drawdown analysis
767 | - **Walk-Forward Optimization**: Out-of-sample testing with automatic parameter tuning
768 | - **Monte Carlo Simulations**: Robustness testing with confidence intervals
769 | - **LangGraph Workflow**: Multi-agent orchestration for intelligent strategy selection and validation
770 | - **Production Features**: Database persistence, batch processing, and HTML reporting
771 |
772 | ### Advanced Research Agents
773 |
774 | - **Parallel Research Execution**: Achieved 7-256x speedup (exceeded 2x target) with intelligent agent orchestration
775 | - **Adaptive Timeout Protection**: Dynamic timeouts (120s-600s) based on research depth and complexity
776 | - **Intelligent Model Selection**: OpenRouter integration with 400+ models, 40-60% cost reduction
777 | - **Comprehensive Error Handling**: Circuit breakers, retry logic, and graceful degradation
778 | - **Early Termination**: Confidence-based stopping to optimize time and costs
779 | - **Content Filtering**: High-credibility source prioritization for quality results
780 | - **Multi-Agent Orchestration**: Supervisor pattern for complex research coordination
781 |
782 | ### Performance Improvements
783 |
784 | - **Parallel Agent Execution**: Increased concurrent agents from 4 to 6
785 | - **Optimized Semaphores**: BoundedSemaphore for better resource management
786 | - **Reduced Rate Limiting**: Delays decreased from 0.5s to 0.05s
787 | - **Batch Processing**: Improved throughput for multiple research tasks
788 | - **Smart Caching**: Redis-powered with in-memory fallback
789 |
790 | ### Testing & Quality
791 |
792 | - **84% Test Coverage**: 93 tests with comprehensive coverage
793 | - **Zero Linting Errors**: Fixed 947 issues for clean codebase
794 | - **Full Type Annotations**: Complete type coverage for research components
795 | - **Error Recovery Testing**: Comprehensive failure scenario coverage
796 |
797 | ### Personal Use Optimization
798 |
799 | - **No Authentication Required**: Removed all authentication/billing complexity for personal use
800 | - **Pre-seeded S&P 500 Database**: 520 stocks with comprehensive screening recommendations
801 | - **Simplified Architecture**: Clean, focused codebase for core stock analysis functionality
802 | - **Multi-Transport Support**: HTTP, SSE, and STDIO for all MCP clients
803 |
804 | ### Development Experience Improvements
805 |
806 | - **Comprehensive Makefile**: One command (`make dev`) starts everything including database seeding
807 | - **Smart Error Handling**: Automatic fix suggestions for common issues
808 | - **Fast Development**: < 3 second startup with `./tools/fast_dev.sh`
809 | - **Parallel Processing**: 4x speedup for stock screening operations
810 | - **Enhanced Tooling**: Hot reload, experiment harness, quick testing
811 |
812 | ### Technical Improvements
813 |
814 | - **Modern Tooling**: Migrated to uv and ty for faster dependency management and type checking
815 | - **Market Data**: Improved fallback logic and async support
816 | - **Caching**: Smart Redis caching with graceful in-memory fallback
817 | - **Database**: SQLite default with PostgreSQL option for enhanced performance
818 |
819 | ## Acknowledgments
820 |
821 | MaverickMCP builds on these excellent open-source projects:
822 |
823 | - **[FastMCP](https://github.com/jlowin/fastmcp)** - MCP framework powering the server
824 | - **[yfinance](https://github.com/ranaroussi/yfinance)** - Market data access
825 | - **[TA-Lib](https://github.com/mrjbq7/ta-lib)** - Technical analysis indicators
826 | - **[pandas](https://pandas.pydata.org/)** & **[NumPy](https://numpy.org/)** - Data analysis
827 | - **[FastAPI](https://fastapi.tiangolo.com/)** - Modern web framework
828 | - The entire Python open-source community
829 |
830 | ## License
831 |
832 | MIT License - see [LICENSE](LICENSE) file for details. Free to use for personal and commercial purposes.
833 |
834 | ## Support
835 |
836 | If you find MaverickMCP useful:
837 |
838 | - Star the repository
839 | - Report bugs via GitHub issues
840 | - Suggest features
841 | - Improve documentation
842 |
843 | ---
844 |
845 | Built for traders and investors. Happy Trading!
846 |
847 | [](https://mseep.ai/app/wshobson-maverick-mcp)
848 |
849 | **Read the full build guide**: [How to Build an MCP Stock Analysis Server](https://sethhobson.com/2025/08/how-to-build-an-mcp-stock-analysis-server/)
850 |
851 | ## Disclaimer
852 |
853 | <sub>**This software is for educational and informational purposes only. It is NOT financial advice.**</sub>
854 |
855 | <sub>**Investment Risk Warning**: Past performance does not guarantee future results. All investments carry risk of loss, including total loss of capital. Technical analysis and screening results are not predictive of future performance. Market data may be delayed, inaccurate, or incomplete.</sub>
856 |
857 | <sub>**No Professional Advice**: This tool provides data analysis, not investment recommendations. Always consult with a qualified financial advisor before making investment decisions. The developers are not licensed financial advisors or investment professionals. Nothing in this software constitutes professional financial, investment, legal, or tax advice.</sub>
858 |
859 | <sub>**Data and Accuracy**: Market data provided by third-party sources (Tiingo, Yahoo Finance, FRED). Data may contain errors, delays, or omissions. Technical indicators are mathematical calculations based on historical data. No warranty is made regarding data accuracy or completeness.</sub>
860 |
861 | <sub>**Regulatory Compliance**: US Users - This software is not registered with the SEC, CFTC, or other regulatory bodies. International Users - Check local financial software regulations before use. Users are responsible for compliance with all applicable laws and regulations. Some features may not be available in certain jurisdictions.</sub>
862 |
863 | <sub>**Limitation of Liability**: Developers disclaim all liability for investment losses or damages. Use this software at your own risk. No guarantee is made regarding software availability or functionality.</sub>
864 |
865 | <sub>By using MaverickMCP, you acknowledge these risks and agree to use the software for educational purposes only.</sub>
866 |
```
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
```markdown
1 | # Security Policy
2 |
3 | ## Reporting Security Vulnerabilities
4 |
5 | The MaverickMCP team takes security seriously. We appreciate your efforts to responsibly disclose your findings and will make every effort to acknowledge your contributions.
6 |
7 | ## Reporting a Vulnerability
8 |
9 | **Please DO NOT report security vulnerabilities through public GitHub issues.**
10 |
11 | Instead, please report them via GitHub Security Advisories (recommended).
12 |
13 | Please include:
14 | - Type of vulnerability
15 | - Full paths of affected source files
16 | - Location of the affected code (tag/branch/commit or direct URL)
17 | - Any special configuration required to reproduce
18 | - Step-by-step instructions to reproduce
19 | - Proof-of-concept or exploit code (if possible)
20 | - Impact of the issue, including how an attacker might exploit it
21 |
22 | You should receive a response within 48 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
23 |
24 | ## Supported Versions
25 |
26 | | Version | Supported |
27 | | ------- | ------------------ |
28 | | 0.1.x | :white_check_mark: |
29 | | < 0.1 | :x: |
30 |
31 | ## Security Features
32 |
33 | MaverickMCP implements security measures appropriate for personal-use software:
34 |
35 | ### Personal Use Security Model
36 | - **Local Deployment**: Designed to run locally for individual users
37 | - **No Network Authentication**: Simplicity over complex auth systems
38 | - **Environment Variable Security**: All API keys stored as environment variables
39 | - **Basic Rate Limiting**: Protection against excessive API calls
40 |
41 | ### Data Protection
42 | - **Input Validation**: Comprehensive Pydantic validation on all inputs
43 | - **SQL Injection Prevention**: SQLAlchemy ORM with parameterized queries
44 | - **API Key Security**: Secure handling of financial data provider credentials
45 | - **Local Data Storage**: All analysis data stored locally by default
46 |
47 | ### Infrastructure Security
48 | - **Environment Variables**: All secrets externalized, no hardcoded credentials
49 | - **Secure Headers**: HSTS, CSP, X-Frame-Options, X-Content-Type-Options
50 | - **Audit Logging**: Comprehensive security event logging
51 | - **Circuit Breakers**: Protection against cascade failures
52 |
53 | ## Security Best Practices for Contributors
54 |
55 | ### Configuration
56 | - Never commit secrets or API keys
57 | - Use environment variables for all sensitive configuration
58 | - Follow the `.env.example` template
59 | - Use strong, unique passwords for development databases
60 |
61 | ### Code Guidelines
62 | - Always validate and sanitize user input
63 | - Use parameterized queries (SQLAlchemy ORM)
64 | - Implement proper error handling without exposing sensitive information
65 | - Follow the principle of least privilege
66 | - Add rate limiting to new endpoints
67 |
68 | ### Dependencies
69 | - Keep dependencies up to date
70 | - Review security advisories regularly
71 | - Run `safety check` before releases
72 | - Use `bandit` for static security analysis
73 |
74 | ## Security Checklist for Pull Requests
75 |
76 | - [ ] No hardcoded secrets or credentials
77 | - [ ] Input validation on all user-provided data
78 | - [ ] Proper error handling without information leakage
79 | - [ ] API key handling follows environment variable patterns
80 | - [ ] Financial data handling includes appropriate disclaimers
81 | - [ ] Security tests for new features
82 | - [ ] No vulnerable dependencies introduced
83 | - [ ] Personal-use security model maintained (no complex auth)
84 |
85 | ## Running Security Audits
86 |
87 | ### Dependency Scanning
88 | ```bash
89 | # Install security tools
90 | pip install safety bandit
91 |
92 | # Check for known vulnerabilities
93 | safety check
94 |
95 | # Static security analysis
96 | bandit -r maverick_mcp/
97 | ```
98 |
99 | ### Additional Security Tools
100 | ```bash
101 | # OWASP dependency check
102 | pip install pip-audit
103 | pip-audit
104 |
105 | # Advanced static analysis
106 | pip install semgrep
107 | semgrep --config=auto maverick_mcp/
108 | ```
109 |
110 | ## Security Headers Configuration
111 |
112 | The application implements the following security headers:
113 | - `Strict-Transport-Security: max-age=31536000; includeSubDomains`
114 | - `X-Content-Type-Options: nosniff`
115 | - `X-Frame-Options: DENY`
116 | - `X-XSS-Protection: 1; mode=block`
117 | - `Referrer-Policy: strict-origin-when-cross-origin`
118 | - `Content-Security-Policy: default-src 'self'`
119 |
120 | ## Incident Response
121 |
122 | In case of a security incident:
123 |
124 | 1. **Immediate Response**: Assess the severity and impact
125 | 2. **Containment**: Isolate affected systems
126 | 3. **Investigation**: Determine root cause and extent
127 | 4. **Remediation**: Fix the vulnerability
128 | 5. **Recovery**: Restore normal operations
129 | 6. **Post-Incident**: Document lessons learned
130 |
131 | ## Security Contacts
132 |
133 | - **Primary**: [GitHub Security Advisories](https://github.com/wshobson/maverick-mcp/security) (Recommended)
134 | - **Alternative**: [GitHub Issues](https://github.com/wshobson/maverick-mcp/issues) (Public security issues only)
135 | - **Community**: [GitHub Discussions](https://github.com/wshobson/maverick-mcp/discussions)
136 |
137 | ## Acknowledgments
138 |
139 | We would like to thank the following individuals for responsibly disclosing security issues:
140 |
141 | *This list will be updated as vulnerabilities are reported and fixed.*
142 |
143 | ## Financial Data Security
144 |
145 | ### Investment Data Protection
146 | - **Personal Investment Information**: Never share account details, positions, or personal financial data
147 | - **API Keys**: Secure storage of financial data provider API keys (Tiingo, FRED, etc.)
148 | - **Market Data**: Ensure compliance with data provider terms of service and usage restrictions
149 | - **Analysis Results**: Be aware that financial analysis outputs may contain sensitive investment insights
150 |
151 | ### Compliance Considerations
152 | - **Financial Regulations**: Users must comply with applicable securities laws (SEC, CFTC, etc.)
153 | - **Data Privacy**: Market analysis and portfolio data should be treated as confidential
154 | - **Audit Trails**: Financial analysis activities may need to be logged for regulatory purposes
155 | - **Cross-border Data**: Consider regulations when using financial data across international boundaries
156 |
157 | ## Financial Disclaimer for Security Context
158 |
159 | **IMPORTANT**: This security policy covers the technical security of the software only. The financial analysis and investment tools provided by MaverickMCP are for educational purposes only and do not constitute financial advice. Always consult with qualified financial professionals for investment decisions.
160 |
161 | ## Resources
162 |
163 | - [OWASP Top 10](https://owasp.org/www-project-top-ten/)
164 | - [CWE Top 25](https://cwe.mitre.org/top25/)
165 | - [Python Security Best Practices](https://python.readthedocs.io/en/latest/library/security_warnings.html)
166 | - [FastAPI Security](https://fastapi.tiangolo.com/tutorial/security/)
167 | - [SEC Cybersecurity Guidelines](https://www.sec.gov/spotlight/cybersecurity)
168 | - [Financial Data Security Best Practices](https://www.cisa.gov/financial-services)
169 |
170 | ---
171 |
172 | Thank you for helping keep MaverickMCP and its users safe!
```
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
```markdown
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, caste, color, religion, or sexual
10 | identity and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | - Demonstrating empathy and kindness toward other people
21 | - Being respectful of differing opinions, viewpoints, and experiences
22 | - Giving and gracefully accepting constructive feedback
23 | - Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | - Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | - The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | - Trolling, insulting or derogatory comments, and personal or political attacks
33 | - Public or private harassment
34 | - Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | - Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Financial Software Specific Guidelines
40 |
41 | Given the nature of this financial analysis software, we have additional community standards:
42 |
43 | ### Educational Focus
44 |
45 | - **Maintain Educational Purpose**: All discussions and contributions should focus on the educational and learning aspects of financial analysis
46 | - **No Investment Advice**: Contributors and community members must not provide specific investment recommendations or financial advice
47 | - **Respect Disclaimers**: Always include appropriate disclaimers when discussing financial concepts or analysis
48 |
49 | ### Professional Discourse
50 |
51 | - **Factual Discussions**: Keep financial discussions factual and educational, avoiding speculation or promotional content
52 | - **Risk Awareness**: Acknowledge the risks inherent in financial markets when discussing trading or investment concepts
53 | - **Data Accuracy**: Strive for accuracy in financial data and calculations, and acknowledge limitations
54 |
55 | ### Inclusive Learning Environment
56 |
57 | - **Welcome All Experience Levels**: From beginners learning basic concepts to experts contributing advanced features
58 | - **Patient Teaching**: Help newcomers understand both programming concepts and financial analysis principles
59 | - **Diverse Perspectives**: Welcome different approaches to financial analysis and technical implementation
60 |
61 | ## Enforcement Responsibilities
62 |
63 | Community leaders are responsible for clarifying and enforcing our standards of
64 | acceptable behavior and will take appropriate and fair corrective action in
65 | response to any behavior that they deem inappropriate, threatening, offensive,
66 | or harmful.
67 |
68 | Community leaders have the right and responsibility to remove, edit, or reject
69 | comments, commits, code, wiki edits, issues, and other contributions that are
70 | not aligned to this Code of Conduct, and will communicate reasons for moderation
71 | decisions when appropriate.
72 |
73 | ## Scope
74 |
75 | This Code of Conduct applies within all community spaces, and also applies when
76 | an individual is officially representing the community in public spaces.
77 | Examples of representing our community include using an official e-mail address,
78 | posting via an official social media account, or acting as an appointed
79 | representative at an online or offline event.
80 |
81 | ## Enforcement
82 |
83 | All complaints will be reviewed and investigated promptly and fairly.
84 |
85 | All community leaders are obligated to respect the privacy and security of the
86 | reporter of any incident.
87 |
88 | ## Financial Disclaimer for Community Interactions
89 |
90 | **IMPORTANT**: All discussions, code contributions, and educational content in this community are for educational purposes only. Nothing in our community interactions should be construed as financial advice.
91 |
92 | ### Community Member Responsibilities
93 |
94 | - **No Financial Advice**: Do not provide specific investment recommendations or financial advice
95 | - **Educational Purpose**: Frame all discussions in educational contexts
96 | - **Risk Acknowledgment**: Acknowledge that all financial analysis carries risk
97 | - **Disclaimer Inclusion**: Include appropriate disclaimers in financial-related content
98 |
99 | ### Project Maintainer Responsibilities
100 |
101 | - **Consistent Disclaimers**: Ensure all financial analysis features include appropriate disclaimers
102 | - **Educational Focus**: Guide discussions toward learning and technical implementation
103 | - **Regulatory Awareness**: Be mindful of financial regulations and compliance considerations
104 | - **Community Safety**: Protect community members from potentially harmful financial advice
105 |
106 | ## Enforcement Guidelines
107 |
108 | Community leaders will follow these Community Impact Guidelines in determining
109 | the consequences for any action they deem in violation of this Code of Conduct:
110 |
111 | ### 1. Correction
112 |
113 | **Community Impact**: Use of inappropriate language or other behavior deemed
114 | unprofessional or unwelcome in the community.
115 |
116 | **Consequence**: A private, written warning from community leaders, providing
117 | clarity around the nature of the violation and an explanation of why the
118 | behavior was inappropriate. A public apology may be requested.
119 |
120 | ### 2. Warning
121 |
122 | **Community Impact**: A violation through a single incident or series
123 | of actions.
124 |
125 | **Consequence**: A warning with consequences for continued behavior. No
126 | interaction with the people involved, including unsolicited interaction with
127 | those enforcing the Code of Conduct, for a specified period of time. This
128 | includes avoiding interactions in community spaces as well as external channels
129 | like social media. Violating these terms may lead to a temporary or
130 | permanent ban.
131 |
132 | ### 3. Temporary Ban
133 |
134 | **Community Impact**: A serious violation of community standards, including
135 | sustained inappropriate behavior.
136 |
137 | **Consequence**: A temporary ban from any sort of interaction or public
138 | communication with the community for a specified period of time. No public or
139 | private interaction with the people involved, including unsolicited interaction
140 | with those enforcing the Code of Conduct, is allowed during this period.
141 | Violating these terms may lead to a permanent ban.
142 |
143 | ### 4. Permanent Ban
144 |
145 | **Community Impact**: Demonstrating a pattern of violation of community
146 | standards, including sustained inappropriate behavior, harassment of an
147 | individual, or aggression toward or disparagement of classes of individuals.
148 |
149 | **Consequence**: A permanent ban from any sort of public interaction within
150 | the community.
151 |
152 | ## Attribution
153 |
154 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
155 | version 2.1, available at
156 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
157 |
158 | Community Impact Guidelines were inspired by
159 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
160 |
161 | For answers to common questions about this code of conduct, see the FAQ at
162 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available
163 | at [https://www.contributor-covenant.org/translations][translations].
164 |
165 | [homepage]: https://www.contributor-covenant.org
166 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
167 | [Mozilla CoC]: https://github.com/mozilla/diversity
168 | [FAQ]: https://www.contributor-covenant.org/faq
169 | [translations]: https://www.contributor-covenant.org/translations
170 |
171 | ---
172 |
173 | ## Contact Information
174 |
175 | - **GitHub Discussions**: [Community Discussions](https://github.com/wshobson/maverick-mcp/discussions)
176 | - **Security Issues**: [Security Policy](SECURITY.md)
177 |
178 | Remember: We're building an educational financial analysis tool together. Let's keep our community welcoming, professional, and focused on learning!
179 |
```
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
```markdown
1 | # Contributing to MaverickMCP
2 |
3 | Welcome to MaverickMCP! We're excited to have you contribute to this open-source financial analysis MCP server.
4 |
5 | ## Table of Contents
6 |
7 | - [Development Setup](#development-setup)
8 | - [Project Structure](#project-structure)
9 | - [Running Tests](#running-tests)
10 | - [Code Style](#code-style)
11 | - [Making Changes](#making-changes)
12 | - [Submitting Pull Requests](#submitting-pull-requests)
13 | - [Reporting Issues](#reporting-issues)
14 | - [Financial Domain Guidelines](#financial-domain-guidelines)
15 |
16 | ## Development Setup
17 |
18 | ### Prerequisites
19 |
20 | - Python 3.12+
21 | - [uv](https://docs.astral.sh/uv/) for dependency management
22 | - PostgreSQL (optional, SQLite works for development)
23 | - Redis (optional for development)
24 |
25 | ### Quick Start
26 |
27 | 1. **Clone the repository**
28 |
29 | ```bash
30 | git clone https://github.com/wshobson/maverick-mcp.git
31 | cd maverick-mcp
32 | ```
33 |
34 | 2. **Install dependencies**
35 |
36 | ```bash
37 | uv sync --extra dev
38 | ```
39 |
40 | 3. **Set up environment**
41 |
42 | ```bash
43 | cp .env.example .env
44 | # Edit .env with your configuration
45 | ```
46 |
47 | 4. **Start development server**
48 | ```bash
49 | make dev
50 | # Or: ./scripts/start-backend.sh --dev
51 | ```
52 |
53 | ### Development Commands
54 |
55 | - `make dev` - Start everything (recommended)
56 | - `make test` - Run unit tests (5-10 seconds)
57 | - `make lint` - Check code quality
58 | - `make format` - Auto-format code
59 | - `make typecheck` - Run type checking
60 |
61 | ### Pre-commit Hooks (Optional but Recommended)
62 |
63 | We provide pre-commit hooks to ensure code quality:
64 |
65 | ```bash
66 | # Install pre-commit (one time setup)
67 | pip install pre-commit
68 |
69 | # Install hooks for this repository
70 | pre-commit install
71 |
72 | # Run hooks on all files (optional)
73 | pre-commit run --all-files
74 | ```
75 |
76 | Pre-commit hooks will automatically run on every commit and include:
77 |
78 | - Code formatting (ruff)
79 | - Linting (ruff)
80 | - Security scanning (bandit, safety)
81 | - Custom financial domain validations
82 |
83 | **Note**: Pre-commit hooks are optional for contributors but recommended for maintainers.
84 |
85 | ## Project Structure
86 |
87 | MaverickMCP follows Domain-Driven Design (DDD) principles:
88 |
89 | ```
90 | maverick_mcp/
91 | ├── api/ # FastAPI routers and server
92 | ├── domain/ # Core business logic (entities, services)
93 | ├── application/ # Use cases and DTOs
94 | ├── infrastructure/# External services (database, APIs)
95 | ├── auth/ # Authentication and security
96 | ├── config/ # Settings and configuration
97 | └── tests/ # Test suite
98 | ```
99 |
100 | ## Running Tests
101 |
102 | We use pytest with multiple test categories:
103 |
104 | ```bash
105 | # Unit tests only (fast, ~5-10 seconds)
106 | make test
107 |
108 | # All tests including integration
109 | make test-all
110 |
111 | # Specific test
112 | make test-specific TEST=test_name
113 |
114 | # With coverage
115 | pytest --cov=maverick_mcp
116 | ```
117 |
118 | **Note**: Integration tests require PostgreSQL and Redis. They're excluded from CI by default.
119 |
120 | ## Code Style
121 |
122 | We enforce strict code quality standards:
123 |
124 | ### Tools
125 |
126 | - **ruff** for linting and formatting
127 | - **pyright** for type checking
128 | - **pytest** for testing
129 |
130 | ### Guidelines
131 |
132 | 1. **Type Hints**: Required for all functions and variables
133 | 2. **Docstrings**: Google-style docstrings for public APIs
134 | 3. **Error Handling**: Proper exception handling with specific error types
135 | 4. **Security**: Never hardcode secrets, always use environment variables
136 |
137 | ### Before Submitting
138 |
139 | ```bash
140 | # Run all quality checks
141 | make check # Runs lint + typecheck
142 |
143 | # Auto-format code
144 | make format
145 | ```
146 |
147 | ## Making Changes
148 |
149 | ### Development Workflow
150 |
151 | 1. **Start with an issue** - Create or find an existing issue
152 | 2. **Create a branch** - Use descriptive branch names:
153 |
154 | - `feature/add-new-indicator`
155 | - `fix/authentication-bug`
156 | - `docs/improve-setup-guide`
157 |
158 | 3. **Make focused commits** - One logical change per commit
159 | 4. **Write tests** - Add tests for new features or bug fixes
160 | 5. **Update documentation** - Keep docs current with changes
161 |
162 | ### Financial Calculations
163 |
164 | When working with financial logic:
165 |
166 | - **Accuracy is critical** - Double-check all calculations
167 | - **Use proper data types** - `Decimal` for currency, `float` for ratios
168 | - **Include validation** - Validate input ranges and edge cases
169 | - **Add comprehensive tests** - Test edge cases and boundary conditions
170 | - **Document assumptions** - Explain the financial logic in docstrings
171 |
172 | ## Submitting Pull Requests
173 |
174 | ### Checklist
175 |
176 | - [ ] Tests pass (`make test`)
177 | - [ ] Code is formatted (`make format`)
178 | - [ ] Type checking passes (`make typecheck`)
179 | - [ ] Pre-commit hooks pass (`pre-commit run --all-files`)
180 | - [ ] Documentation is updated
181 | - [ ] Financial calculations are validated
182 | - [ ] No hardcoded secrets or credentials
183 |
184 | ### PR Template
185 |
186 | ```markdown
187 | ## Description
188 |
189 | Brief description of the changes
190 |
191 | ## Type of Change
192 |
193 | - [ ] Bug fix
194 | - [ ] New feature
195 | - [ ] Documentation update
196 | - [ ] Refactoring
197 |
198 | ## Financial Impact
199 |
200 | - [ ] No financial calculations affected
201 | - [ ] Financial calculations verified for accuracy
202 | - [ ] New financial calculations added with tests
203 |
204 | ## Testing
205 |
206 | - [ ] Unit tests added/updated
207 | - [ ] Integration tests added (if applicable)
208 | - [ ] Manual testing completed
209 |
210 | ## Screenshots (if applicable)
211 | ```
212 |
213 | ## Reporting Issues
214 |
215 | ### Bug Reports
216 |
217 | Use the bug report template and include:
218 |
219 | - **Environment details** (Python version, OS, dependencies)
220 | - **Reproduction steps** - Clear, minimal steps to reproduce
221 | - **Expected vs actual behavior**
222 | - **Error messages** - Full stack traces when available
223 | - **Financial context** - If related to calculations or market data
224 |
225 | ### Feature Requests
226 |
227 | Include:
228 |
229 | - **Use case** - What problem does this solve?
230 | - **Proposed solution** - How should it work?
231 | - **Financial domain knowledge** - Any domain-specific requirements
232 | - **Implementation considerations** - Technical constraints or preferences
233 |
234 | ## Financial Domain Guidelines
235 |
236 | ### Market Data
237 |
238 | - **Respect rate limits** - All providers have API limits
239 | - **Cache appropriately** - Balance freshness with performance
240 | - **Handle market closures** - Account for weekends and holidays
241 | - **Validate symbols** - Check ticker symbol formats
242 |
243 | ### Technical Indicators
244 |
245 | - **Use established formulas** - Follow industry-standard calculations
246 | - **Document data requirements** - Specify minimum periods needed
247 | - **Handle edge cases** - Division by zero, insufficient data
248 | - **Test with real market data** - Verify against known examples
249 |
250 | ### Risk Management
251 |
252 | - **Position sizing** - Implement proper risk controls
253 | - **Stop loss calculations** - Accurate risk/reward ratios
254 | - **Portfolio limits** - Respect maximum position sizes
255 | - **Backtesting accuracy** - Avoid look-ahead bias
256 |
257 | ### Financial Compliance for Contributors
258 |
259 | - **Educational Purpose**: All financial calculations and analysis tools must be clearly marked as educational
260 | - **No Investment Advice**: Never include language that could be construed as investment recommendations
261 | - **Disclaimer Requirements**: Include appropriate disclaimers in docstrings for financial functions
262 | - **Data Attribution**: Properly attribute data sources (Tiingo, Yahoo Finance, FRED, etc.)
263 | - **Risk Warnings**: Include risk warnings in documentation for portfolio and trading-related features
264 | - **Regulatory Awareness**: Be mindful of securities regulations (SEC, CFTC, international equivalents)
265 |
266 | #### Financial Function Documentation Template
267 |
268 | ```python
269 | def calculate_risk_metric(data: pd.DataFrame) -> float:
270 | """
271 | Calculate a financial risk metric.
272 |
273 | DISCLAIMER: This is for educational purposes only and does not
274 | constitute financial advice. Past performance does not guarantee
275 | future results.
276 |
277 | Args:
278 | data: Historical price data
279 |
280 | Returns:
281 | Risk metric value
282 | """
283 | ```
284 |
285 | ## Architecture Guidelines
286 |
287 | ### Domain-Driven Design
288 |
289 | - **Domain layer** - Pure business logic, no external dependencies
290 | - **Application layer** - Use cases and orchestration
291 | - **Infrastructure layer** - Database, APIs, external services
292 | - **API layer** - HTTP handlers, validation, serialization
293 |
294 | ### MCP Integration
295 |
296 | - **Tool design** - Each tool should have a single, clear purpose
297 | - **Resource management** - Implement proper caching and cleanup
298 | - **Error handling** - Return meaningful error messages
299 | - **Documentation** - Include usage examples and parameter descriptions
300 |
301 | ## Getting Help
302 |
303 | - **Discussions** - Use GitHub Discussions for questions
304 | - **Issues** - Create issues for bugs or feature requests
305 | - **Code Review** - Participate in PR reviews to learn
306 | - **Documentation** - Check existing docs and CLAUDE.md for project context
307 |
308 | ## Contributing to Open Source
309 |
310 | ### Community Standards
311 |
312 | MaverickMCP follows the [Contributor Covenant Code of Conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct/):
313 |
314 | - **Be welcoming** - Help newcomers feel welcome
315 | - **Be respectful** - Treat all contributors with respect
316 | - **Be patient** - Allow time for responses and reviews
317 | - **Be constructive** - Focus on improving the project
318 | - **Be inclusive** - Welcome diverse perspectives and backgrounds
319 |
320 | ### Recognition
321 |
322 | Contributors are recognized in multiple ways:
323 |
324 | - **CHANGELOG.md** - All contributors listed in release notes
325 | - **GitHub contributors** - Automatic recognition via commits
326 | - **Special mentions** - Outstanding contributions highlighted in README
327 | - **Hall of Fame** - Major contributors featured in documentation
328 |
329 | ### Continuous Integration
330 |
331 | Our CI/CD pipeline ensures code quality:
332 |
333 | - **Automated testing** - All PRs run comprehensive test suites
334 | - **Security scanning** - Automated vulnerability detection
335 | - **Code quality checks** - Linting, formatting, and type checking
336 | - **Performance testing** - Benchmark validation on PRs
337 | - **Documentation validation** - Ensures docs stay current
338 |
339 | ### Current Architecture (Simplified for Personal Use)
340 |
341 | MaverickMCP has been cleaned up and simplified:
342 |
343 | - **No Complex Auth**: Removed enterprise JWT/OAuth systems for simplicity
344 | - **No Billing System**: Personal-use focused, no subscription management
345 | - **Local First**: Designed to run locally with Claude Desktop
346 | - **Educational Focus**: Built for learning and personal financial analysis
347 | - **Clean Dependencies**: Removed unnecessary enterprise features
348 |
349 | This makes the codebase much more approachable for contributors!
350 |
351 | ## License
352 |
353 | By contributing, you agree that your contributions will be licensed under the MIT License.
354 |
355 | ## Financial Software Disclaimer for Contributors
356 |
357 | **IMPORTANT**: By contributing to MaverickMCP, you acknowledge that:
358 |
359 | - All financial analysis tools are for educational purposes only
360 | - No content should be construed as investment advice or recommendations
361 | - Contributors are not responsible for user investment decisions or outcomes
362 | - All financial calculations should include appropriate disclaimers and risk warnings
363 | - Data accuracy cannot be guaranteed and users must verify information independently
364 |
365 | Contributors should review the full financial disclaimer in the LICENSE file and README.md.
366 |
367 | ## Recognition
368 |
369 | Contributors will be acknowledged in our CHANGELOG and can be featured in project documentation. We appreciate all contributions, from code to documentation to issue reports!
370 |
371 | ---
372 |
373 | Thank you for contributing to MaverickMCP! Your efforts help make sophisticated financial analysis tools accessible to everyone.
374 |
```
--------------------------------------------------------------------------------
/CLAUDE.md:
--------------------------------------------------------------------------------
```markdown
1 | # CLAUDE.md
2 |
3 | This file provides guidance to Claude Code (claude.ai/code) when working with the MaverickMCP codebase.
4 |
5 | **🚀 QUICK START**: Run `make dev` to start the server. Connect with Claude Desktop using `mcp-remote`. See "Claude Desktop Setup" section below.
6 |
7 | ## Project Overview
8 |
9 | MaverickMCP is a personal stock analysis MCP server built for Claude Desktop. It provides:
10 |
11 | - Pre-seeded database with all 520 S&P 500 stocks and screening recommendations
12 | - Real-time and historical stock data access with intelligent caching
13 | - Advanced technical analysis tools (RSI, MACD, Bollinger Bands, etc.)
14 | - Multiple stock screening strategies (Maverick Bullish/Bearish, Supply/Demand Breakouts)
15 | - **Personal portfolio tracking with cost basis averaging and live P&L** (NEW)
16 | - Portfolio optimization and correlation analysis with auto-detection
17 | - Market and macroeconomic data integration
18 | - SQLAlchemy-based database integration with SQLite default (PostgreSQL optional)
19 | - Redis caching for high performance (optional)
20 | - Clean, personal-use architecture without authentication complexity
21 |
22 | ## Project Structure
23 |
24 | - `maverick_mcp/`
25 | - `api/`: MCP server implementation
26 | - `server.py`: Main FastMCP server (simple stock analysis mode)
27 | - `routers/`: Domain-specific routers for organized tool groups
28 | - `config/`: Configuration and settings
29 | - `core/`: Core financial analysis functions
30 | - `data/`: Data handling, caching, and database models
31 | - `providers/`: Stock, market, and macro data providers
32 | - `utils/`: Development utilities and performance optimizations
33 | - `tests/`: Comprehensive test suite
34 | - `validation/`: Request/response validation
35 | - `tools/`: Development tools for faster workflows
36 | - `docs/`: Architecture documentation
37 | - `scripts/`: Startup and utility scripts
38 | - `Makefile`: Central command interface
39 |
40 | ## Environment Setup
41 |
42 | 1. **Prerequisites**:
43 |
44 | - **Python 3.12+**: Core runtime environment
45 | - **[uv](https://docs.astral.sh/uv/)**: Modern Python package manager (recommended)
46 | - Redis server (optional, for enhanced caching performance)
47 | - PostgreSQL (optional, SQLite works fine for personal use)
48 |
49 | 2. **Installation**:
50 |
51 | ```bash
52 | # Clone the repository
53 | git clone https://github.com/wshobson/maverick-mcp.git
54 | cd maverick-mcp
55 |
56 | # Install dependencies using uv (recommended - fastest)
57 | uv sync
58 |
59 | # Or use traditional pip
60 | python -m venv .venv
61 | source .venv/bin/activate # On Windows: .venv\Scripts\activate
62 | pip install -e .
63 |
64 | # Set up environment
65 | cp .env.example .env
66 | # Add your Tiingo API key (required)
67 | ```
68 |
69 | 3. **Required Configuration** (add to `.env`):
70 |
71 | ```
72 | # Required - Stock data provider (free tier available)
73 | TIINGO_API_KEY=your-tiingo-key
74 | ```
75 |
76 | 4. **Optional Configuration** (add to `.env`):
77 |
78 | ```
79 | # OpenRouter API (strongly recommended for research - access to 400+ AI models with intelligent cost optimization)
80 | OPENROUTER_API_KEY=your-openrouter-key
81 |
82 | # Web Search API (recommended for research features)
83 | EXA_API_KEY=your-exa-key
84 |
85 | # Enhanced data providers (optional)
86 | FRED_API_KEY=your-fred-key
87 |
88 | # Database (optional - uses SQLite by default)
89 | DATABASE_URL=postgresql://localhost/maverick_mcp
90 |
91 | # Redis (optional - works without caching)
92 | REDIS_HOST=localhost
93 | REDIS_PORT=6379
94 | ```
95 |
96 | **Get a free Tiingo API key**: Sign up at [tiingo.com](https://tiingo.com) - free tier includes 500 requests/day.
97 |
98 | **OpenRouter API (Recommended)**: Sign up at [openrouter.ai](https://openrouter.ai) for access to 400+ AI models with intelligent cost optimization. The system automatically selects optimal models based on task requirements.
99 |
100 | ## Quick Start Commands
101 |
102 | ### Essential Commands (Powered by Makefile)
103 |
104 | ```bash
105 | # Start the MCP server
106 | make dev # Start with SSE transport (default, recommended)
107 | make dev-sse # Start with SSE transport (same as dev)
108 | make dev-http # Start with Streamable-HTTP transport (for testing/debugging)
109 | make dev-stdio # Start with STDIO transport (direct connection)
110 |
111 | # Development
112 | make backend # Start backend server only
113 | make tail-log # Follow logs in real-time
114 | make stop # Stop all services
115 |
116 | # Testing
117 | make test # Run unit tests (5-10 seconds)
118 | make test-watch # Auto-run tests on file changes
119 | make test-cov # Run with coverage report
120 |
121 | # Code Quality
122 | make lint # Check code quality
123 | make format # Auto-format code
124 | make typecheck # Run type checking
125 | make check # Run all checks
126 |
127 | # Database
128 | make migrate # Run database migrations
129 | make setup # Initial setup
130 |
131 | # Utilities
132 | make clean # Clean up generated files
133 | make redis-start # Start Redis (if using caching)
134 |
135 | # Quick shortcuts
136 | make d # Alias for make dev
137 | make dh # Alias for make dev-http
138 | make ds # Alias for make dev-stdio
139 | make t # Alias for make test
140 | make l # Alias for make lint
141 | make c # Alias for make check
142 | ```
143 |
144 | ## Claude Desktop Setup
145 |
146 | ### Connection Methods
147 |
148 | **✅ RECOMMENDED**: Claude Desktop works best with the **SSE endpoint via mcp-remote bridge**. This configuration has been tested and **prevents tools from disappearing** after initial connection.
149 |
150 | #### Method A: SSE Server with mcp-remote Bridge (Recommended - Stable)
151 |
152 | This is the **tested and proven method for Claude Desktop** - provides stable tool registration:
153 |
154 | 1. **Start the SSE server**:
155 | ```bash
156 | make dev # Runs SSE server on port 8003
157 | ```
158 |
159 | 2. **Configure with mcp-remote bridge**:
160 | Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
161 |
162 | ```json
163 | {
164 | "mcpServers": {
165 | "maverick-mcp": {
166 | "command": "npx",
167 | "args": ["-y", "mcp-remote", "http://localhost:8003/sse"]
168 | }
169 | }
170 | }
171 | ```
172 |
173 | **Why This Configuration Works Best**:
174 | - ✅ **Prevents Tool Disappearing**: Tools remain available throughout your session
175 | - ✅ **Stable Connection**: SSE transport provides consistent communication
176 | - ✅ **Session Persistence**: Maintains connection state for complex analysis workflows
177 | - ✅ **All 35+ Tools Available**: Reliable access to all financial and research tools
178 | - ✅ **Tested and Confirmed**: This exact configuration has been verified to work
179 | - ✅ **No Trailing Slash Issues**: Server automatically handles both `/sse` and `/sse/` paths
180 |
181 | #### Method B: HTTP Streamable Server with mcp-remote Bridge (Alternative)
182 |
183 | 1. **Start the HTTP Streamable server**:
184 | ```bash
185 | make dev # Runs HTTP streamable server on port 8003
186 | ```
187 |
188 | 2. **Configure with mcp-remote bridge**:
189 | Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
190 |
191 | ```json
192 | {
193 | "mcpServers": {
194 | "maverick-mcp": {
195 | "command": "npx",
196 | "args": ["-y", "mcp-remote", "http://localhost:8003/mcp/"]
197 | }
198 | }
199 | }
200 | ```
201 |
202 | **Benefits**:
203 | - ✅ Uses HTTP Streamable transport
204 | - ✅ Alternative to SSE endpoint
205 | - ✅ Supports remote access
206 |
207 | #### Method C: Remote via Claude.ai (Alternative)
208 |
209 | For native remote server support, use [Claude.ai web interface](https://claude.ai/settings/integrations) instead of Claude Desktop.
210 |
211 | 3. **Restart Claude Desktop** and test with: "Show me technical analysis for AAPL"
212 |
213 | ### Other Popular MCP Clients
214 |
215 | > ⚠️ **Critical Transport Warning**: MCP clients have specific transport limitations. Using incorrect configurations will cause connection failures. Always verify which transports your client supports.
216 |
217 | #### Transport Compatibility Matrix
218 |
219 | | MCP Client | STDIO | HTTP | SSE | Optimal Method |
220 | |----------------------|-------|------|-----|-----------------------------------------------|
221 | | **Claude Desktop** | ❌ | ❌ | ✅ | **SSE via mcp-remote** (stable, tested) |
222 | | **Cursor IDE** | ✅ | ❌ | ✅ | SSE and STDIO supported |
223 | | **Claude Code CLI** | ✅ | ✅ | ✅ | All transports supported |
224 | | **Continue.dev** | ✅ | ❌ | ✅ | SSE and STDIO supported |
225 | | **Windsurf IDE** | ✅ | ❌ | ✅ | SSE and STDIO supported |
226 |
227 | #### Claude Desktop (Most Commonly Used)
228 |
229 | **✅ TESTED CONFIGURATION**: Use SSE endpoint with mcp-remote bridge - prevents tools from disappearing and ensures stable connection.
230 |
231 | **Configuration Location:**
232 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
233 | - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
234 | - Linux: `~/.config/Claude/claude_desktop_config.json`
235 |
236 | **SSE Connection with mcp-remote (Tested and Stable):**
237 |
238 | 1. Start the server:
239 | ```bash
240 | make dev # Starts SSE server on port 8003
241 | ```
242 |
243 | 2. Configure Claude Desktop:
244 | ```json
245 | {
246 | "mcpServers": {
247 | "maverick-mcp": {
248 | "command": "npx",
249 | "args": ["-y", "mcp-remote", "http://localhost:8003/sse"]
250 | }
251 | }
252 | }
253 | ```
254 |
255 | **Important**: This exact configuration has been tested and confirmed to prevent the common issue where tools appear initially but then disappear from Claude Desktop. The server now accepts both `/sse` and `/sse/` paths without redirects.
256 |
257 | **Restart Required:** Always restart Claude Desktop after config changes.
258 |
259 | #### Cursor IDE - SSE and STDIO Support
260 |
261 | **Option 1: Direct SSE (Recommended):**
262 | ```json
263 | {
264 | "mcpServers": {
265 | "maverick-mcp": {
266 | "url": "http://localhost:8003/sse"
267 | }
268 | }
269 | }
270 | ```
271 |
272 | **Location:** Cursor → Settings → MCP Servers
273 |
274 | #### Claude Code CLI - Full Transport Support
275 |
276 | **SSE Transport (Recommended):**
277 | ```bash
278 | claude mcp add --transport sse maverick-mcp http://localhost:8003/sse
279 | ```
280 |
281 | **HTTP Transport (Alternative):**
282 | ```bash
283 | claude mcp add --transport http maverick-mcp http://localhost:8003/mcp/
284 | ```
285 |
286 | **STDIO Transport (Development only):**
287 | ```bash
288 | claude mcp add maverick-mcp uv run python -m maverick_mcp.api.server --transport stdio
289 | ```
290 |
291 | #### Continue.dev - SSE and STDIO Support
292 |
293 | **Option 1: Direct SSE (Recommended):**
294 | ```json
295 | {
296 | "mcpServers": {
297 | "maverick-mcp": {
298 | "url": "http://localhost:8003/sse"
299 | }
300 | }
301 | }
302 | ```
303 |
304 | **Option 2: SSE via mcp-remote (Alternative):**
305 | ```json
306 | {
307 | "experimental": {
308 | "modelContextProtocolServer": {
309 | "transport": {
310 | "type": "stdio",
311 | "command": "npx",
312 | "args": ["-y", "mcp-remote", "http://localhost:8003/sse"]
313 | }
314 | }
315 | }
316 | }
317 | ```
318 |
319 | **Location:** `~/.continue/config.json`
320 |
321 | #### Windsurf IDE - SSE and STDIO Support
322 |
323 | **Option 1: Direct SSE (Recommended):**
324 | ```json
325 | {
326 | "mcpServers": {
327 | "maverick-mcp": {
328 | "serverUrl": "http://localhost:8003/sse"
329 | }
330 | }
331 | }
332 | ```
333 |
334 | **Option 2: SSE via mcp-remote (Alternative):**
335 | ```json
336 | {
337 | "mcpServers": {
338 | "maverick-mcp": {
339 | "command": "npx",
340 | "args": ["-y", "mcp-remote", "http://localhost:8003/sse"]
341 | }
342 | }
343 | }
344 | ```
345 |
346 | **Location:** Windsurf → Settings → Advanced Settings → MCP Servers
347 |
348 | ### How It Works
349 |
350 | **Connection Architecture:**
351 | - **STDIO Mode (Optimal for Claude Desktop)**: Direct subprocess communication - fastest, most reliable
352 | - **Streamable-HTTP Endpoint**: `http://localhost:8003/` - For remote access via mcp-remote bridge
353 | - **SSE Endpoint**: `http://localhost:8003/sse` - For other clients with native SSE support (accepts both `/sse` and `/sse/`)
354 |
355 | > **Key Finding**: Direct STDIO is the optimal transport for Claude Desktop. HTTP/SSE require the mcp-remote bridge tool, adding latency and complexity. SSE is particularly problematic as it's incompatible with mcp-remote (GET vs POST mismatch).
356 |
357 | **Transport Limitations by Client:**
358 | - **Claude Desktop**: STDIO-only, cannot directly connect to HTTP/SSE
359 | - **Most Other Clients**: Support STDIO + SSE (but not HTTP)
360 | - **Claude Code CLI**: Full transport support (STDIO, HTTP, SSE)
361 |
362 | **mcp-remote Bridge Tool:**
363 | - **Purpose**: Converts STDIO client calls to HTTP/SSE server requests
364 | - **Why Needed**: Bridges the gap between STDIO-only clients and HTTP/SSE servers
365 | - **Connection Flow**: Client (STDIO) ↔ mcp-remote ↔ HTTP/SSE Server
366 | - **Installation**: `npx mcp-remote <server-url>`
367 |
368 | **Key Transport Facts:**
369 | - **STDIO**: All clients support this for local connections
370 | - **HTTP**: Only Claude Code CLI supports direct HTTP connections
371 | - **SSE**: Cursor, Continue.dev, Windsurf support direct SSE connections
372 | - **Claude Desktop Limitation**: Cannot connect to HTTP/SSE without mcp-remote bridge
373 |
374 | **Alternatives for Remote Access:**
375 | - Use Claude.ai web interface for native remote server support (no mcp-remote needed)
376 |
377 | ## Key Features
378 |
379 | ### Stock Analysis
380 |
381 | - Historical price data with database caching
382 | - Technical indicators (SMA, EMA, RSI, MACD, Bollinger Bands)
383 | - Support/resistance levels
384 | - Volume analysis and patterns
385 |
386 | ### Stock Screening (Pre-seeded S&P 500 Data)
387 |
388 | - **Maverick Bullish**: High momentum stocks with strong technicals from 520 S&P 500 stocks
389 | - **Maverick Bearish**: Weak setups for short opportunities with pre-analyzed data
390 | - **Supply/Demand Breakouts**: Stocks in confirmed uptrend phases with technical breakout patterns
391 | - All screening data is pre-calculated and stored in database for instant results
392 |
393 | ### Portfolio Analysis
394 |
395 | - Portfolio optimization using Modern Portfolio Theory
396 | - Risk analysis and correlation matrices
397 | - Performance metrics and comparisons
398 |
399 | ### Market Data
400 |
401 | - Real-time quotes and market indices
402 | - Sector performance analysis
403 | - Economic indicators from FRED API
404 |
405 | ## Available Tools
406 |
407 | All tools are organized into logical groups (39+ tools total):
408 |
409 | ### Data Tools (`/data/*`) - S&P 500 Pre-seeded
410 |
411 | - `get_stock_data` - Historical price data with database caching
412 | - `get_stock_info` - Company information from pre-seeded S&P 500 database
413 | - `get_multiple_stocks_data` - Batch data fetching with optimized queries
414 |
415 | ### Technical Analysis (`/technical/*`)
416 |
417 | - `calculate_sma`, `calculate_ema` - Moving averages
418 | - `calculate_rsi` - Relative Strength Index
419 | - `calculate_macd` - MACD indicator
420 | - `calculate_bollinger_bands` - Bollinger Bands
421 | - `get_full_technical_analysis` - Complete analysis suite
422 |
423 | ### Screening (`/screening/*`) - Pre-calculated Results
424 |
425 | - `get_maverick_recommendations` - Bullish momentum stocks from S&P 500 database
426 | - `get_maverick_bear_recommendations` - Bearish setups with pre-analyzed data
427 | - `get_trending_breakout_recommendations` - Supply/demand breakout candidates from 520 stocks
428 | - All screening results are pre-calculated and stored for instant access
429 |
430 | ### Advanced Research Tools (`/research/*`) - NEW AI-Powered Analysis
431 |
432 | - `research_comprehensive` - Full parallel research with multiple AI agents (7-256x faster)
433 | - `research_company` - Company-specific deep research with financial analysis
434 | - `analyze_market_sentiment` - Multi-source sentiment analysis with confidence tracking
435 | - `coordinate_agents` - Multi-agent supervisor for complex research orchestration
436 |
437 | **Research Features:**
438 | - **Parallel Execution**: 7-256x speedup with intelligent agent orchestration
439 | - **Adaptive Timeouts**: 120s-600s based on research depth and complexity
440 | - **Smart Model Selection**: Automatic selection from 400+ models via OpenRouter
441 | - **Cost Optimization**: 40-60% cost reduction through intelligent model routing
442 | - **Early Termination**: Confidence-based early stopping to save time and costs
443 | - **Content Filtering**: High-credibility source prioritization
444 | - **Error Recovery**: Circuit breakers and comprehensive error handling
445 |
446 | ### Portfolio Management (`/portfolio/*`) - Personal Holdings Tracking (NEW)
447 |
448 | - `portfolio_add_position` - Add or update positions with automatic cost basis averaging
449 | - `portfolio_get_my_portfolio` - View portfolio with live P&L calculations
450 | - `portfolio_remove_position` - Remove partial or full positions
451 | - `portfolio_clear_portfolio` - Clear all positions with safety confirmation
452 |
453 | **Key Features:**
454 | - Persistent storage with cost basis tracking (average cost method)
455 | - Live unrealized P&L calculations with real-time prices
456 | - Automatic cost averaging on repeat purchases
457 | - Support for fractional shares and high-precision decimals
458 | - Multi-portfolio support (track IRA, 401k, taxable separately)
459 | - Portfolio resource (`portfolio://my-holdings`) for AI context
460 |
461 | ### Portfolio Analysis (`/portfolio/*`) - Intelligent Integration
462 |
463 | - `risk_adjusted_analysis` - Risk-based position sizing (shows your existing positions)
464 | - `compare_tickers` - Side-by-side comparison (auto-uses portfolio if no tickers provided)
465 | - `portfolio_correlation_analysis` - Correlation matrix (auto-analyzes your holdings)
466 |
467 | **Smart Features:**
468 | - Tools auto-detect your portfolio positions
469 | - Position-aware recommendations (averaging up/down, profit taking)
470 | - No manual ticker entry needed for portfolio analysis
471 |
472 | ### Backtesting (`/backtesting/*`) - VectorBT-Powered Strategy Testing
473 |
474 | - `run_backtest` - Execute backtests with any strategy
475 | - `compare_strategies` - A/B testing for strategy comparison
476 | - `optimize_strategy` - Walk-forward optimization and parameter tuning
477 | - `analyze_backtest_results` - Comprehensive performance analytics
478 | - `get_backtest_report` - Generate detailed HTML reports
479 |
480 | **Capabilities:**
481 | - 15+ built-in strategies including ML algorithms
482 | - VectorBT engine for vectorized performance
483 | - Parallel processing with 7-256x speedup
484 | - Monte Carlo simulations and robustness testing
485 | - Multi-timeframe support (1min to monthly)
486 |
487 | ### Market Data
488 |
489 | - `get_market_overview` - Indices, sectors, market breadth
490 | - `get_watchlist` - Sample portfolio with real-time data
491 |
492 | ## Development Commands
493 |
494 | ### Running the Server
495 |
496 | ```bash
497 | # Development mode (recommended - Makefile commands)
498 | make dev # SSE transport (default, recommended for Claude Desktop)
499 | make dev-http # Streamable-HTTP transport (for testing with curl/Postman)
500 | make dev-stdio # STDIO transport (direct connection)
501 |
502 | # Alternative: Direct commands (manual)
503 | uv run python -m maverick_mcp.api.server --transport sse --port 8003
504 | uv run python -m maverick_mcp.api.server --transport streamable-http --port 8003
505 | uv run python -m maverick_mcp.api.server --transport stdio
506 |
507 | # Script-based startup (with environment variable)
508 | ./scripts/dev.sh # Defaults to SSE
509 | MAVERICK_TRANSPORT=streamable-http ./scripts/dev.sh
510 | ```
511 |
512 | **When to use each transport:**
513 | - **SSE** (`make dev` or `make dev-sse`): Best for Claude Desktop - tested and stable
514 | - **Streamable-HTTP** (`make dev-http`): Ideal for testing with curl/Postman, debugging transport issues
515 | - **STDIO** (`make dev-stdio`): Direct connection without network layer, good for development
516 |
517 | ### Testing
518 |
519 | ```bash
520 | # Quick testing
521 | make test # Unit tests only (5-10 seconds)
522 | make test-specific TEST=test_name # Run specific test
523 | make test-watch # Auto-run on changes
524 |
525 | # Using uv (recommended)
526 | uv run pytest # Manual pytest execution
527 | uv run pytest --cov=maverick_mcp # With coverage
528 | uv run pytest -m integration # Integration tests (requires PostgreSQL/Redis)
529 |
530 | # Alternative: Direct pytest (if activated in venv)
531 | pytest # Manual pytest execution
532 | pytest --cov=maverick_mcp # With coverage
533 | pytest -m integration # Integration tests (requires PostgreSQL/Redis)
534 | ```
535 |
536 | ### Code Quality
537 |
538 | ```bash
539 | # Automated quality checks
540 | make format # Auto-format with ruff
541 | make lint # Check code quality with ruff
542 | make typecheck # Type check with ty (Astral's modern type checker)
543 | make check # Run all checks
544 |
545 | # Using uv (recommended)
546 | uv run ruff check . # Linting
547 | uv run ruff format . # Formatting
548 | uv run ty check . # Type checking (Astral's modern type checker)
549 |
550 | # Ultra-fast one-liner (no installation needed)
551 | uvx ty check . # Run ty directly without installing
552 |
553 | # Alternative: Direct commands (if activated in venv)
554 | ruff check . # Linting
555 | ruff format . # Formatting
556 | ty check . # Type checking
557 | ```
558 |
559 | ## Configuration
560 |
561 | ### Database Options
562 |
563 | **SQLite (Default - No Setup Required, includes S&P 500 data)**:
564 |
565 | ```bash
566 | # Uses SQLite automatically with S&P 500 data seeding on first run
567 | make dev
568 | ```
569 |
570 | **PostgreSQL (Optional - Better Performance)**:
571 |
572 | ```bash
573 | # In .env file
574 | DATABASE_URL=postgresql://localhost/maverick_mcp
575 |
576 | # Create database
577 | createdb maverick_mcp
578 | make migrate
579 | ```
580 |
581 | ### Caching Options
582 |
583 | **No Caching (Default)**:
584 |
585 | - Works out of the box, uses in-memory caching
586 |
587 | **Redis Caching (Optional - Better Performance)**:
588 |
589 | ```bash
590 | # Install and start Redis
591 | brew install redis
592 | brew services start redis
593 |
594 | # Or use make command
595 | make redis-start
596 |
597 | # Server automatically detects Redis and uses it
598 | ```
599 |
600 | ## Code Guidelines
601 |
602 | ### General Principles
603 |
604 | - Python 3.12+ with modern features
605 | - Type hints for all functions
606 | - Google-style docstrings for public APIs
607 | - Comprehensive error handling
608 | - Performance-first design with caching
609 |
610 | ### Financial Analysis
611 |
612 | - Use pandas_ta for technical indicators
613 | - Document all financial calculations
614 | - Validate input data ranges
615 | - Cache expensive computations
616 | - Use vectorized operations for performance
617 |
618 | ### MCP Integration
619 |
620 | - Register tools with `@mcp.tool()` decorator
621 | - Return JSON-serializable results
622 | - Implement graceful error handling
623 | - Use database caching for persistence
624 | - Follow FastMCP 2.0 patterns
625 |
626 | ## Troubleshooting
627 |
628 | ### Common Issues
629 |
630 | **Server won't start**:
631 |
632 | ```bash
633 | make stop # Stop any running processes
634 | make clean # Clean temporary files
635 | make dev # Restart
636 | ```
637 |
638 | **Port already in use**:
639 |
640 | ```bash
641 | lsof -i :8003 # Find what's using port 8003
642 | make stop # Stop MaverickMCP services
643 | ```
644 |
645 | **Redis connection errors** (optional):
646 |
647 | ```bash
648 | brew services start redis # Start Redis
649 | # Or disable caching by not setting REDIS_HOST
650 | ```
651 |
652 | **Database errors**:
653 |
654 | ```bash
655 | # Use SQLite (no setup required)
656 | unset DATABASE_URL
657 | make dev
658 |
659 | # Or fix PostgreSQL
660 | createdb maverick_mcp
661 | make migrate
662 | ```
663 |
664 | **Claude Desktop not connecting**:
665 |
666 | 1. Verify server is running: `lsof -i :8003` (check if port 8003 is in use)
667 | 2. Check `claude_desktop_config.json` syntax and correct port (8003)
668 | 3. **Use the tested SSE configuration**: `http://localhost:8003/sse` with mcp-remote
669 | 4. Restart Claude Desktop completely
670 | 5. Test with: "Get AAPL stock data"
671 |
672 | **Tools appearing then disappearing**:
673 |
674 | 1. **FIXED**: Server now accepts both `/sse` and `/sse/` without 307 redirects
675 | 2. Use the recommended SSE configuration with mcp-remote bridge
676 | 3. Ensure you're using the exact configuration shown above
677 | 4. The SSE + mcp-remote setup has been tested and prevents tool disappearing
678 | 5. **No trailing slash required**: Server automatically handles path normalization
679 |
680 | **Research Tool Issues**:
681 |
682 | 1. **Timeouts**: Research tools have adaptive timeouts (120s-600s)
683 | 2. Deep research may take 2-10 minutes depending on complexity
684 | 3. Monitor progress in server logs with `make tail-log`
685 | 4. Ensure `OPENROUTER_API_KEY` and `EXA_API_KEY` are set for full functionality
686 |
687 | **Missing S&P 500 screening data**:
688 |
689 | ```bash
690 | # Manually seed S&P 500 database if needed
691 | uv run python scripts/seed_sp500.py
692 | ```
693 |
694 | ### Performance Tips
695 |
696 | - **Use Redis caching** for better performance
697 | - **PostgreSQL over SQLite** for larger datasets
698 | - **Parallel screening** is enabled by default (4x speedup)
699 | - **Parallel research** achieves 7-256x speedup with agent orchestration
700 | - **In-memory caching** reduces API calls
701 | - **Smart model selection** reduces costs by 40-60% with OpenRouter
702 |
703 | ## Quick Testing
704 |
705 | Test the server is working:
706 |
707 | ```bash
708 | # Test server is running
709 | lsof -i :8003
710 |
711 | # Test MCP endpoint (after connecting with mcp-remote)
712 | # Use Claude Desktop with: "List available tools"
713 | ```
714 |
715 | ### Test Backtesting Features
716 |
717 | Once connected to Claude Desktop, test the backtesting framework:
718 |
719 | ```
720 | # Basic backtest
721 | "Run a backtest on SPY using the momentum strategy for 2024"
722 |
723 | # Strategy comparison
724 | "Compare RSI vs MACD strategies on AAPL for the last year"
725 |
726 | # ML strategy test
727 | "Test the adaptive ML strategy on tech sector stocks"
728 |
729 | # Performance analysis
730 | "Show me detailed metrics for a mean reversion strategy on QQQ"
731 | ```
732 |
733 | ## Recent Updates
734 |
735 | ### Production-Ready Backtesting Framework (NEW)
736 |
737 | - **VectorBT Integration**: High-performance vectorized backtesting engine
738 | - **15+ Built-in Strategies**: Including ML-powered adaptive, ensemble, and regime-aware algorithms
739 | - **Parallel Processing**: 7-256x speedup for multi-strategy evaluation
740 | - **Advanced Analytics**: Sharpe, Sortino, Calmar ratios, maximum drawdown, win rate analysis
741 | - **Walk-Forward Optimization**: Out-of-sample testing with parameter tuning
742 | - **Monte Carlo Simulations**: Robustness testing with confidence intervals
743 | - **LangGraph Workflow**: Multi-agent orchestration for intelligent strategy selection
744 | - **Comprehensive Reporting**: HTML reports with interactive visualizations
745 |
746 | ### Advanced Research Agents (Major Feature Release)
747 |
748 | - **Parallel Research Execution**: Achieved 7-256x speedup (exceeded 2x target) with intelligent agent orchestration
749 | - **Adaptive Timeout Protection**: Dynamic timeouts (120s-600s) based on research depth and complexity
750 | - **Intelligent Model Selection**: OpenRouter integration with 400+ models, 40-60% cost reduction
751 | - **Comprehensive Error Handling**: Circuit breakers, retry logic, and graceful degradation
752 | - **Early Termination**: Confidence-based stopping to optimize time and costs
753 | - **Content Filtering**: High-credibility source prioritization for quality results
754 | - **Multi-Agent Orchestration**: Supervisor pattern for complex research coordination
755 | - **New Research Tools**: `research_comprehensive`, `research_company`, `analyze_market_sentiment`, `coordinate_agents`
756 |
757 | ### Performance Improvements
758 |
759 | - **Parallel Agent Execution**: Increased concurrent agents from 4 to 6
760 | - **Optimized Semaphores**: BoundedSemaphore for better resource management
761 | - **Reduced Rate Limiting**: Delays decreased from 0.5s to 0.05s
762 | - **Batch Processing**: Improved throughput for multiple research tasks
763 | - **Smart Caching**: Redis-powered with in-memory fallback
764 | - **Stock Screening**: 4x faster with parallel processing
765 |
766 | ### Testing & Quality
767 |
768 | - **84% Test Coverage**: 93 tests with comprehensive coverage
769 | - **Zero Linting Errors**: Fixed 947 issues for clean codebase
770 | - **Full Type Annotations**: Complete type coverage for research components
771 | - **Error Recovery Testing**: Comprehensive failure scenario coverage
772 |
773 | ### Personal Use Optimization
774 |
775 | - **No Authentication/Billing**: Completely removed for personal use simplicity
776 | - **Pre-seeded S&P 500 Database**: 520 stocks with comprehensive screening data on first startup
777 | - **Simplified Architecture**: Clean, focused codebase without commercial complexity
778 | - **Multi-Transport Support**: HTTP, SSE, and STDIO for all MCP clients
779 | - **SQLite Default**: No database setup required, PostgreSQL optional for performance
780 |
781 | ### AI/LLM Integration
782 |
783 | - **OpenRouter Integration**: Access to 400+ AI models with intelligent cost optimization
784 | - **Smart Model Selection**: Automatic model selection based on task requirements (sentiment analysis, market research, technical analysis)
785 | - **Cost-Efficient by Default**: Prioritizes cost-effectiveness while maintaining quality, 40-60% cost savings over premium-only approaches
786 | - **Multiple Model Support**: Claude Opus 4.1, Claude Sonnet 4, Claude 3.5 Haiku, GPT-5, GPT-5 Nano, Gemini 2.5 Pro, DeepSeek R1, and more
787 |
788 | ### Developer Experience
789 |
790 | - Comprehensive Makefile for all common tasks
791 | - Smart error handling with automatic fix suggestions
792 | - Hot reload development mode
793 | - Extensive test suite with quick unit tests
794 | - Type checking with ty (Astral's extremely fast type checker) for better IDE support
795 |
796 | ## Additional Resources
797 |
798 | - **Architecture docs**: `docs/` directory
799 | - **Portfolio Guide**: `docs/PORTFOLIO.md` - Complete guide to portfolio features
800 | - **Test examples**: `tests/` directory
801 | - **Development tools**: `tools/` directory
802 | - **Example scripts**: `scripts/` directory
803 |
804 | For detailed technical information and advanced usage, see the full documentation in the `docs/` directory.
805 |
806 | ---
807 |
808 | **Note**: This project is designed for personal use. It provides powerful stock analysis tools for Claude Desktop with pre-seeded S&P 500 data, without the complexity of multi-user systems, authentication, or billing. The database automatically seeds with 520 S&P 500 stocks and screening recommendations on first startup.
809 |
```
--------------------------------------------------------------------------------
/maverick_mcp/application/commands/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/application/dto/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/application/queries/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/entities/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/events/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/services/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/value_objects/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/cache/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/persistence/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/providers/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
```python
1 |
```
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
```yaml
1 | github: wshobson
2 |
```
--------------------------------------------------------------------------------
/maverick_mcp/api/utils/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """API utility modules."""
2 |
```
--------------------------------------------------------------------------------
/tests/integration/__init__.py:
--------------------------------------------------------------------------------
```python
1 | # Integration tests module marker
2 |
```
--------------------------------------------------------------------------------
/maverick_mcp/tests/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Test package for Maverick-MCP."""
2 |
```
--------------------------------------------------------------------------------
/maverick_mcp/utils/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Utility modules for Maverick-MCP."""
2 |
```
--------------------------------------------------------------------------------
/maverick_mcp/api/dependencies/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """API dependencies for dependency injection."""
2 |
```
--------------------------------------------------------------------------------
/maverick_mcp/database/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Database package for MaverickMCP."""
2 |
3 | from .base import Base
4 |
5 | __all__ = ["Base"]
6 |
```
--------------------------------------------------------------------------------
/maverick_mcp/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Maverick-MCP package for financial analysis using MCP protocol.
3 | """
4 |
5 | __all__ = []
6 |
```
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
```yaml
1 | version: 2
2 | updates:
3 | - package-ecosystem: uv
4 | directory: "/"
5 | schedule:
6 | interval: weekly
7 |
```
--------------------------------------------------------------------------------
/maverick_mcp/api/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | API components for Maverick-MCP.
3 |
4 | This package contains the API server implementation.
5 | """
6 |
7 | __all__: list[str] = []
8 |
```
--------------------------------------------------------------------------------
/maverick_mcp/application/screening/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Screening application layer.
3 |
4 | This module contains application services, queries, and DTOs
5 | for the screening domain.
6 | """
7 |
```
--------------------------------------------------------------------------------
/maverick_mcp/tools/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Financial analysis tools for Maverick-MCP.
3 | """
4 |
5 | from .portfolio_manager import PortfolioManager
6 |
7 | __all__ = ["PortfolioManager"]
8 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/stock_analysis/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Domain layer stock analysis services.
3 | """
4 |
5 | from .stock_analysis_service import StockAnalysisService
6 |
7 | __all__ = ["StockAnalysisService"]
8 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/health/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Health checking infrastructure."""
2 |
3 | from .health_checker import HealthChecker, HealthStatus
4 |
5 | __all__ = ["HealthChecker", "HealthStatus"]
6 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/screening/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Screening domain module.
3 |
4 | This module contains the pure business logic for stock screening,
5 | following Domain-Driven Design principles.
6 | """
7 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/caching/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Infrastructure layer caching services.
3 | """
4 |
5 | from .cache_management_service import CacheManagementService
6 |
7 | __all__ = ["CacheManagementService"]
8 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/data_fetching/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Infrastructure layer data fetching services.
3 | """
4 |
5 | from .stock_data_service import StockDataFetchingService
6 |
7 | __all__ = ["StockDataFetchingService"]
8 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/screening/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Screening infrastructure layer.
3 |
4 | This module contains infrastructure adapters for the screening domain,
5 | including repository implementations and external service adapters.
6 | """
7 |
```
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "configurations": [
3 | {
4 | "name": "Maverick-MCP CLI",
5 | "type": "debugpy",
6 | "request": "launch",
7 | "module": "maverick_mcp.cli.server",
8 | "args": ["--debug"]
9 | }
10 | ]
11 | }
12 |
```
--------------------------------------------------------------------------------
/maverick_mcp/infrastructure/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Infrastructure layer services.
3 | """
4 |
5 | from .caching import CacheManagementService
6 | from .data_fetching import StockDataFetchingService
7 |
8 | __all__ = ["CacheManagementService", "StockDataFetchingService"]
9 |
```
--------------------------------------------------------------------------------
/maverick_mcp/core/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Core functionality for Maverick-MCP.
3 |
4 | This package contains the core business logic and utilities for the Maverick-MCP service.
5 | """
6 |
7 | from . import technical_analysis, visualization
8 |
9 | __all__ = ["technical_analysis", "visualization"]
10 |
```
--------------------------------------------------------------------------------
/tests/integration/test_api_technical.py:
--------------------------------------------------------------------------------
```python
1 | """Placeholder integration tests for technical analysis endpoints."""
2 |
3 | import pytest
4 |
5 | pytest.skip(
6 | "Technical analysis integration tests require external services not available in the open-source build.",
7 | allow_module_level=True,
8 | )
9 |
```
--------------------------------------------------------------------------------
/maverick_mcp/memory/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Memory and persistence management for Maverick-MCP agents.
3 | """
4 |
5 | from langgraph.checkpoint.memory import MemorySaver
6 |
7 | from .stores import ConversationStore, MemoryStore
8 |
9 | __all__ = [
10 | "MemorySaver",
11 | "MemoryStore",
12 | "ConversationStore",
13 | ]
14 |
```
--------------------------------------------------------------------------------
/maverick_mcp/langchain_tools/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | LangChain tool adapters for Maverick-MCP.
3 | """
4 |
5 | from .adapters import create_langchain_tool, mcp_to_langchain_adapter
6 | from .registry import ToolRegistry, get_tool_registry
7 |
8 | __all__ = [
9 | "mcp_to_langchain_adapter",
10 | "create_langchain_tool",
11 | "ToolRegistry",
12 | "get_tool_registry",
13 | ]
14 |
```
--------------------------------------------------------------------------------
/tests/performance/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Performance Testing Suite for MaverickMCP Backtesting System.
3 |
4 | This package contains comprehensive performance tests including:
5 | - Load testing for concurrent users
6 | - Benchmark tests against performance targets
7 | - Stress testing for resource usage monitoring
8 | - Profiling tests for bottleneck identification
9 | """
10 |
```
--------------------------------------------------------------------------------
/maverick_mcp/backtesting/strategies/ml_strategies.py:
--------------------------------------------------------------------------------
```python
1 | """ML strategies bridge module for easier imports."""
2 |
3 | from .ml.adaptive import AdaptiveStrategy as OnlineLearningStrategy
4 | from .ml.ensemble import StrategyEnsemble as EnsembleStrategy
5 | from .ml.regime_aware import RegimeAwareStrategy
6 |
7 | __all__ = ["OnlineLearningStrategy", "RegimeAwareStrategy", "EnsembleStrategy"]
8 |
```
--------------------------------------------------------------------------------
/maverick_mcp/providers/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Data provider modules for Maverick-MCP.
3 |
4 | This package contains provider classes for fetching different types of financial data.
5 | """
6 |
7 | from .macro_data import MacroDataProvider
8 | from .market_data import MarketDataProvider
9 | from .stock_data import StockDataProvider
10 |
11 | __all__ = ["StockDataProvider", "MacroDataProvider", "MarketDataProvider"]
12 |
```
--------------------------------------------------------------------------------
/maverick_mcp/database/base.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Shared database base class for all SQLAlchemy models.
3 |
4 | This module provides a common Base class to avoid circular imports
5 | and ensure all models are registered with the same metadata.
6 | """
7 |
8 | from sqlalchemy.orm import DeclarativeBase
9 |
10 |
11 | class Base(DeclarativeBase):
12 | """Base class for all SQLAlchemy models using SQLAlchemy 2.0+ style."""
13 |
14 | pass
15 |
```
--------------------------------------------------------------------------------
/maverick_mcp/providers/factories/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Provider factories for Maverick-MCP.
3 |
4 | This package contains factory classes that handle provider instantiation,
5 | dependency injection, and lifecycle management following the Factory pattern.
6 | """
7 |
8 | from .config_factory import ConfigurationFactory
9 | from .provider_factory import ProviderFactory
10 |
11 | __all__ = [
12 | "ProviderFactory",
13 | "ConfigurationFactory",
14 | ]
15 |
```
--------------------------------------------------------------------------------
/alembic/versions/08e3945a0c93_merge_heads.py:
--------------------------------------------------------------------------------
```python
1 | """merge_heads
2 |
3 | Revision ID: 08e3945a0c93
4 | Revises: 005_add_user_table, 416a0259129d
5 | Create Date: 2025-06-08 13:23:35.875210
6 |
7 | """
8 |
9 | # revision identifiers, used by Alembic.
10 | revision = "08e3945a0c93"
11 | down_revision = ("005_add_user_table", "416a0259129d")
12 | branch_labels = None
13 | depends_on = None
14 |
15 |
16 | def upgrade() -> None:
17 | pass
18 |
19 |
20 | def downgrade() -> None:
21 | pass
22 |
```
--------------------------------------------------------------------------------
/maverick_mcp/backtesting/strategies/ml/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Machine learning enhanced trading strategies."""
2 |
3 | from .adaptive import AdaptiveStrategy
4 | from .ensemble import StrategyEnsemble
5 | from .feature_engineering import FeatureExtractor, MLPredictor
6 | from .regime_aware import RegimeAwareStrategy
7 |
8 | __all__ = [
9 | "AdaptiveStrategy",
10 | "FeatureExtractor",
11 | "MLPredictor",
12 | "RegimeAwareStrategy",
13 | "StrategyEnsemble",
14 | ]
15 |
```
--------------------------------------------------------------------------------
/alembic/versions/fix_database_integrity_issues.py:
--------------------------------------------------------------------------------
```python
1 | """Legacy migration stub for OSS build without billing tables."""
2 |
3 | # Revision identifiers, used by Alembic.
4 | revision = "fix_database_integrity"
5 | down_revision = "e0c75b0bdadb"
6 | branch_labels = None
7 | depends_on = None
8 |
9 |
10 | def upgrade() -> None:
11 | """No-op migration for the open-source build."""
12 | pass
13 |
14 |
15 | def downgrade() -> None:
16 | """No-op downgrade for the open-source build."""
17 | pass
18 |
```
--------------------------------------------------------------------------------
/alembic/versions/adda6d3fd84b_merge_proprietary_terms_removal_with_.py:
--------------------------------------------------------------------------------
```python
1 | """Merge proprietary terms removal with async jobs
2 |
3 | Revision ID: adda6d3fd84b
4 | Revises: 0004, 011_remove_proprietary_terms
5 | Create Date: 2025-08-10 15:31:44.179603
6 |
7 | """
8 |
9 | # revision identifiers, used by Alembic.
10 | revision = "adda6d3fd84b"
11 | down_revision = ("0004", "011_remove_proprietary_terms")
12 | branch_labels = None
13 | depends_on = None
14 |
15 |
16 | def upgrade() -> None:
17 | pass
18 |
19 |
20 | def downgrade() -> None:
21 | pass
22 |
```
--------------------------------------------------------------------------------
/alembic/versions/e0c75b0bdadb_fix_financial_data_precision_only.py:
--------------------------------------------------------------------------------
```python
1 | """Legacy precision migration stub (billing tables removed in OSS build)."""
2 |
3 | # Revision identifiers, used by Alembic.
4 | revision = "e0c75b0bdadb"
5 | down_revision = "add_stripe_webhook_events"
6 | branch_labels = None
7 | depends_on = None
8 |
9 |
10 | def upgrade() -> None:
11 | """No-op migration for the open-source build."""
12 | pass
13 |
14 |
15 | def downgrade() -> None:
16 | """No-op downgrade for the open-source build."""
17 | pass
18 |
```
--------------------------------------------------------------------------------
/alembic/versions/9374a5c9b679_merge_heads_for_testing.py:
--------------------------------------------------------------------------------
```python
1 | """merge_heads_for_testing
2 |
3 | Revision ID: 9374a5c9b679
4 | Revises: 012_remove_frontend_billing_system, adda6d3fd84b
5 | Create Date: 2025-08-10 19:10:32.920060
6 |
7 | """
8 |
9 | # revision identifiers, used by Alembic.
10 | revision = "9374a5c9b679"
11 | down_revision = ("012_remove_frontend_billing_system", "adda6d3fd84b")
12 | branch_labels = None
13 | depends_on = None
14 |
15 |
16 | def upgrade() -> None:
17 | pass
18 |
19 |
20 | def downgrade() -> None:
21 | pass
22 |
```
--------------------------------------------------------------------------------
/alembic/versions/abf9b9afb134_merge_multiple_heads.py:
--------------------------------------------------------------------------------
```python
1 | """merge_multiple_heads
2 |
3 | Revision ID: abf9b9afb134
4 | Revises: 008_performance_optimization_indexes, f0696e2cac15
5 | Create Date: 2025-07-04 14:57:35.435208
6 |
7 | """
8 |
9 | # revision identifiers, used by Alembic.
10 | revision = "abf9b9afb134"
11 | down_revision = ("008_performance_optimization_indexes", "f0696e2cac15")
12 | branch_labels = None
13 | depends_on = None
14 |
15 |
16 | def upgrade() -> None:
17 | pass
18 |
19 |
20 | def downgrade() -> None:
21 | pass
22 |
```
--------------------------------------------------------------------------------
/scripts/requirements_tiingo.txt:
--------------------------------------------------------------------------------
```
1 | # Requirements for the Tiingo data loader
2 | # Core dependencies
3 | aiohttp>=3.8.0
4 | pandas>=2.0.0
5 | pandas-ta>=0.3.14b0
6 | sqlalchemy>=2.0.0
7 | psycopg2-binary>=2.9.0 # PostgreSQL adapter
8 |
9 | # Optional dependencies for enhanced functionality
10 | numpy>=1.24.0
11 | python-dateutil>=2.8.0
12 | asyncio-throttle>=1.0.0 # Alternative rate limiting
13 | requests>=2.28.0 # Fallback for sync operations
14 |
15 | # Development and testing
16 | pytest>=7.0.0
17 | pytest-asyncio>=0.21.0
18 | asynctest>=0.13.0
```
--------------------------------------------------------------------------------
/maverick_mcp/agents/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Maverick-MCP Agents Module.
3 |
4 | This module contains LangGraph-based agents for financial analysis workflows.
5 | """
6 |
7 | from .base import INVESTOR_PERSONAS, PersonaAwareAgent, PersonaAwareTool
8 | from .circuit_breaker import circuit_breaker, circuit_manager
9 | from .deep_research import DeepResearchAgent
10 | from .supervisor import SupervisorAgent
11 |
12 | __all__ = [
13 | "PersonaAwareAgent",
14 | "PersonaAwareTool",
15 | "INVESTOR_PERSONAS",
16 | "circuit_breaker",
17 | "circuit_manager",
18 | "DeepResearchAgent",
19 | "SupervisorAgent",
20 | ]
21 |
```
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
```yaml
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: 💬 GitHub Discussions
4 | url: https://github.com/wshobson/maverick-mcp/discussions
5 | about: Ask questions and discuss ideas with the community
6 | - name: 📖 Documentation
7 | url: https://github.com/wshobson/maverick-mcp/blob/main/README.md
8 | about: Read the documentation and setup guides
9 | - name: 🔒 Security Advisories
10 | url: https://github.com/wshobson/maverick-mcp/security/advisories/new
11 | about: Report security vulnerabilities privately (recommended for serious issues)
```
--------------------------------------------------------------------------------
/maverick_mcp/api/services/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Services package for MaverickMCP API.
3 |
4 | This package contains service classes extracted from the large server.py file
5 | to improve code organization and maintainability following SOLID principles.
6 | """
7 |
8 | from .base_service import BaseService
9 | from .market_service import MarketService
10 | from .portfolio_service import PortfolioService
11 | from .prompt_service import PromptService
12 | from .resource_service import ResourceService
13 |
14 | __all__ = [
15 | "BaseService",
16 | "MarketService",
17 | "PortfolioService",
18 | "PromptService",
19 | "ResourceService",
20 | ]
21 |
```
--------------------------------------------------------------------------------
/maverick_mcp/workflows/agents/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Intelligent agents for backtesting workflow orchestration.
3 |
4 | This module contains specialized agents for market analysis, strategy selection,
5 | parameter optimization, and results validation within the LangGraph backtesting workflow.
6 | """
7 |
8 | from .market_analyzer import MarketAnalyzerAgent
9 | from .optimizer_agent import OptimizerAgent
10 | from .strategy_selector import StrategySelectorAgent
11 | from .validator_agent import ValidatorAgent
12 |
13 | __all__ = [
14 | "MarketAnalyzerAgent",
15 | "OptimizerAgent",
16 | "StrategySelectorAgent",
17 | "ValidatorAgent",
18 | ]
19 |
```
--------------------------------------------------------------------------------
/pyrightconfig.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "include": [
3 | "maverick_mcp/api/server.py",
4 | "maverick_mcp/data/cache.py",
5 | "maverick_mcp/data/performance.py",
6 | "maverick_mcp/providers/optimized_stock_data.py",
7 | "maverick_mcp/utils/quick_cache.py",
8 | "maverick_mcp/backtesting/strategy_executor.py",
9 | "maverick_mcp/tools/performance_monitoring.py"
10 | ],
11 | "reportMissingImports": "warning",
12 | "reportMissingModuleSource": "warning",
13 | "reportMissingTypeStubs": "warning",
14 | "pythonVersion": "3.12",
15 | "typeCheckingMode": "standard",
16 | "executionEnvironments": [
17 | {
18 | "root": ".",
19 | "pythonVersion": "3.12",
20 | "extraPaths": ["."]
21 | }
22 | ]
23 | }
24 |
```
--------------------------------------------------------------------------------
/maverick_mcp/providers/implementations/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Provider implementations for Maverick-MCP.
3 |
4 | This package contains concrete implementations of the provider interfaces,
5 | including adapters for existing providers and new implementations that
6 | fully embrace the interface-based architecture.
7 | """
8 |
9 | from .cache_adapter import RedisCacheAdapter
10 | from .macro_data_adapter import MacroDataAdapter
11 | from .market_data_adapter import MarketDataAdapter
12 | from .persistence_adapter import SQLAlchemyPersistenceAdapter
13 | from .stock_data_adapter import StockDataAdapter
14 |
15 | __all__ = [
16 | "RedisCacheAdapter",
17 | "StockDataAdapter",
18 | "MarketDataAdapter",
19 | "MacroDataAdapter",
20 | "SQLAlchemyPersistenceAdapter",
21 | ]
22 |
```
--------------------------------------------------------------------------------
/maverick_mcp/config/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Configuration utilities for Maverick-MCP.
3 | """
4 |
5 | from .constants import CACHE_TTL, CONFIG, clean_env_var
6 | from .database import (
7 | DatabasePoolConfig,
8 | create_engine_with_enhanced_config,
9 | get_default_pool_config,
10 | get_development_pool_config,
11 | get_high_concurrency_pool_config,
12 | get_pool_config_from_settings,
13 | validate_production_config,
14 | )
15 |
16 | __all__ = [
17 | "CONFIG",
18 | "CACHE_TTL",
19 | "clean_env_var",
20 | "DatabasePoolConfig",
21 | "get_default_pool_config",
22 | "get_development_pool_config",
23 | "get_high_concurrency_pool_config",
24 | "get_pool_config_from_settings",
25 | "create_engine_with_enhanced_config",
26 | "validate_production_config",
27 | ]
28 |
```
--------------------------------------------------------------------------------
/maverick_mcp/application/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Application layer - contains use cases and orchestration logic."""
2 |
3 | from maverick_mcp.application.dto.technical_analysis_dto import (
4 | BollingerBandsDTO,
5 | CompleteTechnicalAnalysisDTO,
6 | MACDAnalysisDTO,
7 | PriceLevelDTO,
8 | RSIAnalysisDTO,
9 | StochasticDTO,
10 | TrendAnalysisDTO,
11 | VolumeAnalysisDTO,
12 | )
13 | from maverick_mcp.application.queries.get_technical_analysis import (
14 | GetTechnicalAnalysisQuery,
15 | )
16 |
17 | __all__ = [
18 | # Queries
19 | "GetTechnicalAnalysisQuery",
20 | # DTOs
21 | "CompleteTechnicalAnalysisDTO",
22 | "RSIAnalysisDTO",
23 | "MACDAnalysisDTO",
24 | "BollingerBandsDTO",
25 | "StochasticDTO",
26 | "TrendAnalysisDTO",
27 | "VolumeAnalysisDTO",
28 | "PriceLevelDTO",
29 | ]
30 |
```
--------------------------------------------------------------------------------
/maverick_mcp/workflows/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Workflow orchestration module for Maverick MCP.
3 |
4 | This module provides workflow orchestration capabilities using LangGraph
5 | for complex multi-agent trading and analysis workflows.
6 | """
7 |
8 | from .backtesting_workflow import BacktestingWorkflow
9 | from .state import (
10 | BacktestingWorkflowState,
11 | BaseAgentState,
12 | DeepResearchState,
13 | MarketAnalysisState,
14 | PortfolioState,
15 | RiskManagementState,
16 | SupervisorState,
17 | TechnicalAnalysisState,
18 | )
19 |
20 | __all__ = [
21 | "BaseAgentState",
22 | "MarketAnalysisState",
23 | "TechnicalAnalysisState",
24 | "RiskManagementState",
25 | "PortfolioState",
26 | "SupervisorState",
27 | "DeepResearchState",
28 | "BacktestingWorkflowState",
29 | "BacktestingWorkflow",
30 | ]
31 |
```
--------------------------------------------------------------------------------
/maverick_mcp/providers/mocks/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Mock provider implementations for testing.
3 |
4 | This package contains mock implementations of all provider interfaces
5 | that can be used for fast, predictable testing without external dependencies.
6 | """
7 |
8 | from .mock_cache import MockCacheManager
9 | from .mock_config import MockConfigurationProvider
10 | from .mock_macro_data import MockMacroDataProvider
11 | from .mock_market_data import MockMarketDataProvider
12 | from .mock_persistence import MockDataPersistence
13 | from .mock_stock_data import MockStockDataFetcher, MockStockScreener
14 |
15 | __all__ = [
16 | "MockCacheManager",
17 | "MockStockDataFetcher",
18 | "MockStockScreener",
19 | "MockMarketDataProvider",
20 | "MockMacroDataProvider",
21 | "MockDataPersistence",
22 | "MockConfigurationProvider",
23 | ]
24 |
```
--------------------------------------------------------------------------------
/maverick_mcp/data/cache_manager.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Cache manager module.
3 |
4 | This module provides a bridge to import CacheManager and related cache utilities.
5 | The actual implementation is in cache.py but this module provides the expected import path.
6 | """
7 |
8 | from .cache import (
9 | CacheManager,
10 | cleanup_redis_pool,
11 | clear_cache,
12 | ensure_timezone_naive,
13 | generate_cache_key,
14 | get_cache_stats,
15 | get_from_cache,
16 | get_redis_client,
17 | normalize_timezone,
18 | reset_cache_stats,
19 | save_to_cache,
20 | )
21 |
22 | __all__ = [
23 | "CacheManager",
24 | "get_cache_stats",
25 | "reset_cache_stats",
26 | "get_from_cache",
27 | "save_to_cache",
28 | "clear_cache",
29 | "generate_cache_key",
30 | "ensure_timezone_naive",
31 | "normalize_timezone",
32 | "get_redis_client",
33 | "cleanup_redis_pool",
34 | ]
35 |
```
--------------------------------------------------------------------------------
/alembic/versions/001_initial_schema.py:
--------------------------------------------------------------------------------
```python
1 | """Initial schema - MCP-specific tables only
2 |
3 | Revision ID: 001_initial_schema
4 | Revises:
5 | Create Date: 2025-01-06 12:00:00.000000
6 |
7 | Note: This migration creates MCP-specific tables with mcp_ prefix.
8 | Django-owned tables (stocks_stock, stocks_pricecache, maverick_stocks,
9 | maverick_bear_stocks, supply_demand_breakouts) are not managed by Alembic.
10 | """
11 |
12 | # revision identifiers, used by Alembic.
13 | revision = "001_initial_schema"
14 | down_revision = None
15 | branch_labels = None
16 | depends_on = None
17 |
18 |
19 | def upgrade() -> None:
20 | # This migration is now empty as all screening tables
21 | # (maverick_stocks, maverick_bear_stocks, supply_demand_breakouts)
22 | # are Django-owned and should not be created by MCP
23 | pass
24 |
25 |
26 | def downgrade() -> None:
27 | # No tables to drop as screening tables are Django-owned
28 | pass
29 |
```
--------------------------------------------------------------------------------
/alembic/versions/006_rename_metadata_columns.py:
--------------------------------------------------------------------------------
```python
1 | """rename metadata columns
2 |
3 | Revision ID: 006_rename_metadata_columns
4 | Revises: f976356b6f07
5 | Create Date: 2025-06-05
6 |
7 | """
8 |
9 | from alembic import op
10 |
11 | # revision identifiers, used by Alembic.
12 | revision = "006_rename_metadata_columns"
13 | down_revision = "f976356b6f07"
14 | branch_labels = None
15 | depends_on = None
16 |
17 |
18 | def upgrade() -> None:
19 | # Rename metadata columns to avoid SQLAlchemy reserved word conflict
20 | op.alter_column("mcp_auth_audit_log", "metadata", new_column_name="event_metadata")
21 | op.alter_column(
22 | "mcp_user_subscriptions", "metadata", new_column_name="subscription_metadata"
23 | )
24 |
25 |
26 | def downgrade() -> None:
27 | # Revert column names
28 | op.alter_column("mcp_auth_audit_log", "event_metadata", new_column_name="metadata")
29 | op.alter_column(
30 | "mcp_user_subscriptions", "subscription_metadata", new_column_name="metadata"
31 | )
32 |
```
--------------------------------------------------------------------------------
/maverick_mcp/providers/interfaces/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Provider interfaces for Maverick-MCP.
3 |
4 | This package contains abstract interfaces that define contracts for all data providers,
5 | caching systems, and persistence layers. These interfaces enable dependency injection,
6 | improve testability, and reduce coupling between components.
7 |
8 | The interfaces follow the Interface Segregation Principle, providing focused contracts
9 | for specific concerns rather than monolithic interfaces.
10 | """
11 |
12 | from .cache import ICacheManager
13 | from .config import IConfigurationProvider
14 | from .macro_data import IMacroDataProvider
15 | from .market_data import IMarketDataProvider
16 | from .persistence import IDataPersistence
17 | from .stock_data import IStockDataFetcher, IStockScreener
18 |
19 | __all__ = [
20 | "ICacheManager",
21 | "IConfigurationProvider",
22 | "IDataPersistence",
23 | "IMarketDataProvider",
24 | "IMacroDataProvider",
25 | "IStockDataFetcher",
26 | "IStockScreener",
27 | ]
28 |
```
--------------------------------------------------------------------------------
/maverick_mcp/backtesting/strategies/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Strategy modules for VectorBT backtesting."""
2 |
3 | from .base import Strategy
4 |
5 | # ML-enhanced strategies
6 | from .ml import (
7 | AdaptiveStrategy,
8 | FeatureExtractor,
9 | MLPredictor,
10 | RegimeAwareStrategy,
11 | StrategyEnsemble,
12 | )
13 | from .ml.adaptive import HybridAdaptiveStrategy, OnlineLearningStrategy
14 | from .ml.ensemble import RiskAdjustedEnsemble
15 | from .ml.regime_aware import AdaptiveRegimeStrategy, MarketRegimeDetector
16 | from .parser import StrategyParser
17 | from .templates import STRATEGY_TEMPLATES
18 |
19 | __all__ = [
20 | "Strategy",
21 | "StrategyParser",
22 | "STRATEGY_TEMPLATES",
23 | # ML strategies
24 | "AdaptiveStrategy",
25 | "FeatureExtractor",
26 | "MLPredictor",
27 | "RegimeAwareStrategy",
28 | "StrategyEnsemble",
29 | # Advanced ML strategies
30 | "OnlineLearningStrategy",
31 | "HybridAdaptiveStrategy",
32 | "RiskAdjustedEnsemble",
33 | "MarketRegimeDetector",
34 | "AdaptiveRegimeStrategy",
35 | ]
36 |
```
--------------------------------------------------------------------------------
/maverick_mcp/domain/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """Domain layer - contains pure business logic with no infrastructure dependencies."""
2 |
3 | from maverick_mcp.domain.entities.stock_analysis import StockAnalysis
4 | from maverick_mcp.domain.portfolio import Portfolio, Position
5 | from maverick_mcp.domain.services.technical_analysis_service import (
6 | TechnicalAnalysisService,
7 | )
8 | from maverick_mcp.domain.stock_analysis import StockAnalysisService
9 | from maverick_mcp.domain.value_objects.technical_indicators import (
10 | BollingerBands,
11 | MACDIndicator,
12 | PriceLevel,
13 | RSIIndicator,
14 | Signal,
15 | StochasticOscillator,
16 | TrendDirection,
17 | VolumeProfile,
18 | )
19 |
20 | __all__ = [
21 | # Entities
22 | "StockAnalysis",
23 | # Portfolio Entities
24 | "Portfolio",
25 | "Position",
26 | # Services
27 | "TechnicalAnalysisService",
28 | "StockAnalysisService",
29 | # Value Objects
30 | "RSIIndicator",
31 | "MACDIndicator",
32 | "BollingerBands",
33 | "StochasticOscillator",
34 | "PriceLevel",
35 | "VolumeProfile",
36 | "Signal",
37 | "TrendDirection",
38 | ]
39 |
```
--------------------------------------------------------------------------------
/maverick_mcp/monitoring/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Monitoring package for MaverickMCP backtesting system.
3 |
4 | This package provides comprehensive monitoring capabilities including:
5 | - Prometheus metrics for backtesting performance
6 | - Strategy execution monitoring
7 | - API rate limiting and failure tracking
8 | - Anomaly detection and alerting
9 | """
10 |
11 | from .health_check import (
12 | ComponentHealth,
13 | HealthChecker,
14 | HealthStatus,
15 | SystemHealth,
16 | check_system_health,
17 | get_health_checker,
18 | )
19 | from .metrics import (
20 | BacktestingMetricsCollector,
21 | get_backtesting_metrics,
22 | track_anomaly_detection,
23 | track_api_call_metrics,
24 | track_backtest_execution,
25 | track_strategy_performance,
26 | )
27 |
28 | __all__ = [
29 | "BacktestingMetricsCollector",
30 | "get_backtesting_metrics",
31 | "track_backtest_execution",
32 | "track_strategy_performance",
33 | "track_api_call_metrics",
34 | "track_anomaly_detection",
35 | "HealthChecker",
36 | "HealthStatus",
37 | "ComponentHealth",
38 | "SystemHealth",
39 | "check_system_health",
40 | "get_health_checker",
41 | ]
42 |
```
--------------------------------------------------------------------------------
/maverick_mcp/api/middleware/security.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Simple security middleware for Maverick-MCP personal use.
3 |
4 | This module provides basic security headers for personal use.
5 | Advanced security features have been removed.
6 | """
7 |
8 | from fastapi import Request
9 | from starlette.middleware.base import BaseHTTPMiddleware
10 |
11 | from maverick_mcp.utils.logging import get_logger
12 |
13 | logger = get_logger(__name__)
14 |
15 |
16 | class SecurityHeadersMiddleware(BaseHTTPMiddleware):
17 | """Add basic security headers to all responses."""
18 |
19 | async def dispatch(self, request: Request, call_next):
20 | response = await call_next(request)
21 |
22 | # Basic security headers for personal use
23 | response.headers["X-Content-Type-Options"] = "nosniff"
24 | response.headers["X-Frame-Options"] = "DENY"
25 | response.headers["X-XSS-Protection"] = "1; mode=block"
26 | response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
27 |
28 | return response
29 |
30 |
31 | # Additional middleware classes removed for simplicity
32 | # Only keeping SecurityHeadersMiddleware for basic security
33 |
```
--------------------------------------------------------------------------------
/alembic/versions/003_add_performance_indexes.py:
--------------------------------------------------------------------------------
```python
1 | """Add performance indexes for Maverick-MCP
2 |
3 | Revision ID: 003_add_performance_indexes
4 | Revises: 002_add_authentication_tables
5 | Create Date: 2025-06-03 12:00:00
6 |
7 | This migration adds performance indexes to improve query speed
8 | for MCP-specific tables only. Django-owned tables are not modified.
9 | """
10 |
11 | from alembic import op
12 |
13 | # revision identifiers, used by Alembic.
14 | revision = "003_add_performance_indexes"
15 | down_revision = "002_add_authentication_tables"
16 | branch_labels = None
17 | depends_on = None
18 |
19 |
20 | def upgrade():
21 | """Add performance indexes for MCP tables only."""
22 |
23 | # API key usage performance indexes
24 | op.create_index(
25 | "idx_mcp_api_key_usage_api_key_id",
26 | "mcp_api_key_usage",
27 | ["api_key_id"],
28 | postgresql_using="btree",
29 | )
30 |
31 | print("Performance indexes for MCP tables created successfully!")
32 |
33 |
34 | def downgrade():
35 | """Remove performance indexes from MCP tables."""
36 |
37 | # Drop API key usage index
38 | op.drop_index("idx_mcp_api_key_usage_api_key_id", "mcp_api_key_usage")
39 |
40 | print("Performance indexes removed from MCP tables.")
41 |
```
--------------------------------------------------------------------------------
/maverick_mcp/api/routers/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Router modules for organizing Maverick-MCP endpoints by domain.
3 |
4 | This module contains domain-specific routers that organize
5 | the MCP tools into logical groups for better maintainability.
6 | Personal-use stock analysis MCP server.
7 | """
8 |
9 | from .data import data_router
10 | from .health_enhanced import router as health_enhanced_router
11 | from .performance import get_performance_router
12 | from .portfolio import portfolio_router
13 | from .screening import screening_router
14 | from .technical import technical_router
15 |
16 | # Initialize performance router
17 | performance_router = get_performance_router()
18 |
19 | # Optional: LangGraph agents router
20 | try:
21 | from .agents import agents_router
22 |
23 | has_agents = True
24 | except ImportError:
25 | agents_router = None # type: ignore[assignment]
26 | has_agents = False
27 |
28 | __all__ = [
29 | "data_router",
30 | "health_enhanced_router",
31 | "performance_router",
32 | "portfolio_router",
33 | "screening_router",
34 | "technical_router",
35 | ]
36 |
37 | if has_agents:
38 | __all__.append("agents_router")
39 |
40 | # Export health router as both names for compatibility
41 | health_router = health_enhanced_router
42 |
```
--------------------------------------------------------------------------------
/maverick_mcp/backtesting/__init__.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Backtesting module for MaverickMCP.
3 |
4 | Provides backtesting engines and utilities with conditional imports
5 | to handle missing dependencies gracefully.
6 | """
7 |
8 | __all__ = []
9 |
10 | # Try to import full VectorBT engine
11 | try:
12 | from .vectorbt_engine import VectorBTEngine
13 |
14 | __all__.append("VectorBTEngine")
15 | except ImportError:
16 | # If VectorBT dependencies aren't available, use stub
17 | from .batch_processing_stub import VectorBTEngineStub as _VectorBTEngine
18 |
19 | VectorBTEngine = _VectorBTEngine
20 | __all__.append("VectorBTEngine")
21 |
22 | # Try to import other backtesting components
23 | try:
24 | from .analysis import BacktestAnalyzer as _BacktestAnalyzer
25 |
26 | BacktestAnalyzer = _BacktestAnalyzer
27 | __all__.append("BacktestAnalyzer")
28 | except ImportError:
29 | pass
30 |
31 | try:
32 | from .optimization import StrategyOptimizer as _StrategyOptimizer
33 |
34 | StrategyOptimizer = _StrategyOptimizer
35 | __all__.append("StrategyOptimizer")
36 | except ImportError:
37 | pass
38 |
39 | try:
40 | from .strategy_executor import StrategyExecutor as _StrategyExecutor
41 |
42 | StrategyExecutor = _StrategyExecutor
43 | __all__.append("StrategyExecutor")
44 | except ImportError:
45 | pass
46 |
```
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "makefile.configureOnOpen": false,
3 | "editor.formatOnSave": true,
4 | "notebook.formatOnSave.enabled": true,
5 | "python.analysis.autoImportCompletions": true,
6 | "python.REPL.enableREPLSmartSend": false,
7 | "files.associations": {
8 | "*.html": "jinja-html",
9 | "*.js": "javascript",
10 | "*.jsx": "javascriptreact",
11 | "*.jinja2": "jinja-html",
12 | "*.jinja": "jinja-html"
13 | },
14 | "[python]": {
15 | "editor.formatOnSave": true,
16 | "editor.codeActionsOnSave": {
17 | "source.fixAll": "explicit",
18 | "source.organizeImports": "explicit"
19 | },
20 | "editor.defaultFormatter": "charliermarsh.ruff"
21 | },
22 | "[javascript]": {
23 | "editor.defaultFormatter": "esbenp.prettier-vscode",
24 | "editor.formatOnSave": true
25 | },
26 | "[javascriptreact]": {
27 | "editor.defaultFormatter": "esbenp.prettier-vscode",
28 | "editor.formatOnSave": true
29 | },
30 | "emmet.includeLanguages": {
31 | "jinja-html": "html"
32 | },
33 | "css.lint.unknownAtRules": "ignore",
34 | "css.lint.unknownProperties": "ignore",
35 | "yaml.customTags": ["!reference sequence", "!Ref", "!Sub", "!secret"],
36 | "yaml.validate": false,
37 | "cursorpyright.analysis.autoImportCompletions": true
38 | }
39 |
```
--------------------------------------------------------------------------------
/maverick_mcp/config/constants.py:
--------------------------------------------------------------------------------
```python
1 | """
2 | Constants for the Maverick-MCP package.
3 | """
4 |
5 | import os
6 | from typing import Any
7 |
8 |
9 | def clean_env_var(var_name, default):
10 | """Clean environment variable value to handle comments"""
11 | value = os.getenv(var_name, default)
12 | if value and isinstance(value, str):
13 | # Remove any trailing comments (anything after # that's not inside quotes)
14 | return value.split("#", 1)[0].strip()
15 | return value
16 |
17 |
18 | # Configuration with defaults
19 | CONFIG: dict[str, Any] = {
20 | "redis": {
21 | "host": clean_env_var("REDIS_HOST", "localhost"),
22 | "port": int(clean_env_var("REDIS_PORT", "6379")),
23 | "db": int(clean_env_var("REDIS_DB", "0")),
24 | "username": clean_env_var("REDIS_USERNAME", None),
25 | "password": clean_env_var("REDIS_PASSWORD", None),
26 | "ssl": clean_env_var("REDIS_SSL", "False").lower() == "true",
27 | },
28 | "cache": {
29 | "ttl": int(clean_env_var("CACHE_TTL_SECONDS", "604800")), # 7 days default
30 | "enabled": clean_env_var("CACHE_ENABLED", "True").lower() == "true",
31 | },
32 | "yfinance": {
33 | "timeout": int(clean_env_var("YFINANCE_TIMEOUT_SECONDS", "30")),
34 | },
35 | }
36 |
37 | # Cache TTL in seconds
38 | CACHE_TTL = CONFIG["cache"]["ttl"]
39 |
```
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
```yaml
1 | services:
2 | backend:
3 | build: .
4 | ports:
5 | - "8003:8003"
6 | environment:
7 | - DATABASE_URL=postgresql://postgres:postgres@postgres:5432/maverick_mcp
8 | - REDIS_HOST=redis
9 | # Required API Keys
10 | - TIINGO_API_KEY=${TIINGO_API_KEY}
11 | # Optional API Keys for Enhanced Features
12 | - OPENROUTER_API_KEY=${OPENROUTER_API_KEY}
13 | - EXA_API_KEY=${EXA_API_KEY}
14 | - TAVILY_API_KEY=${TAVILY_API_KEY}
15 | - FRED_API_KEY=${FRED_API_KEY}
16 | - OPENAI_API_KEY=${OPENAI_API_KEY}
17 | - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
18 | # Server Configuration
19 | - API_HOST=0.0.0.0
20 | - API_PORT=8003
21 | - LOG_LEVEL=${LOG_LEVEL:-info}
22 | - ENVIRONMENT=${ENVIRONMENT:-production}
23 | volumes:
24 | - ./maverick_mcp:/app/maverick_mcp
25 | - ./alembic:/app/alembic
26 | - ./.env:/app/.env
27 | depends_on:
28 | - postgres
29 | - redis
30 |
31 | postgres:
32 | image: postgres:15-alpine
33 | environment:
34 | - POSTGRES_USER=postgres
35 | - POSTGRES_PASSWORD=postgres
36 | - POSTGRES_DB=maverick_mcp
37 | volumes:
38 | - postgres-data:/var/lib/postgresql/data
39 | ports:
40 | - "5432:5432"
41 |
42 | redis:
43 | image: redis:7-alpine
44 | volumes:
45 | - redis-data:/data
46 | ports:
47 | - "6379:6379"
48 |
49 | volumes:
50 | postgres-data:
51 | redis-data:
```
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
```dockerfile
1 | # Dockerfile for Maverick-MCP
2 | # Python-only MCP server
3 |
4 | FROM python:3.12-slim
5 |
6 | WORKDIR /app
7 |
8 | # Install system dependencies and TA-Lib
9 | RUN apt-get update && apt-get install -yqq \
10 | build-essential \
11 | python3-dev \
12 | libpq-dev \
13 | wget \
14 | curl \
15 | && rm -rf /var/lib/apt/lists/*
16 |
17 | # Install uv for fast Python package management
18 | RUN pip install --no-cache-dir uv
19 |
20 | # Install and compile TA-Lib
21 | ENV TALIB_DIR=/usr/local
22 | RUN wget https://github.com/ta-lib/ta-lib/releases/download/v0.6.4/ta-lib-0.6.4-src.tar.gz \
23 | && tar -xzf ta-lib-0.6.4-src.tar.gz \
24 | && cd ta-lib-0.6.4/ \
25 | && ./configure --prefix=$TALIB_DIR \
26 | && make -j$(nproc) \
27 | && make install \
28 | && cd .. \
29 | && rm -rf ta-lib-0.6.4-src.tar.gz ta-lib-0.6.4/
30 |
31 | # Copy dependency files first for better caching
32 | COPY pyproject.toml uv.lock README.md ./
33 |
34 | # Install Python dependencies
35 | RUN uv sync --frozen
36 |
37 | # Copy application code
38 | COPY maverick_mcp ./maverick_mcp
39 | COPY alembic ./alembic
40 | COPY alembic.ini setup.py ./
41 |
42 | # Set environment variables
43 | ENV PYTHONUNBUFFERED=1
44 | ENV PYTHONDONTWRITEBYTECODE=1
45 |
46 | # Create non-root user
47 | RUN groupadd -g 1000 maverick && \
48 | useradd -u 1000 -g maverick -s /bin/sh -m maverick && \
49 | chown -R maverick:maverick /app
50 |
51 | USER maverick
52 |
53 | EXPOSE 8000
54 |
55 | # Start MCP server
56 | CMD ["uv", "run", "python", "-m", "maverick_mcp.api.server", "--transport", "sse", "--host", "0.0.0.0", "--port", "8000"]
57 |
```