8000 GitHub - Shearwater1978/ibkr-tax-gemini: It parses your IBKR Activity Reports (CSV), calculates Capital Gains (FIFO) and Dividends using precise **NBP (National Bank of Poland)** exchange rates (D-1 rule), and generates a PDF report ready for your PIT-38 tax declaration. · GitHub
[go: up one dir, main page]

Skip to content

About

It parses your IBKR Activity Reports (CSV), calculates Capital Gains (FIFO) and Dividends using precise **NBP (National Bank of Poland)** exchange rates (D-1 rule), and generates a PDF report ready for your PIT-38 tax declaration.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

🇵🇱 IBKR Tax Calculator (PIT-38 Poland) v2.2.0

Automated Capital Gains & Dividend Tax Calculator for Polish Residents using Interactive Brokers.

Python License Security Version

🚀 Key Features

  • Privacy First: All financial data is stored in a local SQLCipher (AES-256) encrypted database. The SQLCipher driver and a non-empty SQLCIPHER_KEY are required; the application refuses plaintext SQLite.
  • Universal Parser: Supports both Activity Statements and Flex Queries.
  • Smart NBP Rates: T-1 rule compliant, using Batch Caching logic.
  • FIFO Algorithm: Strictly follows tax laws for Cost Basis.
  • PIT-38 Ready: Generates a PDF report compatible with Polish tax forms.

📦 Installation

  1. Clone:

    git clone [https://github.com/your-repo/ibkr-tax-gemini.git](https://github.com/your-repo/ibkr-tax-gemini.git)
    cd ibkr-tax-gemini
  2. Install:

    pip install -r requirements.txt

    This installs the sqlcipher3 driver required for encrypted database access.

  3. Setup Security: Create .env:

    SQLCIPHER_KEY=your_secret_key
    DATABASE_PATH=db/ibkr_history.db.enc

🏃 Usage

The main.py script is now the single entry point for all operations.

# 1. Import Data
# Automatically scans the project 'data/' folder and adds only new records.
# Repeated imports are idempotent and report inserted/skipped counts.
python main.py --import-data

# 2. Generate Report
# Calculates taxes for the specific year using FIFO and NBP rates.
python main.py --target-year 2024 --export-pdf --export-excel

FIFO coverage preflight

Check whether imported history contains enough FIFO inventory for planned sales. This is evidence for a preflight review only: it does not calculate tax, create a sale, or persist any transaction.

python main.py --planned-sale AAPL:10:2024-12-31 --coverage-output json
python main.py --coverage-file planned-sales.json

The JSON file contains an array of objects with ticker, quantity, and as_of. The report includes per-asset status, available and missing quantity, and FIFO lot evidence. NOT_COVERED with history_found: false means no broker history was imported for that asset; it is distinct from an imported history with zero remaining holdings.

Calculations stop with a diagnostic if an NBP rate is unavailable or a sale cannot be matched to inventory. Export failures are also reported as errors; the application does not present incomplete tax totals as valid reports.

Desktop GUI

Install Python dependencies, then start the Electron dashboard:

cd gui
npm install
npm start

The GUI starts a local backend on 127.0.0.1:8000, waits for its /health endpoint, and uses the same encrypted database and report output as the CLI.

Web portal (browser)

The same dark, tabbed portal also runs in a normal browser, without Electron. It needs only Python and the .env from the installation steps.

  1. Start the backend (keep this terminal open):

    python gui/backend/api.py

    It listens on http://127.0.0.1:8000 and must be started from the project root so it finds .env and the encrypted database.

  2. Open http://127.0.0.1:8000/ in a browser. The backend serves the portal itself. On start the portal imports the statement files from data/, loads the available years and calculates the latest one, so the Dashboard fills in without any clicks. If it shows "Backend is unavailable", check that the backend is running. (Opening gui/ui/index.html directly from disk also works.)

  3. To look at another year, choose it in the top bar and press Calculate. The currency selector next to it shows amounts in PLN, USD or EUR at the NBP rate of the year's last day (display only; reports stay in PLN). Click any ticker to open its sales, dividends and open lots in a new tab, or hover it for a short summary.

Stop the backend with Ctrl+C. The backend only accepts requests from file:// pages and localhost/127.0.0.1, so it is not reachable from other machines.

View What it shows
Dashboard P&L and dividend totals, per-ticker breakdown, buttons to open the Excel/PDF reports
Reports → Dividends Every dividend payment of the year with filter, sorting and totals
Reports → Analytics Per-ticker realized P&L, dividends and total result
Reports → Portfolio Open FIFO lots per ticker: cost basis, original-currency cost, and market value / unrealized P&L from current Yahoo Finance quotes (shown as - when no quote exists; needs internet)
Workspace Calculation progress, CSV import, IB connections, FIFO coverage check

The Dividends, Analytics and Portfolio views show the most recently calculated year and stay empty until a calculation succeeds.

IB Live API (optional)

CSV import from data/ remains the default and required workflow. A read-only live connection to Interactive Brokers TWS/IB Gateway is available as an opt-in alternative/supplement for pulling recent executed trades directly from a running Gateway session.

Setup requirements:

  1. Install and run IB Gateway (recommended) or TWS, and log in to a paper trading account (recommended for testing) or live account.
  2. In IB Gateway/TWS, enable API access: Configure → Settings → API → Enable ActiveX and Socket Clients, and add 127.0.0.1 to trusted IPs.
  3. Note the socket port shown in the API settings. Defaults used by this project: 4002 (paper Gateway), 4001 (live Gateway), 7497 (paper TWS), 7496 (live TWS).
  4. Add to your .env to opt in (live sync is disabled unless set):
    IB_LIVE_ENABLED=True
    IB_HOST=127.0.0.1
    IB_PORT=4002
    IB_CLIENT_ID=1
    Each concurrent connection to the same Gateway must use a distinct IB_CLIENT_ID.
  5. In the desktop GUI, use Check IB Connection to verify connectivity and Live Sync to pull and store new executions. Both actions report success/failure in place; neither blocks CSV import if Gateway is down.

Operational limits of read-only access:

  • Only executed trades (fills), positions, account summary, and open orders are requested. The connector never places, modifies, or cancels orders.
  • Dividends, withholding taxes, and corporate actions are not available through this live path; they still require CSV/Flex Query import.
  • Fills reflect executions visible to the current API session. For full historical trade history, use CSV import instead.
  • If IB Gateway/TWS is not running, not configured, or the session is lost, the live sync reports a clear error and CSV import continues to work unaffected.

IB Web API via Client Portal Gateway (optional)

The Client Portal Web API is a separate, HTTPS-based alternative to the socket connector above. It is disabled by default and requires a locally running Client Portal Gateway (CPGW) with a manually authenticated IBKR browser session.

Setup requirements:

  1. Download and unpack the Client Portal Gateway from Interactive Brokers. Install a supported Java runtime if the Gateway does not include one.
  2. Start CPGW using its bundled launch script and configuration. Its default local URL is https://localhost:5000.
  3. Open that URL in a browser, log in with IBKR credentials, and complete 2FA. The application does not handle credentials, start CPGW, or automate 2FA.
  4. Add the following to .env to opt in:
    IB_WEB_API_ENABLED=True
    IB_WEB_BASE_URL=https://localhost:5000/v1/api
    IB_WEB_VERIFY_SSL=False
    IB_WEB_REQUEST_TIMEOUT=10
    CPGW uses a local self-signed certificate by default. Keep IB_WEB_VERIFY_SSL=False only for that local default; set it to True when CPGW is configured with a trusted certificate.
  5. In the desktop GUI, use Check CPGW Connection to inspect the browser session, then Web API Sync to import the available recent executions. A "log in via the browser" message means CPGW needs a fresh manual login.

Operational limits of read-only access:

  • The connector requests account data, open positions, and recent trade confirmations only. It never creates, modifies, or cancels orders.
  • The Web API trade endpoint is not a complete historical statement. Use the CSV/Flex Query import for historical executions, dividends, withholding tax, and corporate actions.
  • CPGW sessions expire and must be kept alive; a later expiry requires another browser login with 2FA. Permission and rate-limit responses are reported as actionable sync errors.
  • The Web API connector, the TWS/Gateway connector, and CSV import are independent. A failure in one does not block either of the others.

📱 Mobile apps (Android and iOS)

Portfolio Companion is an informational portfolio viewer for the phone: it imports IBKR Activity Statements (CSV) on the device and shows holdings, returns, dividends and activity. It does not calculate PIT-38. The Android and iOS apps, their build instructions, user guide and privacy notice live in a separate, private repository, broker-companion; the link works only for accounts that have been given access.

This repository stays the core project: the report parser, FIFO, NBP rates, PIT-38 and the desktop and web tools. The mobile parsers and FIFO are ports of the Python reference here and are kept equal to it through shared synthetic parity fixtures. This repository owns them and their generator (tests/fixtures/parity, tools/generate_parity_fixtures.py, see its README); broker-companion keeps byte-identical copies.

⚠️ Disclaimer

Educational purpose only. Not financial advice.

About

It parses your IBKR Activity Reports (CSV), calculates Capital Gains (FIFO) and Dividends using precise **NBP (National Bank of Poland)** exchange rates (D-1 rule), and generates a PDF report ready for your PIT-38 tax declaration.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0