ibkr-flex-accounting 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ibkr_flex_accounting-0.1.0/.github/workflows/ci.yml +30 -0
- ibkr_flex_accounting-0.1.0/.github/workflows/pypi.yml +34 -0
- ibkr_flex_accounting-0.1.0/.github/workflows/release.yml +66 -0
- ibkr_flex_accounting-0.1.0/.gitignore +8 -0
- ibkr_flex_accounting-0.1.0/.python-version +1 -0
- ibkr_flex_accounting-0.1.0/CHANGELOG.md +17 -0
- ibkr_flex_accounting-0.1.0/LICENSE +21 -0
- ibkr_flex_accounting-0.1.0/Makefile +8 -0
- ibkr_flex_accounting-0.1.0/PKG-INFO +124 -0
- ibkr_flex_accounting-0.1.0/README.md +99 -0
- ibkr_flex_accounting-0.1.0/docs/flex-query-setup.md +45 -0
- ibkr_flex_accounting-0.1.0/pyproject.toml +61 -0
- ibkr_flex_accounting-0.1.0/scripts/test.sh +8 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/__init__.py +64 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/_io.py +28 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/account.py +864 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/cli.py +134 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/controls.py +109 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/performance.py +156 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/py.typed +0 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/reporting.py +354 -0
- ibkr_flex_accounting-0.1.0/src/ibkr_flex_accounting/store.py +673 -0
- ibkr_flex_accounting-0.1.0/tests/__init__.py +0 -0
- ibkr_flex_accounting-0.1.0/tests/test_account.py +473 -0
- ibkr_flex_accounting-0.1.0/tests/test_acquisition.py +464 -0
- ibkr_flex_accounting-0.1.0/tests/test_controls.py +117 -0
- ibkr_flex_accounting-0.1.0/tests/test_multi_currency_and_cli.py +264 -0
- ibkr_flex_accounting-0.1.0/tests/test_performance.py +203 -0
- ibkr_flex_accounting-0.1.0/tests/test_store.py +539 -0
- ibkr_flex_accounting-0.1.0/tests/test_store_retention.py +121 -0
- ibkr_flex_accounting-0.1.0/uv.lock +185 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
pull_request:
|
|
5
|
+
push:
|
|
6
|
+
branches: [main]
|
|
7
|
+
workflow_dispatch:
|
|
8
|
+
workflow_call:
|
|
9
|
+
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
|
|
13
|
+
concurrency:
|
|
14
|
+
group: ci-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
|
15
|
+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
|
16
|
+
|
|
17
|
+
jobs:
|
|
18
|
+
test:
|
|
19
|
+
strategy:
|
|
20
|
+
fail-fast: false
|
|
21
|
+
matrix:
|
|
22
|
+
python: ['3.11', '3.12', '3.13']
|
|
23
|
+
runs-on: ubuntu-latest
|
|
24
|
+
timeout-minutes: 10
|
|
25
|
+
steps:
|
|
26
|
+
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
|
|
27
|
+
- uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
|
28
|
+
with:
|
|
29
|
+
python-version: ${{ matrix.python }}
|
|
30
|
+
- run: make check
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
name: PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ['v*.*.*']
|
|
6
|
+
workflow_dispatch: {}
|
|
7
|
+
|
|
8
|
+
permissions: {}
|
|
9
|
+
|
|
10
|
+
concurrency:
|
|
11
|
+
group: pypi-${{ github.ref }}
|
|
12
|
+
cancel-in-progress: false
|
|
13
|
+
|
|
14
|
+
jobs:
|
|
15
|
+
publish:
|
|
16
|
+
if: github.ref_type == 'tag' && (github.event_name == 'workflow_dispatch' || vars.PYPI_PUBLISH == 'true')
|
|
17
|
+
runs-on: ubuntu-latest
|
|
18
|
+
timeout-minutes: 10
|
|
19
|
+
environment: pypi
|
|
20
|
+
permissions:
|
|
21
|
+
contents: read
|
|
22
|
+
id-token: write
|
|
23
|
+
steps:
|
|
24
|
+
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
|
|
25
|
+
with:
|
|
26
|
+
persist-credentials: false
|
|
27
|
+
- uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
|
28
|
+
- name: Build
|
|
29
|
+
run: |
|
|
30
|
+
version="$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
|
|
31
|
+
[ "${GITHUB_REF_NAME#v}" = "$version" ] || { echo "tag $GITHUB_REF_NAME is not version $version" >&2; exit 1; }
|
|
32
|
+
uv build
|
|
33
|
+
- name: Upload
|
|
34
|
+
run: uv publish --trusted-publishing always --check-url https://pypi.org/simple/
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ['v*.*.*']
|
|
6
|
+
workflow_dispatch: {}
|
|
7
|
+
|
|
8
|
+
permissions: {}
|
|
9
|
+
|
|
10
|
+
concurrency:
|
|
11
|
+
group: release-${{ github.ref }}
|
|
12
|
+
cancel-in-progress: false
|
|
13
|
+
|
|
14
|
+
jobs:
|
|
15
|
+
released:
|
|
16
|
+
runs-on: ubuntu-latest
|
|
17
|
+
timeout-minutes: 5
|
|
18
|
+
permissions:
|
|
19
|
+
contents: read
|
|
20
|
+
outputs:
|
|
21
|
+
done: ${{ steps.check.outputs.done }}
|
|
22
|
+
steps:
|
|
23
|
+
- id: check
|
|
24
|
+
env:
|
|
25
|
+
GH_TOKEN: ${{ github.token }}
|
|
26
|
+
TAG: ${{ github.ref_name }}
|
|
27
|
+
run: |
|
|
28
|
+
done=false
|
|
29
|
+
if [ "$GITHUB_REF_TYPE" = tag ] && gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
|
30
|
+
done=true
|
|
31
|
+
echo "$TAG is already released: nothing to do"
|
|
32
|
+
fi
|
|
33
|
+
echo "done=$done" >> "$GITHUB_OUTPUT"
|
|
34
|
+
|
|
35
|
+
ci:
|
|
36
|
+
needs: released
|
|
37
|
+
if: needs.released.outputs.done != 'true'
|
|
38
|
+
uses: ./.github/workflows/ci.yml
|
|
39
|
+
permissions:
|
|
40
|
+
contents: read
|
|
41
|
+
|
|
42
|
+
github-release:
|
|
43
|
+
needs: ci
|
|
44
|
+
if: github.event_name == 'push' && github.ref_type == 'tag'
|
|
45
|
+
runs-on: ubuntu-latest
|
|
46
|
+
timeout-minutes: 10
|
|
47
|
+
permissions:
|
|
48
|
+
contents: write
|
|
49
|
+
steps:
|
|
50
|
+
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
|
|
51
|
+
with:
|
|
52
|
+
persist-credentials: false
|
|
53
|
+
- uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
|
54
|
+
- name: Build
|
|
55
|
+
run: |
|
|
56
|
+
version="$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
|
|
57
|
+
[ "${GITHUB_REF_NAME#v}" = "$version" ] || { echo "tag $GITHUB_REF_NAME is not version $version" >&2; exit 1; }
|
|
58
|
+
uv build
|
|
59
|
+
- env:
|
|
60
|
+
GH_TOKEN: ${{ github.token }}
|
|
61
|
+
TAG: ${{ github.ref_name }}
|
|
62
|
+
run: |
|
|
63
|
+
object=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" --jq 'select(.object.type == "tag") | .object.sha')
|
|
64
|
+
test -n "$object" || { echo "::error::$TAG is not an annotated tag carrying release notes"; exit 1; }
|
|
65
|
+
gh api "repos/$GITHUB_REPOSITORY/git/tags/$object" --jq .message > "$RUNNER_TEMP/notes.md"
|
|
66
|
+
gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" --notes-file "$RUNNER_TEMP/notes.md"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.12
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.1.0] - 2026-11-29
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Initial standalone release of `ibkr-flex-accounting`:
|
|
8
|
+
- Flex Web Service v3 HTTP client with SSRF-safe `GetStatement` URL validation, redirect blocking, XXE rejection, and durable per-lane request journals (`reporting`).
|
|
9
|
+
- Strict `Decimal` NAV, Cash Report, Open Positions, Accruals, Conversion Rates, Statement of Funds, Forex Balances, `ChangeInNAV`, and MTM/FIFO performance reconciliation (`account`, `controls`, `performance`).
|
|
10
|
+
- Automatic or explicit multi-base-currency support (`base_currency=None` infers from `EquitySummaryInBase`; explicit codes enforce strict currency matching).
|
|
11
|
+
- Multi-lane resumable collector (`daily`, `period`, `performance_history`, `history`), window compaction, safe superseded-period pruning, and cross-account dividend/coupon `income_facts` (`store`).
|
|
12
|
+
- `ibkr-flex` CLI (`bootstrap`, `collect`, `inspect`, `prune`).
|
|
13
|
+
|
|
14
|
+
### Upgrade
|
|
15
|
+
|
|
16
|
+
- Action required: None (initial release).
|
|
17
|
+
- Rollback: Not applicable.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 benjamin-di
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ibkr-flex-accounting
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Strict, resumable Interactive Brokers Flex Web Service v3 accounting, reconciliation, and market-projection engine
|
|
5
|
+
Project-URL: Homepage, https://github.com/benjamin-di/ibkr-flex-accounting
|
|
6
|
+
Project-URL: Issues, https://github.com/benjamin-di/ibkr-flex-accounting/issues
|
|
7
|
+
Author: benjamin-di
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: accounting,finance,flex,ibkr,interactive-brokers,portfolio,reconciliation
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
21
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Requires-Dist: pyyaml<7,>=6
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# ibkr-flex-accounting
|
|
27
|
+
|
|
28
|
+
Strict, resumable Interactive Brokers Flex Web Service v3 accounting, reconciliation, and market-projection engine for Python.
|
|
29
|
+
|
|
30
|
+
## Why this library exists
|
|
31
|
+
|
|
32
|
+
Thin XML parsers turn Flex statements into objects, but real portfolio accounting hits harder problems:
|
|
33
|
+
|
|
34
|
+
- **Strict arithmetic reconciliation**: Every accepted snapshot must reconcile native cash (`CashReport`), positions (`OpenPositions`), accruals (`InterestAccruals`, `OpenDividendAccruals`), closing FX (`ConversionRates`), Statement of Funds running balances (`StmtFunds`), Forex balances (`FxPositions`), `ChangeInNAV`, and `MTMPerformanceSummaryInBase` / `FIFOPerformanceSummaryInBase` using `Decimal` arithmetic.
|
|
35
|
+
- **Resumable multi-lane acquisition**: Independent `daily`, `period` (YTD/MTD), `performance_history`, and `history` lanes persist durable JSON journals so a slow backfill never blocks the daily close, references survive restarts, and tokens are never logged or redirected off `*.interactivebrokers.com`.
|
|
36
|
+
- **Immutable archives + safe compaction**: Raw XML files are stored content-addressed (`YYYY-MM-DD-ibkr-flex-<sha16>.xml`), superseded period windows can be compacted in memory and safely pruned on disk while preserving every daily original.
|
|
37
|
+
- **Any base currency**: Base currency (`USD`, `EUR`, `GBP`, `CHF`, etc.) is inferred from `EquitySummaryInBase` or enforced explicitly via `base_currency=...`.
|
|
38
|
+
- **Pure market projection**: `value(report, when, quote=..., fx=...)` projects confirmed broker quantities onto external closing prices/FX without mutating accounting facts, separating quote-source basis differences from market movement.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install ibkr-flex-accounting
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Or with `uv`:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uv add ibkr-flex-accounting
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Quick start
|
|
53
|
+
|
|
54
|
+
### Python API
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from pathlib import Path
|
|
58
|
+
from ibkr_flex_accounting import account, store
|
|
59
|
+
|
|
60
|
+
cfg = {
|
|
61
|
+
"account": "U1234567",
|
|
62
|
+
"query_id": "123456",
|
|
63
|
+
"query_name": "Portfolio Accounting",
|
|
64
|
+
"anchor": "2025-12-31",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Bootstrap a normalized store from an archive of Flex XML files
|
|
68
|
+
acct_store, rejected = store.bootstrap(Path("./archive"), cfg)
|
|
69
|
+
store.compact(acct_store)
|
|
70
|
+
|
|
71
|
+
latest = account.latest(acct_store, "2026-09-08")
|
|
72
|
+
print(latest["base_currency"], latest["nav"]["total"])
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Multi-lane collection (resumable)
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import os
|
|
79
|
+
from pathlib import Path
|
|
80
|
+
from ibkr_flex_accounting import account, reporting, store
|
|
81
|
+
|
|
82
|
+
acct_store = account.load("store.json")
|
|
83
|
+
acct_store, acks, findings = store.collect(
|
|
84
|
+
acct_store,
|
|
85
|
+
cfg,
|
|
86
|
+
state_dir=Path("./state"),
|
|
87
|
+
archive=Path("./archive"),
|
|
88
|
+
when="2026-09-08",
|
|
89
|
+
token=os.environ["IBKR_FLEX_TOKEN"],
|
|
90
|
+
)
|
|
91
|
+
store.compact(acct_store)
|
|
92
|
+
store.save("store.json", acct_store)
|
|
93
|
+
for state_path, state, _ in acks:
|
|
94
|
+
reporting.acknowledge(state_path, state)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### CLI
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
# Build a store from archived XMLs
|
|
101
|
+
ibkr-flex bootstrap --archive ./archive --config ibkr-flex.yaml --output store.json --compact
|
|
102
|
+
|
|
103
|
+
# Run one resumable collection cycle (reads IBKR_FLEX_TOKEN from env)
|
|
104
|
+
ibkr-flex collect --archive ./archive --config ibkr-flex.yaml --state-dir ./state --store store.json
|
|
105
|
+
|
|
106
|
+
# Inspect latest NAV, controls, and issues
|
|
107
|
+
ibkr-flex inspect --store store.json
|
|
108
|
+
|
|
109
|
+
# Safely prune superseded period XMLs (all daily originals are preserved)
|
|
110
|
+
ibkr-flex prune --archive ./archive --store store.json
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
See [docs/flex-query-setup.md](docs/flex-query-setup.md) for the required IBKR Activity Flex Query sections and configuration fields.
|
|
114
|
+
|
|
115
|
+
## Security & safety invariants
|
|
116
|
+
|
|
117
|
+
- **XXE-safe**: Rejects XML payloads containing `<!DOCTYPE` or `<!ENTITY`.
|
|
118
|
+
- **No token leakage**: `GetStatement` only follows `https://*.interactivebrokers.com/.../GetStatement` URLs, disables HTTP redirects (`NoRedirect`), redacts tokens and URLs from error messages, and caps responses at 32 MiB.
|
|
119
|
+
- **Rate-limit friendly**: Enforces a 1.1s cooldown after every Flex Web Service call (including failures).
|
|
120
|
+
- **Atomic writes**: Journals, archives, and JSON stores use same-directory temp file + `fsync` + `os.replace`.
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# ibkr-flex-accounting
|
|
2
|
+
|
|
3
|
+
Strict, resumable Interactive Brokers Flex Web Service v3 accounting, reconciliation, and market-projection engine for Python.
|
|
4
|
+
|
|
5
|
+
## Why this library exists
|
|
6
|
+
|
|
7
|
+
Thin XML parsers turn Flex statements into objects, but real portfolio accounting hits harder problems:
|
|
8
|
+
|
|
9
|
+
- **Strict arithmetic reconciliation**: Every accepted snapshot must reconcile native cash (`CashReport`), positions (`OpenPositions`), accruals (`InterestAccruals`, `OpenDividendAccruals`), closing FX (`ConversionRates`), Statement of Funds running balances (`StmtFunds`), Forex balances (`FxPositions`), `ChangeInNAV`, and `MTMPerformanceSummaryInBase` / `FIFOPerformanceSummaryInBase` using `Decimal` arithmetic.
|
|
10
|
+
- **Resumable multi-lane acquisition**: Independent `daily`, `period` (YTD/MTD), `performance_history`, and `history` lanes persist durable JSON journals so a slow backfill never blocks the daily close, references survive restarts, and tokens are never logged or redirected off `*.interactivebrokers.com`.
|
|
11
|
+
- **Immutable archives + safe compaction**: Raw XML files are stored content-addressed (`YYYY-MM-DD-ibkr-flex-<sha16>.xml`), superseded period windows can be compacted in memory and safely pruned on disk while preserving every daily original.
|
|
12
|
+
- **Any base currency**: Base currency (`USD`, `EUR`, `GBP`, `CHF`, etc.) is inferred from `EquitySummaryInBase` or enforced explicitly via `base_currency=...`.
|
|
13
|
+
- **Pure market projection**: `value(report, when, quote=..., fx=...)` projects confirmed broker quantities onto external closing prices/FX without mutating accounting facts, separating quote-source basis differences from market movement.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install ibkr-flex-accounting
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or with `uv`:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
uv add ibkr-flex-accounting
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Quick start
|
|
28
|
+
|
|
29
|
+
### Python API
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from ibkr_flex_accounting import account, store
|
|
34
|
+
|
|
35
|
+
cfg = {
|
|
36
|
+
"account": "U1234567",
|
|
37
|
+
"query_id": "123456",
|
|
38
|
+
"query_name": "Portfolio Accounting",
|
|
39
|
+
"anchor": "2025-12-31",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
# Bootstrap a normalized store from an archive of Flex XML files
|
|
43
|
+
acct_store, rejected = store.bootstrap(Path("./archive"), cfg)
|
|
44
|
+
store.compact(acct_store)
|
|
45
|
+
|
|
46
|
+
latest = account.latest(acct_store, "2026-09-08")
|
|
47
|
+
print(latest["base_currency"], latest["nav"]["total"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Multi-lane collection (resumable)
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import os
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
from ibkr_flex_accounting import account, reporting, store
|
|
56
|
+
|
|
57
|
+
acct_store = account.load("store.json")
|
|
58
|
+
acct_store, acks, findings = store.collect(
|
|
59
|
+
acct_store,
|
|
60
|
+
cfg,
|
|
61
|
+
state_dir=Path("./state"),
|
|
62
|
+
archive=Path("./archive"),
|
|
63
|
+
when="2026-09-08",
|
|
64
|
+
token=os.environ["IBKR_FLEX_TOKEN"],
|
|
65
|
+
)
|
|
66
|
+
store.compact(acct_store)
|
|
67
|
+
store.save("store.json", acct_store)
|
|
68
|
+
for state_path, state, _ in acks:
|
|
69
|
+
reporting.acknowledge(state_path, state)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### CLI
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
# Build a store from archived XMLs
|
|
76
|
+
ibkr-flex bootstrap --archive ./archive --config ibkr-flex.yaml --output store.json --compact
|
|
77
|
+
|
|
78
|
+
# Run one resumable collection cycle (reads IBKR_FLEX_TOKEN from env)
|
|
79
|
+
ibkr-flex collect --archive ./archive --config ibkr-flex.yaml --state-dir ./state --store store.json
|
|
80
|
+
|
|
81
|
+
# Inspect latest NAV, controls, and issues
|
|
82
|
+
ibkr-flex inspect --store store.json
|
|
83
|
+
|
|
84
|
+
# Safely prune superseded period XMLs (all daily originals are preserved)
|
|
85
|
+
ibkr-flex prune --archive ./archive --store store.json
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
See [docs/flex-query-setup.md](docs/flex-query-setup.md) for the required IBKR Activity Flex Query sections and configuration fields.
|
|
89
|
+
|
|
90
|
+
## Security & safety invariants
|
|
91
|
+
|
|
92
|
+
- **XXE-safe**: Rejects XML payloads containing `<!DOCTYPE` or `<!ENTITY`.
|
|
93
|
+
- **No token leakage**: `GetStatement` only follows `https://*.interactivebrokers.com/.../GetStatement` URLs, disables HTTP redirects (`NoRedirect`), redacts tokens and URLs from error messages, and caps responses at 32 MiB.
|
|
94
|
+
- **Rate-limit friendly**: Enforces a 1.1s cooldown after every Flex Web Service call (including failures).
|
|
95
|
+
- **Atomic writes**: Journals, archives, and JSON stores use same-directory temp file + `fsync` + `os.replace`.
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# IBKR Activity Flex Query Setup
|
|
2
|
+
|
|
3
|
+
`ibkr-flex-accounting` expects a single **Activity Flex Query** (`type="AF"`) configured in IBKR Client Portal under **Performance & Reports → Flex Queries**.
|
|
4
|
+
|
|
5
|
+
## Required XML Sections
|
|
6
|
+
|
|
7
|
+
| Section | Purpose | Required |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| `OpenPositions` (`SUMMARY`) | Closing positions, mark prices, cost basis, accrued bond interest | Yes |
|
|
10
|
+
| `CashReport` (currency detail) | Native-currency starting/ending/settled cash | Yes |
|
|
11
|
+
| `EquitySummaryInBase` | Daily NAV components (`cash`, `stock`, `bonds`, `interestAccruals`, `dividendAccruals`, `total`) | Yes |
|
|
12
|
+
| `ConversionRates` | Closing FX rates to the account base currency | Yes |
|
|
13
|
+
| `StmtFunds` (`Currency` detail) | Native running cash ledger control | Recommended |
|
|
14
|
+
| `FxPositions` (`SUMMARY`) | Forex balances control | Recommended |
|
|
15
|
+
| `FxTransactions` (`TRANSACTION`) | Realized Forex P/L control | Optional |
|
|
16
|
+
| `ChangeInNAV` | Period NAV bridge, funding flows, broker TWR | Recommended |
|
|
17
|
+
| `InterestAccruals` | Native-currency interest accrual roll-forward | Recommended |
|
|
18
|
+
| `OpenDividendAccruals` | Open dividend accrual inventory | Recommended |
|
|
19
|
+
| `MTMPerformanceSummaryInBase` | Broker mark-to-market performance attribution | Recommended |
|
|
20
|
+
| `FIFOPerformanceSummaryInBase` | Realized and unrealized FIFO P/L | Optional |
|
|
21
|
+
| `SecuritiesInfo` | Contract metadata (ISIN, description, listing exchange) | Optional |
|
|
22
|
+
| `Trades`, `CashTransactions`, `CorporateActions`, `Transfers`, `ChangeInDividendAccruals` | Activity resolution and dividend/coupon receipt matching | Optional |
|
|
23
|
+
|
|
24
|
+
## Query Format Settings
|
|
25
|
+
|
|
26
|
+
- **Format**: XML
|
|
27
|
+
- **Date Format**: `yyyyMMdd`
|
|
28
|
+
- **Time Format**: `HHmmss`
|
|
29
|
+
- **Date/Time Separator**: `;` (semi-colon)
|
|
30
|
+
- **Include Canceled Trades**: Yes (required for accurate trade/cancellation resolution)
|
|
31
|
+
|
|
32
|
+
## Configuration (`ibkr-flex.yaml`)
|
|
33
|
+
|
|
34
|
+
```yaml
|
|
35
|
+
account: U1234567
|
|
36
|
+
query_id: "123456"
|
|
37
|
+
query_name: Portfolio Accounting
|
|
38
|
+
anchor: "2025-12-31"
|
|
39
|
+
# Optional:
|
|
40
|
+
# history_start: "2025-01-01"
|
|
41
|
+
# timezone: "America/New_York"
|
|
42
|
+
# base_currency: "USD" # Omit to infer from EquitySummaryInBase
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Environment variables `IBKR_FLEX_ACCOUNT`, `IBKR_FLEX_QUERY_ID`, `IBKR_FLEX_QUERY_NAME`, `IBKR_FLEX_BASE_CURRENCY`, and `IBKR_FLEX_TOKEN` override the YAML values at runtime.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ibkr-flex-accounting"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Strict, resumable Interactive Brokers Flex Web Service v3 accounting, reconciliation, and market-projection engine"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "benjamin-di" }]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
keywords = ["interactive-brokers", "ibkr", "flex", "accounting", "portfolio", "reconciliation", "finance"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
22
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"PyYAML>=6,<7",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
ibkr-flex = "ibkr_flex_accounting.cli:main"
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/benjamin-di/ibkr-flex-accounting"
|
|
33
|
+
Issues = "https://github.com/benjamin-di/ibkr-flex-accounting/issues"
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = [
|
|
37
|
+
"pytest>=8",
|
|
38
|
+
"ruff>=0.14",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[build-system]
|
|
42
|
+
requires = ["hatchling"]
|
|
43
|
+
build-backend = "hatchling.build"
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.wheel]
|
|
46
|
+
packages = ["src/ibkr_flex_accounting"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
testpaths = ["tests"]
|
|
50
|
+
addopts = "-q"
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
line-length = 120
|
|
54
|
+
target-version = "py311"
|
|
55
|
+
|
|
56
|
+
[tool.ruff.lint]
|
|
57
|
+
select = ["E", "F", "I", "B", "UP", "S", "RUF"]
|
|
58
|
+
ignore = ["S101", "S314", "RUF001", "RUF002", "RUF003"]
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint.per-file-ignores]
|
|
61
|
+
"tests/*" = ["S", "E501", "B905"]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Strict, resumable Interactive Brokers Flex Web Service v3 accounting engine."""
|
|
2
|
+
|
|
3
|
+
from . import account, controls, performance, reporting, store
|
|
4
|
+
from .account import SCHEMA, TOL, empty_store, latest, load, merge, parse, revision, value
|
|
5
|
+
from .controls import validate
|
|
6
|
+
from .performance import parse as parse_performance
|
|
7
|
+
from .reporting import JournalError, ReportingError, acknowledge, acquisition, request
|
|
8
|
+
from .store import (
|
|
9
|
+
activity,
|
|
10
|
+
bootstrap,
|
|
11
|
+
collect,
|
|
12
|
+
compact,
|
|
13
|
+
configuration,
|
|
14
|
+
income_facts,
|
|
15
|
+
known_shas,
|
|
16
|
+
missing_performance_day,
|
|
17
|
+
missing_performance_days,
|
|
18
|
+
nav_history,
|
|
19
|
+
periods,
|
|
20
|
+
prune_superseded,
|
|
21
|
+
save,
|
|
22
|
+
superseded,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"SCHEMA",
|
|
29
|
+
"TOL",
|
|
30
|
+
"JournalError",
|
|
31
|
+
"ReportingError",
|
|
32
|
+
"__version__",
|
|
33
|
+
"account",
|
|
34
|
+
"acknowledge",
|
|
35
|
+
"acquisition",
|
|
36
|
+
"activity",
|
|
37
|
+
"bootstrap",
|
|
38
|
+
"collect",
|
|
39
|
+
"compact",
|
|
40
|
+
"configuration",
|
|
41
|
+
"controls",
|
|
42
|
+
"empty_store",
|
|
43
|
+
"income_facts",
|
|
44
|
+
"known_shas",
|
|
45
|
+
"latest",
|
|
46
|
+
"load",
|
|
47
|
+
"merge",
|
|
48
|
+
"missing_performance_day",
|
|
49
|
+
"missing_performance_days",
|
|
50
|
+
"nav_history",
|
|
51
|
+
"parse",
|
|
52
|
+
"parse_performance",
|
|
53
|
+
"performance",
|
|
54
|
+
"periods",
|
|
55
|
+
"prune_superseded",
|
|
56
|
+
"reporting",
|
|
57
|
+
"request",
|
|
58
|
+
"revision",
|
|
59
|
+
"save",
|
|
60
|
+
"store",
|
|
61
|
+
"superseded",
|
|
62
|
+
"validate",
|
|
63
|
+
"value",
|
|
64
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Atomic file writes and SHA-256 digests with no external dependencies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def digest(path: str | Path) -> str:
|
|
12
|
+
"""Return the hex SHA-256 digest of a file."""
|
|
13
|
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def atomic_write(path: str | Path, data: str | bytes) -> None:
|
|
17
|
+
"""Write bytes or UTF-8 text atomically via same-directory temp file + fsync + replace."""
|
|
18
|
+
target = Path(path)
|
|
19
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as handle:
|
|
21
|
+
temp = Path(handle.name)
|
|
22
|
+
handle.write(data.encode("utf-8") if isinstance(data, str) else data)
|
|
23
|
+
handle.flush()
|
|
24
|
+
os.fsync(handle.fileno())
|
|
25
|
+
try:
|
|
26
|
+
os.replace(temp, target)
|
|
27
|
+
finally:
|
|
28
|
+
temp.unlink(missing_ok=True)
|