Skip to content

About

Open-source portfolio accounting, performance analytics, and risk analysis platform.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

OpenTradeLab

OpenTradeLab (version 0.2.0) is an open-source, deterministic multi-market financial analytics and historical simulation platform. It is designed to process transaction logs, enforce strict validation, calculate portfolio metrics using First-In-First-Out (FIFO) lot matching, and export versioned, reproducible JSON reports.

Important: OpenTradeLab is an analytical and historical simulation platform. It does not provide live order execution, brokerage access, or automated trading actions.


Key Features

  • Strict, Non-Silent Validation: Missing fields, duplicate transaction IDs, invalid numbers, and non-ISO timestamps are systematically captured without silent drops.
  • Deterministic FIFO Lot Accounting: Realized P&L is computed using exact lot matching with proportional transaction fee allocation.
  • Zero-Dependency Runtime: Built purely on Python 3.12+ standard library (decimal.Decimal, dataclasses, csv, datetime, argparse). No floating-point inaccuracies or external package bloat.
  • Point-in-Time Portfolio Valuation: Integrates validated historical market price quotes to compute exact unrealized P&L and market value for open long positions without future quote lookahead.
  • Auditable Cash Ledger & Negative-Cash Policy: Tracks opening balances, deposits, withdrawals, and trade cash flows chronologically with strict non-margin overdraft prevention.
  • Consolidated Portfolio Equity: Computes true total equity ($\text{Cash} + \text{Positions Market Value}$) cleanly separated from realized and unrealized performance indicators.
  • Auditable Corporate Actions: Accurately models cash dividend entitlement on ex-dates, cash crediting on payment dates, and forward/reverse stock splits with exact economic cost basis invariance and fractional share preservation.
  • Portfolio Performance Analytics: Computes Time-Weighted Return (TWR), Money-Weighted Return (MWR / XIRR), peak-to-trough Drawdown series, and economic Capital Reconciliation.
  • Benchmark Comparison & Relative Performance: Point-in-time benchmark return, excess return, sample covariance Beta ($\beta$), and periodic/annualized Jensen's Alpha ($\alpha$) with sample size and variance guards.
  • Periodic Return Engine: Daily and monthly portfolio and benchmark returns with external cash flow isolation, subperiod compounding, staleness detection, and synchronous alignment.
  • Advanced Risk Analytics: Annualized volatility ($\sigma_{\text{ann}}$), Sharpe ratio, Sortino ratio ($N$-convention $LPM_2$), Calmar ratio (flow-isolated TWR performance index drawdown), and empirical Historical VaR / Expected Shortfall (CVaR).
  • Schema-Versioned Reports: Outputs JSON reports conforming to schema version 1.0.0 for automated pipeline integration.
  • Developer-Friendly: Full typing with strict mypy checks, ruff linting, and comprehensive pytest coverage.

Installation

Prerequisites

  • Python 3.12 or newer

Setup

# Clone the repository
git clone https://github.com/opentradelab/opentradelab.git
cd opentradelab

# Optional: create a virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install development dependencies (pytest, ruff, mypy)
pip install -e ".[dev]"

Quickstart & CLI Usage

The platform provides a standalone CLI opentradelab (or executable via python -m opentradelab.cli):

# Display CLI help
python -m opentradelab.cli --help

# Process a transaction CSV and export a JSON report (transaction-only mode)
python -m opentradelab.cli --input examples/sample_trades.csv --output report.json

# Point-in-time valuation with historical quotes
python -m opentradelab.cli -i examples/sample_trades.csv -q examples/sample_quotes.csv -t 2026-01-16T18:00:00Z -o valuation_report.json

# Complete workflow: trades, cash flow ledger, quotes, and portfolio equity
python -m opentradelab.cli -i examples/sample_trades.csv -k examples/sample_cash.csv -q examples/sample_quotes.csv -t 2026-01-16T18:00:00Z -o complete_report.json

# Full multi-engine workflow with corporate actions (dividends and splits)
python -m opentradelab.cli -i examples/sample_trades.csv -k examples/sample_cash.csv -q examples/sample_quotes.csv -a examples/sample_corporate_actions.csv -t 2026-01-16T18:00:00Z -o full_report.json

# Complete workflow including benchmark comparison
python -m opentradelab.cli -i tests/fixtures/benchmark_trades.csv -k tests/fixtures/benchmark_cash.csv -q tests/fixtures/benchmark_quotes.csv -b tests/fixtures/benchmark_series.csv -t 2026-07-31T18:00:00Z -o bench_report.json

# Periodic returns workflow (daily or monthly)
python -m opentradelab.cli -i tests/fixtures/periodic_daily_trades.csv -k tests/fixtures/periodic_daily_cash.csv -q tests/fixtures/periodic_daily_quotes.csv -b tests/fixtures/periodic_daily_benchmark.csv -t 2026-08-05T18:00:00Z -f daily -o daily_report.json

# Advanced risk analytics workflow
python -m opentradelab.cli -i tests/fixtures/periodic_daily_trades.csv -k tests/fixtures/periodic_daily_cash.csv -q tests/fixtures/periodic_daily_quotes.csv -b tests/fixtures/periodic_daily_benchmark.csv -t 2026-08-05T18:00:00Z -f daily --risk --risk-free-rate 4.5 -o risk_report.json

Complete Example Workflow

python -m opentradelab.cli -i examples/sample_trades.csv -o output_report.json

Example terminal output:

============================================================
                   OpenTradeLab Summary
============================================================
Source File:            examples/sample_trades.csv
Generated At:           2026-10-27T12:00:00Z
Records Processed:      10 (8 valid, 2 invalid)
Base Currency:          USD
------------------------------------------------------------
Total Volume:           $76,700.00
Total Fees:             $13.00
Realized P&L:           $670.30
Closed Trades:          4
Win Rate:               50.00%
Profit Factor:          6.47
------------------------------------------------------------
Open Positions:
  - AAPL: 40.00 shares (Cost Basis: $6,080.00, Avg: $152.00)
  - AMZN: 30.00 shares (Cost Basis: $5,100.00, Avg: $170.00)
  - GOOG: 10.00 shares (Cost Basis: $1,800.00, Avg: $180.00)
------------------------------------------------------------
Validation Errors:      2
  [Row 8] TXN-ERR1 (quantity): NON_POSITIVE_VALUE - Quantity must be strictly positive (> 0), got: '0'
  [Row 10] TXN-1002 (transaction_id): DUPLICATE_TRANSACTION_ID - Duplicate transaction ID encountered: 'TXN-1002'
============================================================
Report successfully written to output_report.json

Point-in-Time Valuation Workflow

python -m opentradelab.cli -i examples/sample_trades.csv -q examples/sample_quotes.csv -t 2026-01-16T18:00:00Z -o valuation_report.json

Example terminal output with valuation:

============================================================
                   OpenTradeLab Summary
============================================================
Source File:            examples/sample_trades.csv
Generated At:           2026-01-16T18:00:00Z
Records Processed:      10 (8 valid, 2 invalid)
Base Currency:          USD
------------------------------------------------------------
Total Volume:           $76,700.00
Total Fees:             $13.00
Realized P&L:           $670.30
Closed Trades:          4
Win Rate:               50.00%
Profit Factor:          6.47
------------------------------------------------------------
Open Positions:
  - AAPL: 40.00 shares (Cost Basis: $6,080.00, Avg: $152.00)
  - AMZN: 30.00 shares (Cost Basis: $5,100.00, Avg: $170.00)
  - GOOG: 10.00 shares (Cost Basis: $1,800.00, Avg: $180.00)
------------------------------------------------------------
Valuation (as of 2026-01-16T18:00:00+00:00):
  Status:               COMPLETE
  Positions Mkt Value:  $13,400.00
  Total Unrealized P&L: $420.00
  Valued Positions:
    - AAPL: 40.00 shs @ $160.00 (Value: $6,400.00, Unrealized: $320.00 [OK])
    - AMZN: 30.00 shs @ $175.00 (Value: $5,250.00, Unrealized: $150.00 [OK])
    - GOOG: 10.00 shs @ $175.00 (Value: $1,750.00, Unrealized: -$50.00 [OK])
------------------------------------------------------------
Validation Errors:      2
  [Row 8] TXN-ERR1 (quantity): NON_POSITIVE_VALUE - Quantity must be strictly positive (> 0), got: '0'
  [Row 10] TXN-1002 (transaction_id): DUPLICATE_TRANSACTION_ID - Duplicate transaction ID encountered: 'TXN-1002'
============================================================
Report successfully written to valuation_report.json

Complete Consolidated Workflow (Trades + Cash Ledger + Quotes + Equity)

python -m opentradelab.cli -i examples/sample_trades.csv -k examples/sample_cash.csv -q examples/sample_quotes.csv -t 2026-01-16T18:00:00Z -o complete_report.json

Example terminal output with cash ledger and portfolio equity:

============================================================
                   OpenTradeLab Summary
============================================================
Source File:            examples/sample_trades.csv
Generated At:           2026-01-16T18:00:00Z
Records Processed:      10 (8 valid, 2 invalid)
Base Currency:          USD
------------------------------------------------------------
Total Volume:           $76,700.00
Total Fees:             $13.00
Realized P&L:           $670.30
Closed Trades:          4
Win Rate:               50.00%
Profit Factor:          6.47
------------------------------------------------------------
Open Positions:
  - AAPL: 40.00 shares (Cost Basis: $6,080.00, Avg: $152.00)
  - AMZN: 30.00 shares (Cost Basis: $5,100.00, Avg: $170.00)
  - GOOG: 10.00 shares (Cost Basis: $1,800.00, Avg: $180.00)
------------------------------------------------------------
Valuation (as of 2026-01-16T18:00:00+00:00):
  Status:               COMPLETE
  Positions Mkt Value:  $13,400.00
  Total Unrealized P&L: $420.00
  Valued Positions:
    - AAPL: 40.00 shs @ $160.00 (Value: $6,400.00, Unrealized: $320.00 [OK])
    - AMZN: 30.00 shs @ $175.00 (Value: $5,250.00, Unrealized: $150.00 [OK])
    - GOOG: 10.00 shs @ $175.00 (Value: $1,750.00, Unrealized: -$50.00 [OK])
------------------------------------------------------------
Cash Ledger (as of 2026-01-16T18:00:00+00:00):
  Status:               COMPLETE
  Opening Balance:      $100,000.00
  Total Deposits:       $5,000.00
  Total Withdrawals:    $2,000.00
  Buy Cash Outflows:    $44,507.50
  Sell Cash Inflows:    $32,194.50
  Total Fees Paid:      $13.00
  Ending Cash Balance:  $90,687.00
------------------------------------------------------------
Portfolio Equity (as of 2026-01-16T18:00:00+00:00):
  Status:               COMPLETE
  Cash Balance:         $90,687.00
  Positions Mkt Value:  $13,400.00
  Total Equity:         $104,087.00
  Realized P&L:         $670.30
  Unrealized P&L:       $420.00
------------------------------------------------------------
Performance Analytics (as of 2026-01-16T18:00:00+00:00):
  Status:               INCOMPLETE
  Time-Weighted Return: N/A
  Money-Weighted (IRR): 1,467.59%
  Maximum Drawdown:     -1.89%
  Current Drawdown:     -1.89%
  Capital Reconciled:   Balanced ($0.00 diff)
  Performance Warnings:
    * Subperiod valuation missing at one or more cash flow boundaries.
------------------------------------------------------------
Validation Errors:      2
  [Row 8] TXN-ERR1 (quantity): NON_POSITIVE_VALUE - Quantity must be strictly positive (> 0), got: '0'
  [Row 10] TXN-1002 (transaction_id): DUPLICATE_TRANSACTION_ID - Duplicate transaction ID encountered: 'TXN-1002'
============================================================
Report successfully written to complete_report.json

Documentation


License

OpenTradeLab is open-source software licensed under the Apache License 2.0.

About

Open-source portfolio accounting, performance analytics, and risk analysis platform.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages