Skip to content

Repository files navigation

Mind & Market

Behavioral-finance research platform — scores investor biases, backtests their cost against a disciplined SIP, and generates bias-aware AI guidance.

CI Tests Python License

Status: v1 — trimmed scope, no vector DB, no LangChain, single free LLM call.


Architecture

                  ┌──────────────────────────────────────────┐
                  │            Streamlit UI Layer            │
                  │    (Market | Behavioral | Backtest | AI) │
                  └────────────────────┬─────────────────────┘
                                       │ HTTP
                                       ▼
                  ┌──────────────────────────────────────────┐
                  │             FastAPI Core API             │
                  │      Pydantic schemas + rate limiter     │
                  └──────┬─────────────┬──────────────┬──────┘
                         │             │              │
       ┌─────────────────┘             │              └─────────────────┐
       ▼                               ▼                                ▼
┌──────────────┐               ┌──────────────┐                 ┌──────────────┐
│  Engine 1:   │               │  Engine 2:   │                 │  Engine 3:   │
│ Behavioral   │               │  Market &    │                 │  Backtest    │
│ Profiler     │               │  Technical   │                 │  Engine      │
└──────┬───────┘               │  Analytics   │                 └──────┬───────┘
       │                       └──────┬───────┘                        │
       ▼                              ▼                                ▼
┌──────────────┐               ┌──────────────┐                 ┌──────────────┐
│ Survey Input │               │ yfinance +   │                 │ Biased vs    │
│ CSV / Forms  │               │ SQLite Cache │                 │ SIP Compare  │
└──────────────┘               └──────────────┘                 └──────────────┘
                                                                                  │
                                                                                  ▼
                                                                         ┌──────────────┐
                                                                         │  Engine 4:   │
                                                                         │  AI Advisor  │
                                                                         │  (OpenAI)    │
                                                                         └──────────────┘

Quick Start

Prerequisites

  • Python 3.10+
  • (Optional) Docker & Docker Compose

Local Setup

# Clone
git clone <repo-url>
cd mind-and-market

# Create virtual environment
python -m venv venv
source venv/bin/activate  # or `venv\Scripts\activate` on Windows

# Install dependencies
pip install -r requirements.txt

# Configure environment
cp .env.example .env
# Edit .env to add your OPENAI_API_KEY (optional — only needed for AI Advisor)

# Run tests
python -m pytest tests/ -v

# Start the API server
uvicorn src.api.app:app --reload --port 8000

# Start the UI (in another terminal)
streamlit run ui/app.py

Docker Setup

# Copy and edit .env
cp .env.example .env

# Run everything
docker-compose up --build

# API: http://localhost:8000/docs
# UI:  http://localhost:8501

API Endpoints

Endpoint Method Description
/api/v1/health GET Health check
/api/v1/market/fetch POST Fetch market data + compute indicators
/api/v1/behavioral/score POST Score a single survey response
/api/v1/behavioral/score-batch POST Batch score multiple responses
/api/v1/backtest/compare POST Run biased vs SIP backtest
/api/v1/advisor/generate POST Generate AI financial guidance

Full interactive docs at http://localhost:8000/docs (Swagger UI).

Rate limit: 60 requests per minute per IP. Exceeding returns 429.

Engine Details

Engine 1: Market Analytics

  • Data: yfinance (NSE/BSE tickers, ^NSEI for Nifty 50)
  • Indicators: SMA-20, EMA-50, EMA-200, RSI-14, MACD (12/26/9), Bollinger Bands, ATR-14
  • Cache: SQLite with TTL-based invalidation (24h default)

Engine 2: Behavioral Profiler

  • Input: Self-rated skill, quiz score, expected vs actual return, trade frequency, risk tolerance
  • Output: [overconfidence_score, disposition_tendency, loss_aversion_ratio]
  • Formula: See src/behavioral/overconfidence_scorer.py for documented weights

Engine 3: Backtest Engine

  • Biased Strategy: Early profit-taking, hold losers, over-trading
  • Disciplined SIP: Fixed monthly investment, buy-and-hold
  • Metrics: CAGR, Max Drawdown, Sharpe, Sortino, brokerage cost
  • Caveats: See docs/LIMITATIONS.md

Engine 4: AI Advisor

  • LLM: OpenAI gpt-4o-mini (single API call, no RAG)
  • Guardrails: Non-advisory framing, conservative allocation, mandatory disclaimer
  • Disclaimer: Every response includes: "Educational/research tool. Not registered investment advice."

Project Structure

mind-and-market/
├── src/
│   ├── behavioral/       # Survey parser + overconfidence scorer
│   ├── market/           # Data fetcher + indicators + SQLite cache
│   ├── backtest/         # Disposition sim + SIP comparator + metrics
│   ├── advisor/          # Prompt templates + LLM engine
│   ├── api/              # FastAPI routes + Pydantic schemas + rate limiter
│   └── config.py         # pydantic-settings config
├── ui/
│   └── app.py            # Streamlit application
├── tests/                # 73 pytest tests (one file per engine + P0 fixes)
├── data/processed/       # SQLite database + yfinance cache
├── docs/
│   └── LIMITATIONS.md    # Backtest caveats and assumptions
├── .github/workflows/    # CI (ruff + black + mypy + pytest on push)
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── README.md

Testing

# Run all tests
python -m pytest tests/ -v

# Run specific engine tests
python -m pytest tests/test_market.py -v
python -m pytest tests/test_behavioral.py -v
python -m pytest tests/test_backtest.py -v
python -m pytest tests/test_advisor.py -v
python -m pytest tests/test_api.py -v

Known Limitations

See docs/LIMITATIONS.md for full details.

Key caveats:

  • Transaction costs model only brokerage (no STT, stamp duty, GST)
  • No survivorship-bias-free data
  • Fractional shares assumed (Indian markets use lot sizes)
  • Overconfidence formula weights are v1 heuristics, not literature-validated
  • AI advisor is educational only — not a substitute for SEBI-registered advice

v2 Roadmap

  • RAG with Qdrant — knowledge base of SEBI guidelines, fund fact sheets, bias literature
  • LSTM/Prophet — advanced price prediction with walk-forward validation
  • Multi-user auth — JWT-based user accounts and survey history
  • Walk-forward backtest — out-of-sample validation for strategy parameters
  • Full transaction cost model — STT, stamp duty, GST, slippage
  • Streamlit auth — login-gated access
  • Export reports — PDF/HTML backtest reports with charts

License

MIT

About

Behavioral finance research platform — scores investor biases, backtests their cost against a disciplined SIP, and generates bias-aware AI guidance.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages