eqdesk 0.1.1__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.
Files changed (38) hide show
  1. eqdesk-0.1.1/LICENSE +21 -0
  2. eqdesk-0.1.1/PKG-INFO +154 -0
  3. eqdesk-0.1.1/README.md +127 -0
  4. eqdesk-0.1.1/pyproject.toml +43 -0
  5. eqdesk-0.1.1/src/eqdesk/__init__.py +1 -0
  6. eqdesk-0.1.1/src/eqdesk/book/book.py +144 -0
  7. eqdesk-0.1.1/src/eqdesk/brokers/base_broker.py +43 -0
  8. eqdesk-0.1.1/src/eqdesk/brokers/book_ledger.py +110 -0
  9. eqdesk-0.1.1/src/eqdesk/brokers/paper.py +76 -0
  10. eqdesk-0.1.1/src/eqdesk/brokers/paper_book.py +99 -0
  11. eqdesk-0.1.1/src/eqdesk/brokers/paper_reader.py +71 -0
  12. eqdesk-0.1.1/src/eqdesk/checks/__init__.py +1 -0
  13. eqdesk-0.1.1/src/eqdesk/checks/days.py +7 -0
  14. eqdesk-0.1.1/src/eqdesk/checks/inputs.py +34 -0
  15. eqdesk-0.1.1/src/eqdesk/checks/performance.py +64 -0
  16. eqdesk-0.1.1/src/eqdesk/checks/prices.py +67 -0
  17. eqdesk-0.1.1/src/eqdesk/checks/result.py +45 -0
  18. eqdesk-0.1.1/src/eqdesk/checks/settings.py +16 -0
  19. eqdesk-0.1.1/src/eqdesk/checks/statements.py +39 -0
  20. eqdesk-0.1.1/src/eqdesk/checks/trades.py +119 -0
  21. eqdesk-0.1.1/src/eqdesk/data_definitions/__init__.py +0 -0
  22. eqdesk-0.1.1/src/eqdesk/data_definitions/regions.py +17 -0
  23. eqdesk-0.1.1/src/eqdesk/data_definitions/trading_costs.py +9 -0
  24. eqdesk-0.1.1/src/eqdesk/data_definitions/universe.py +32 -0
  25. eqdesk-0.1.1/src/eqdesk/database/mongodb.py +174 -0
  26. eqdesk-0.1.1/src/eqdesk/pipeline/__init__.py +0 -0
  27. eqdesk-0.1.1/src/eqdesk/pipeline/price_updater.py +71 -0
  28. eqdesk-0.1.1/src/eqdesk/providers/__init__.py +0 -0
  29. eqdesk-0.1.1/src/eqdesk/providers/base_provider.py +10 -0
  30. eqdesk-0.1.1/src/eqdesk/providers/book_provider.py +10 -0
  31. eqdesk-0.1.1/src/eqdesk/providers/factor_provider.py +11 -0
  32. eqdesk-0.1.1/src/eqdesk/providers/financial_provider.py +11 -0
  33. eqdesk-0.1.1/src/eqdesk/providers/price_provider.py +11 -0
  34. eqdesk-0.1.1/src/eqdesk/strategy/__init__.py +0 -0
  35. eqdesk-0.1.1/src/eqdesk/strategy/afactorstrategy.py +63 -0
  36. eqdesk-0.1.1/src/eqdesk/strategy/amultifactorstrategy.py +65 -0
  37. eqdesk-0.1.1/src/eqdesk/strategy/asinglefactorstrategy.py +40 -0
  38. eqdesk-0.1.1/src/eqdesk/strategy/constituents.py +54 -0
eqdesk-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eric Ji Yong Chung
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.
eqdesk-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: eqdesk
3
+ Version: 0.1.1
4
+ Summary: Run factor strategies as paper books: strategies, paper broker, book checks.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: finance,factor investing,paper trading,backtesting,mongodb
8
+ Author: chung-ejy
9
+ Author-email: avocadoedevs@gmail.com
10
+ Requires-Python: >=3.13
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Financial and Insurance Industry
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Office/Business :: Financial :: Investment
17
+ Classifier: Operating System :: OS Independent
18
+ Requires-Dist: factorframe (>=0.1.1,<0.2)
19
+ Requires-Dist: pandas (>=3.0.3,<4.0.0)
20
+ Requires-Dist: pymongo (>=4.17.0,<5.0.0)
21
+ Project-URL: Changelog, https://github.com/ejchungie/eqdesk/blob/main/CHANGELOG.md
22
+ Project-URL: Homepage, https://github.com/ejchungie/eqdesk
23
+ Project-URL: Issues, https://github.com/ejchungie/eqdesk/issues
24
+ Project-URL: Repository, https://github.com/ejchungie/eqdesk
25
+ Description-Content-Type: text/markdown
26
+
27
+ # eqdesk
28
+
29
+ Run factor strategies as books. eqdesk sits on top of [factorframe](https://github.com/ejchungie/factorframe):
30
+ factorframe computes factors, weights and backtests; eqdesk adds the desk around them.
31
+ - **Strategies** pick each quarter's stocks from a ranked index, using only what was known then.
32
+ - A **paper broker** trades a book with fees and keeps a full ledger.
33
+ - A **Book** reads and writes a strategy's data in MongoDB.
34
+ - **Price updates** add new prices from your own data feed.
35
+ - **Book checks** test whether a book's numbers can be trusted.
36
+
37
+ Status: early (0.x); the API can change between minor versions. MIT licence. Python 3.13+.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install eqdesk # installs factorframe too
43
+ ```
44
+
45
+ The strategy and backtest parts run on plain DataFrames. Book, the providers, PaperBook and PriceUpdater
46
+ need a MongoDB server (default `localhost:27017`).
47
+
48
+ ## Quickstart (no database needed)
49
+
50
+ ```python
51
+ from pandas import DataFrame
52
+
53
+ from factorframe.data_definitions.financials import generate_financial_dummy_data
54
+ from factorframe.factor.single_factor import SingleFactor
55
+ from factorframe.metric.metric import Metrics
56
+ from factorframe.portfolio.allocation_type import AllocationType
57
+ from factorframe.portfolio.factor_portfolio import FactorPortfolio
58
+ from factorframe.portfolio.weighting import WeightingType
59
+ from factorframe.utils.timeframe import TimeFrame
60
+
61
+ from eqdesk.data_definitions.regions import Regions
62
+ from eqdesk.data_definitions.universe import Universe
63
+ from eqdesk.strategy.asinglefactorstrategy import ASingleFactorStrategy
64
+
65
+
66
+ class EquityToAssets(SingleFactor):
67
+ name = "equity_to_assets"
68
+ timeframe = TimeFrame.QUARTER
69
+ factor_delay = 1
70
+ factor_memory = 1
71
+
72
+ def factor_calculations(self, data: DataFrame) -> DataFrame:
73
+ data["factor"] = data["total_equity"] / data["total_assets"]
74
+ return data.dropna(subset=["date"])[["date", "ticker", "factor"]]
75
+
76
+
77
+ class EquityToAssetsStrategy(ASingleFactorStrategy):
78
+ factor = EquityToAssets()
79
+
80
+
81
+ # 20 stocks; each quarter the 10 most traded form the index and the strategy holds 5 of them
82
+ universe = Universe(Regions.UNITED_STATES, index_size=10, holdings=5)
83
+ portfolio = FactorPortfolio(TimeFrame.QUARTER, WeightingType.FACTOR, AllocationType.INDEXING)
84
+ strategy = EquityToAssetsStrategy("example", portfolio, universe, TimeFrame.QUARTER)
85
+
86
+ financials = generate_financial_dummy_data(num_tickers=20, num_years=5)
87
+ factors = strategy.factor.calculate(financials)
88
+ prices = financials[["date", "ticker", "price"]].assign(volume=1000)
89
+ index = financials.assign(year=financials["date"].dt.year, quarter=financials["date"].dt.quarter)
90
+ index["volume_rank"] = index.groupby(["year", "quarter"])["volume"].rank(ascending=False, method="first")
91
+ index = index[["year", "quarter", "ticker", "volume_rank"]]
92
+
93
+ result = strategy.historical_performance(factors, prices, index)
94
+ print(strategy.universe.name, Metrics(periods_per_year=4).calculate(result.dropna(subset=["weight"])))
95
+ # <universe name> {'total_return': ..., 'annualized_volatility': ..., 'sharpe_ratio': ..., 'max_drawdown': ...}
96
+ ```
97
+
98
+ ## How it fits together
99
+
100
+ ```mermaid
101
+ flowchart LR
102
+ FEED["your data feed"] --> PU["PriceUpdater<br/>new prices into MongoDB"]
103
+ PU --> DB[("&lt;REGION&gt;_prices · _factors · _financials")]
104
+ DB --> BK["Book(strategy)<br/>reads data, writes &lt;strategy&gt;_&lt;universe&gt;"]
105
+ ST["Strategy<br/>(factor + portfolio + Universe)"] --> BK
106
+ BK --> HP["historical_performance<br/>allocations, portfolio"]
107
+ HP --> PB["PaperBook + Paper broker<br/>trades, ledger, value history"]
108
+ HP --> CK["checks<br/>pass / warn / fail"]
109
+ PB --> CK
110
+ ```
111
+
112
+ | Concept | Where | What it is |
113
+ |---|---|---|
114
+ | Region | `data_definitions/regions.py` | a market; prefixes its databases (`UNITED_STATES_prices`) |
115
+ | Universe | `data_definitions/universe.py` | region + index size + how many to hold; its `name` (`<short>_<TYPE>_<size>`) names the book |
116
+ | Strategy | `strategy/` | a factor (or several) + a factorframe portfolio + a Universe |
117
+ | Book | `book/book.py` | a strategy plus its databases: `with Book(strategy) as book:` |
118
+ | Providers | `providers/` | pick database names: `<REGION>_prices`, `<REGION>_factors`, `<REGION>_financials`, `<strategy>_<universe>` |
119
+ | Paper trading | `brokers/` | `Paper` broker, `BookLedger`, `PaperBook` (database `<strategy>_<universe>_paper`), `PaperReader` |
120
+ | Price updates | `pipeline/price_updater.py` | `PriceUpdater(database, feed).update(tickers, today)` |
121
+ | Checks | `checks/` | functions returning `CheckResult` (pass / warn / fail, message, rows) |
122
+ | Trading costs | `data_definitions/trading_costs.py` | buy and sell cost rates by region (estimates) |
123
+
124
+ ### Data layout in MongoDB
125
+
126
+ | Database | Collections the package reads or writes |
127
+ |---|---|
128
+ | `<REGION>_prices` | `prices` (date, ticker, price, volume), `index` (year, quarter, ticker, volume_rank), `market` (benchmark), `tickers` (ticker, name), `errors` |
129
+ | `<REGION>_factors` | one collection per factor `name` (date, ticker, factor) |
130
+ | `<REGION>_financials` | `financials` (ticker, date, year, quarter, filed, statement fields) |
131
+ | `<strategy>_<universe>` | results you save: `normalized_data`, `allocations`, `portfolios`, `errors`, check runs |
132
+ | `<strategy>_<universe>_paper` | the paper ledger: account, positions, trades, value history |
133
+
134
+ ## Extending it
135
+
136
+ - **A strategy:** subclass `ASingleFactorStrategy` (set `factor`) or `AMultiFactorStrategy` (list `factors`).
137
+ Override `strategy_specific` to change how members and prices are picked.
138
+ - **A data feed for PriceUpdater:** an object with `latest_day(today)`, `stocks(tickers, start, end)`,
139
+ `benchmark(start, end)` (DataFrames with date and, for stocks, ticker), `errors` (dict) and `source` (str).
140
+ - **A real broker:** subclass `BaseBroker`; record fills in a `BookLedger` so the trade checks still apply.
141
+ - **Market rules for the checks:** fill a `CheckSettings` per region (daily move limit, stale days, ...).
142
+ - **A new region:** add a `Regions` member and its `trading_costs` entry.
143
+
144
+ ## Known limits
145
+
146
+ - Only `UniverseType.VOLUME` has an index ranking today (`index.volume_rank`); SIZE and PRICE are placeholders.
147
+ - The Japan trading-cost rate is a placeholder, not researched.
148
+ - Dates: some stored data keeps ISO text dates, some keeps datetimes; the helpers compare plain days.
149
+
150
+ ## More
151
+
152
+ - [CODEMAP.md](CODEMAP.md): every file and where to change what.
153
+ - [CHANGELOG.md](CHANGELOG.md): releases.
154
+
eqdesk-0.1.1/README.md ADDED
@@ -0,0 +1,127 @@
1
+ # eqdesk
2
+
3
+ Run factor strategies as books. eqdesk sits on top of [factorframe](https://github.com/ejchungie/factorframe):
4
+ factorframe computes factors, weights and backtests; eqdesk adds the desk around them.
5
+ - **Strategies** pick each quarter's stocks from a ranked index, using only what was known then.
6
+ - A **paper broker** trades a book with fees and keeps a full ledger.
7
+ - A **Book** reads and writes a strategy's data in MongoDB.
8
+ - **Price updates** add new prices from your own data feed.
9
+ - **Book checks** test whether a book's numbers can be trusted.
10
+
11
+ Status: early (0.x); the API can change between minor versions. MIT licence. Python 3.13+.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pip install eqdesk # installs factorframe too
17
+ ```
18
+
19
+ The strategy and backtest parts run on plain DataFrames. Book, the providers, PaperBook and PriceUpdater
20
+ need a MongoDB server (default `localhost:27017`).
21
+
22
+ ## Quickstart (no database needed)
23
+
24
+ ```python
25
+ from pandas import DataFrame
26
+
27
+ from factorframe.data_definitions.financials import generate_financial_dummy_data
28
+ from factorframe.factor.single_factor import SingleFactor
29
+ from factorframe.metric.metric import Metrics
30
+ from factorframe.portfolio.allocation_type import AllocationType
31
+ from factorframe.portfolio.factor_portfolio import FactorPortfolio
32
+ from factorframe.portfolio.weighting import WeightingType
33
+ from factorframe.utils.timeframe import TimeFrame
34
+
35
+ from eqdesk.data_definitions.regions import Regions
36
+ from eqdesk.data_definitions.universe import Universe
37
+ from eqdesk.strategy.asinglefactorstrategy import ASingleFactorStrategy
38
+
39
+
40
+ class EquityToAssets(SingleFactor):
41
+ name = "equity_to_assets"
42
+ timeframe = TimeFrame.QUARTER
43
+ factor_delay = 1
44
+ factor_memory = 1
45
+
46
+ def factor_calculations(self, data: DataFrame) -> DataFrame:
47
+ data["factor"] = data["total_equity"] / data["total_assets"]
48
+ return data.dropna(subset=["date"])[["date", "ticker", "factor"]]
49
+
50
+
51
+ class EquityToAssetsStrategy(ASingleFactorStrategy):
52
+ factor = EquityToAssets()
53
+
54
+
55
+ # 20 stocks; each quarter the 10 most traded form the index and the strategy holds 5 of them
56
+ universe = Universe(Regions.UNITED_STATES, index_size=10, holdings=5)
57
+ portfolio = FactorPortfolio(TimeFrame.QUARTER, WeightingType.FACTOR, AllocationType.INDEXING)
58
+ strategy = EquityToAssetsStrategy("example", portfolio, universe, TimeFrame.QUARTER)
59
+
60
+ financials = generate_financial_dummy_data(num_tickers=20, num_years=5)
61
+ factors = strategy.factor.calculate(financials)
62
+ prices = financials[["date", "ticker", "price"]].assign(volume=1000)
63
+ index = financials.assign(year=financials["date"].dt.year, quarter=financials["date"].dt.quarter)
64
+ index["volume_rank"] = index.groupby(["year", "quarter"])["volume"].rank(ascending=False, method="first")
65
+ index = index[["year", "quarter", "ticker", "volume_rank"]]
66
+
67
+ result = strategy.historical_performance(factors, prices, index)
68
+ print(strategy.universe.name, Metrics(periods_per_year=4).calculate(result.dropna(subset=["weight"])))
69
+ # <universe name> {'total_return': ..., 'annualized_volatility': ..., 'sharpe_ratio': ..., 'max_drawdown': ...}
70
+ ```
71
+
72
+ ## How it fits together
73
+
74
+ ```mermaid
75
+ flowchart LR
76
+ FEED["your data feed"] --> PU["PriceUpdater<br/>new prices into MongoDB"]
77
+ PU --> DB[("&lt;REGION&gt;_prices · _factors · _financials")]
78
+ DB --> BK["Book(strategy)<br/>reads data, writes &lt;strategy&gt;_&lt;universe&gt;"]
79
+ ST["Strategy<br/>(factor + portfolio + Universe)"] --> BK
80
+ BK --> HP["historical_performance<br/>allocations, portfolio"]
81
+ HP --> PB["PaperBook + Paper broker<br/>trades, ledger, value history"]
82
+ HP --> CK["checks<br/>pass / warn / fail"]
83
+ PB --> CK
84
+ ```
85
+
86
+ | Concept | Where | What it is |
87
+ |---|---|---|
88
+ | Region | `data_definitions/regions.py` | a market; prefixes its databases (`UNITED_STATES_prices`) |
89
+ | Universe | `data_definitions/universe.py` | region + index size + how many to hold; its `name` (`<short>_<TYPE>_<size>`) names the book |
90
+ | Strategy | `strategy/` | a factor (or several) + a factorframe portfolio + a Universe |
91
+ | Book | `book/book.py` | a strategy plus its databases: `with Book(strategy) as book:` |
92
+ | Providers | `providers/` | pick database names: `<REGION>_prices`, `<REGION>_factors`, `<REGION>_financials`, `<strategy>_<universe>` |
93
+ | Paper trading | `brokers/` | `Paper` broker, `BookLedger`, `PaperBook` (database `<strategy>_<universe>_paper`), `PaperReader` |
94
+ | Price updates | `pipeline/price_updater.py` | `PriceUpdater(database, feed).update(tickers, today)` |
95
+ | Checks | `checks/` | functions returning `CheckResult` (pass / warn / fail, message, rows) |
96
+ | Trading costs | `data_definitions/trading_costs.py` | buy and sell cost rates by region (estimates) |
97
+
98
+ ### Data layout in MongoDB
99
+
100
+ | Database | Collections the package reads or writes |
101
+ |---|---|
102
+ | `<REGION>_prices` | `prices` (date, ticker, price, volume), `index` (year, quarter, ticker, volume_rank), `market` (benchmark), `tickers` (ticker, name), `errors` |
103
+ | `<REGION>_factors` | one collection per factor `name` (date, ticker, factor) |
104
+ | `<REGION>_financials` | `financials` (ticker, date, year, quarter, filed, statement fields) |
105
+ | `<strategy>_<universe>` | results you save: `normalized_data`, `allocations`, `portfolios`, `errors`, check runs |
106
+ | `<strategy>_<universe>_paper` | the paper ledger: account, positions, trades, value history |
107
+
108
+ ## Extending it
109
+
110
+ - **A strategy:** subclass `ASingleFactorStrategy` (set `factor`) or `AMultiFactorStrategy` (list `factors`).
111
+ Override `strategy_specific` to change how members and prices are picked.
112
+ - **A data feed for PriceUpdater:** an object with `latest_day(today)`, `stocks(tickers, start, end)`,
113
+ `benchmark(start, end)` (DataFrames with date and, for stocks, ticker), `errors` (dict) and `source` (str).
114
+ - **A real broker:** subclass `BaseBroker`; record fills in a `BookLedger` so the trade checks still apply.
115
+ - **Market rules for the checks:** fill a `CheckSettings` per region (daily move limit, stale days, ...).
116
+ - **A new region:** add a `Regions` member and its `trading_costs` entry.
117
+
118
+ ## Known limits
119
+
120
+ - Only `UniverseType.VOLUME` has an index ranking today (`index.volume_rank`); SIZE and PRICE are placeholders.
121
+ - The Japan trading-cost rate is a placeholder, not researched.
122
+ - Dates: some stored data keeps ISO text dates, some keeps datetimes; the helpers compare plain days.
123
+
124
+ ## More
125
+
126
+ - [CODEMAP.md](CODEMAP.md): every file and where to change what.
127
+ - [CHANGELOG.md](CHANGELOG.md): releases.
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "eqdesk"
3
+ version = "0.1.1"
4
+ description = "Run factor strategies as paper books: strategies, paper broker, book checks."
5
+ license = "MIT"
6
+ readme = "README.md"
7
+ authors = [{name = "chung-ejy", email = "avocadoedevs@gmail.com"}]
8
+ keywords = ["finance", "factor investing", "paper trading", "backtesting", "mongodb"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Financial and Insurance Industry",
12
+ "Intended Audience :: Science/Research",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.13",
15
+ "Topic :: Office/Business :: Financial :: Investment",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ requires-python = ">=3.13"
19
+ dependencies = [
20
+ "pandas>=3.0.3,<4.0.0",
21
+ "pymongo>=4.17.0,<5.0.0",
22
+ "factorframe>=0.1.1,<0.2",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/ejchungie/eqdesk"
27
+ Repository = "https://github.com/ejchungie/eqdesk"
28
+ Issues = "https://github.com/ejchungie/eqdesk/issues"
29
+ Changelog = "https://github.com/ejchungie/eqdesk/blob/main/CHANGELOG.md"
30
+
31
+ [tool.poetry]
32
+ packages = [{include = "eqdesk", from = "src"}]
33
+
34
+ [build-system]
35
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
36
+ build-backend = "poetry.core.masonry.api"
37
+
38
+ [dependency-groups]
39
+ dev = ["pytest>=9.1.1,<10.0.0"]
40
+
41
+ [tool.pytest.ini_options]
42
+ pythonpath = ["src"]
43
+ testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ """Run factor strategies as paper books."""
@@ -0,0 +1,144 @@
1
+ """Book: one strategy on its universe, with the databases it reads (prices, factors, financials) and writes (its book)."""
2
+ from eqdesk.strategy.afactorstrategy import AFactorStrategy
3
+ from eqdesk.providers.factor_provider import FactorProvider
4
+ from eqdesk.providers.price_provider import PriceProvider
5
+ from eqdesk.providers.book_provider import BookProvider
6
+ from eqdesk.providers.financial_provider import FinancialProvider
7
+
8
+ import pandas as pd
9
+ from pandas import DataFrame
10
+
11
+
12
+ class Book(object):
13
+ """A strategy applied to its universe, with the data it needs.
14
+
15
+ The Book owns the providers: it reads prices and factors and writes only to its own book
16
+ database (e.g. <strategy>_<universe>, eq #55). Strategies never touch a provider.
17
+ Use it as `with Book(strategy) as book:` to open and close all three connections.
18
+ """
19
+
20
+ def __init__(self,strategy:AFactorStrategy):
21
+ self.strategy = strategy
22
+ region = strategy.universe.region
23
+ self.factor_provider = FactorProvider(region)
24
+ self.price_provider = PriceProvider(region)
25
+ self.book_provider = BookProvider(strategy)
26
+ self.financial_provider = FinancialProvider(region) # statements, read by the book checks (eq #58)
27
+
28
+ def _databases(self):
29
+ return (self.price_provider.database, self.factor_provider.database, self.book_provider.database,
30
+ self.financial_provider.database)
31
+
32
+ def __enter__(self):
33
+ for database in self._databases():
34
+ database.connect()
35
+ return self
36
+
37
+ def __exit__(self, *exc):
38
+ for database in self._databases():
39
+ database.close()
40
+
41
+ def constituents(self) -> DataFrame:
42
+ """Every "index" row of the universe's tickers, ranks above the limit included, so the strategy
43
+ can fill a gap: year, quarter, ticker, volume_rank."""
44
+ return pd.DataFrame(self.price_provider.database.find_many("index",{"ticker":{"$in":self.tickers()}}))
45
+
46
+ def tickers(self) -> list[str]:
47
+ """Every ticker that reaches the index size in at least one quarter (the data to load)."""
48
+ index_size = self.strategy.universe.index_size
49
+ rows = self.price_provider.database.find_many("index",{"volume_rank":{"$lte":index_size}})
50
+ return sorted({row["ticker"] for row in rows if row.get("ticker")})
51
+
52
+ def ticker_factors(self,ticker:str) -> DataFrame:
53
+ """The strategy's factors for one ticker, one column per factor, merged on date and ticker.
54
+ A factor that fails to load is recorded in the book's "errors" collection and skipped."""
55
+ frames = []
56
+ for factor in self.strategy.factors:
57
+ try:
58
+ records = self.factor_provider.database.find_many(factor.name,{"ticker":ticker})
59
+ if records:
60
+ frames.append(pd.DataFrame(records).drop(columns=["_id"],errors="ignore")
61
+ .rename(columns={"factor":factor.name}))
62
+ except Exception as e:
63
+ self.book_provider.database.insert_one("errors",{"ticker":ticker,"factor":factor.name,"message":str(e)})
64
+ if not frames:
65
+ return DataFrame()
66
+ merged = frames[0]
67
+ for frame in frames[1:]:
68
+ merged = merged.merge(frame,on=["date","ticker"],how="left",validate="one_to_one")
69
+ return merged
70
+
71
+ def prices_and_normalized(self,tickers:list[str] | None = None) -> tuple[DataFrame,DataFrame]:
72
+ """Prices and saved normalized_data for every ticker (default: the universe) that has both;
73
+ a ticker missing either is printed and skipped."""
74
+ prices, normalized = [], []
75
+ for ticker in self.tickers() if tickers is None else tickers:
76
+ price_docs = self.price_provider.database.find_many("prices",{"ticker":ticker})
77
+ normalized_docs = self.book_provider.database.find_many("normalized_data",{"ticker":ticker})
78
+ if price_docs and normalized_docs:
79
+ prices.extend(price_docs)
80
+ normalized.extend(normalized_docs)
81
+ else:
82
+ print(ticker,"missing data",len(price_docs),len(normalized_docs))
83
+ return pd.DataFrame(prices), pd.DataFrame(normalized)
84
+
85
+ def results(self,collection:str) -> DataFrame:
86
+ """A saved collection from the book database, e.g. "portfolios" or "allocations"."""
87
+ return pd.DataFrame(self.book_provider.database.find_many(collection))
88
+
89
+ def latest_allocations(self) -> DataFrame:
90
+ """The book's allocations on its last date, empty if it has none."""
91
+ return self.allocations_on()
92
+
93
+ def allocations_on(self, date=None) -> DataFrame:
94
+ """The allocations in effect on a day (its own or the last one before it); the latest with no date."""
95
+ database = self.book_provider.database
96
+ # the whole day: US allocations are stored at 04:00, trades at midnight
97
+ query = {"date": {"$lt": pd.Timestamp(date).normalize() + pd.Timedelta(days=1)}} if date else {}
98
+ last = database.last_document("allocations", "date", query)
99
+ return pd.DataFrame(database.find_many("allocations", {"date": last["date"]})) if last else pd.DataFrame()
100
+
101
+ def statements(self, fields: tuple[str, ...] = ("ticker", "date", "year", "quarter", "filed", "total_assets")) -> DataFrame:
102
+ """The universe's quarterly statements (only the fields asked for that exist), for the book checks."""
103
+ rows = pd.DataFrame(self.financial_provider.database.find_many("financials", {"ticker": {"$in": self.tickers()}}))
104
+ return rows[[field for field in fields if field in rows]] if not rows.empty else rows
105
+
106
+ def prices_on(self, tickers: list[str], start, end) -> DataFrame:
107
+ """Stored prices (ticker, date, price) for some stocks between two days, both included (eq #59: fill checks)."""
108
+ first, after = pd.Timestamp(start).normalize(), pd.Timestamp(end).normalize() + pd.Timedelta(days=1)
109
+ # US prices store dates as ISO text ("2026-11-30T05:00:00Z"), Korea as datetimes: ask for both
110
+ query = {"ticker": {"$in": list(tickers)}, "$or": [
111
+ {"date": {"$gte": first, "$lt": after}},
112
+ {"date": {"$gte": first.strftime("%Y-%m-%d"), "$lt": after.strftime("%Y-%m-%d")}}]}
113
+ return pd.DataFrame(self.price_provider.database.find_many("prices", query))
114
+
115
+ def tickers_with(self, collection: str) -> set[str]:
116
+ """Universe tickers that have rows in "prices" (price database) or "normalized_data" (book database)."""
117
+ database = self.price_provider.database if collection == "prices" else self.book_provider.database
118
+ return set(database.find_unique_values(collection, "ticker", {"ticker": {"$in": self.tickers()}}))
119
+
120
+ def market(self) -> DataFrame:
121
+ """The region's benchmark index series (date, price, ...)."""
122
+ return pd.DataFrame(self.price_provider.database.find_many("market"))
123
+
124
+ def names(self) -> dict[str,str]:
125
+ """Company name by ticker (the ticker itself where no name is stored)."""
126
+ return {t["ticker"]: t.get("name", t["ticker"]) for t in self.price_provider.database.find_many("tickers")}
127
+
128
+ def save(self,collection:str,data:DataFrame):
129
+ """Replace a collection in the book database (refuses empty data)."""
130
+ if data.empty:
131
+ raise ValueError(f"Refusing to replace {collection!r} with empty data")
132
+ self.book_provider.database.drop_collection(collection)
133
+ self.book_provider.database.insert_many(collection,data.to_dict("records"))
134
+ if "ticker" in data: # dropping the collection dropped its index
135
+ self.book_provider.database.create_index(collection,["ticker"])
136
+
137
+ def save_one(self,collection:str,document:dict):
138
+ """Replace a collection in the book database with one document."""
139
+ self.book_provider.database.drop_collection(collection)
140
+ self.book_provider.database.insert_one(collection,document)
141
+
142
+ def append(self,collection:str,document:dict):
143
+ """Add one document to a book collection, keeping the earlier ones (e.g. each book-check run)."""
144
+ self.book_provider.database.insert_one(collection,document)
@@ -0,0 +1,43 @@
1
+ """BaseBroker: the contract every broker meets (buy, sell, positions, account, history, fills)."""
2
+ from abc import ABC, abstractmethod
3
+ from eqdesk.data_definitions.regions import Regions
4
+ from pandas import DataFrame
5
+
6
+ class BaseBroker(ABC):
7
+ """A broker for one region. Amounts are notional (money, in the region's currency); limit is an
8
+ optional limit price. Each method returns a DataFrame of the rows it produced or holds."""
9
+
10
+ @property
11
+ @abstractmethod
12
+ def region(self) -> Regions:
13
+ ...
14
+
15
+ @property
16
+ @abstractmethod
17
+ def broker(self) -> str:
18
+ ...
19
+
20
+ @abstractmethod
21
+ def buy(self,ticker,notional,limit) -> DataFrame:
22
+ ...
23
+
24
+ @abstractmethod
25
+ def sell(self,ticker,notional,limit) -> DataFrame:
26
+ ...
27
+
28
+ @abstractmethod
29
+ def positions(self) -> DataFrame:
30
+ ...
31
+
32
+ @abstractmethod
33
+ def account(self) -> DataFrame:
34
+ ...
35
+
36
+ @abstractmethod
37
+ def history(self) -> DataFrame:
38
+ ...
39
+
40
+ @abstractmethod
41
+ def fills(self, since) -> DataFrame:
42
+ """Filled orders from this date on. A real broker can fill later or in parts, so the ledger records fills."""
43
+ ...
@@ -0,0 +1,110 @@
1
+ """One book's own record of cash, positions and trades, whichever broker executes them.
2
+
3
+ A real account pools every book, so only this ledger knows which shares belong to which book.
4
+ `trades` is the permanent record; `positions` and `account` are current views rebuilt on each save.
5
+ """
6
+ import pandas as pd
7
+
8
+ POSITION_COLUMNS = ["ticker", "shares", "avg_cost", "last_price", "price_date", "value", "weight"]
9
+ TRADE_COLUMNS = ["order_id", "date", "ticker", "side", "notional", "limit", "shares", "fill_price", "fee", "status", "reason"]
10
+
11
+
12
+ class BookLedger:
13
+
14
+ def __init__(self, book: str, database=None):
15
+ self.book, self.database = book, database
16
+ self.cash, self.start_cash, self.start_date, self.fees_paid = 0.0, 0.0, None, 0.0
17
+ self.holdings: dict[str, dict] = {} # ticker -> shares, avg_cost, last_price, price_date
18
+ self.trades: list[dict] = []
19
+ self._saved_trades = 0
20
+
21
+ def open(self, cash: float, date):
22
+ self.cash, self.start_cash, self.start_date = float(cash), float(cash), date
23
+
24
+ def next_order_id(self) -> str:
25
+ return f"{self.book}-{len(self.trades) + 1}"
26
+
27
+ def record(self, trade: dict):
28
+ """Every order goes in the trades; a fill also moves cash and shares."""
29
+ self.trades.append(trade)
30
+ if trade["status"] != "filled":
31
+ return
32
+ self.fees_paid += trade["fee"]
33
+ if trade["side"] == "buy":
34
+ self._add(trade)
35
+ else:
36
+ self._remove(trade)
37
+
38
+ def _add(self, trade: dict):
39
+ self.cash -= trade["notional"] + trade["fee"]
40
+ held = self.holdings.get(trade["ticker"], {"shares": 0.0, "avg_cost": 0.0})
41
+ shares = held["shares"] + trade["shares"]
42
+ cost = (held["shares"] * held["avg_cost"] + trade["notional"]) / shares
43
+ self.holdings[trade["ticker"]] = {"shares": shares, "avg_cost": cost, "last_price": trade["fill_price"], "price_date": trade["date"]}
44
+
45
+ def _remove(self, trade: dict):
46
+ self.cash += trade["notional"] - trade["fee"]
47
+ held = self.holdings[trade["ticker"]]
48
+ held["shares"] -= trade["shares"]
49
+ if held["shares"] <= 1e-9: # sold everything, apart from rounding
50
+ del self.holdings[trade["ticker"]]
51
+
52
+ def shares(self, ticker: str) -> float:
53
+ return self.holdings.get(ticker, {}).get("shares", 0.0)
54
+
55
+ def mark(self, date, prices: dict[str, float]):
56
+ """Revalue holdings at new prices. A stock with no new price keeps its last one."""
57
+ for ticker, held in self.holdings.items():
58
+ if ticker in prices:
59
+ held["last_price"], held["price_date"] = float(prices[ticker]), date
60
+
61
+ def positions_value(self) -> float:
62
+ return sum(held["shares"] * held["last_price"] for held in self.holdings.values())
63
+
64
+ def positions(self) -> pd.DataFrame:
65
+ total = self.cash + self.positions_value()
66
+ rows = [{"ticker": ticker, **held, "value": held["shares"] * held["last_price"],
67
+ "weight": held["shares"] * held["last_price"] / total} for ticker, held in self.holdings.items()]
68
+ return pd.DataFrame(rows, columns=POSITION_COLUMNS)
69
+
70
+ def account(self) -> pd.DataFrame:
71
+ return pd.DataFrame([{"book": self.book, "start_date": self.start_date, "start_cash": self.start_cash, "cash": self.cash,
72
+ "fees_paid": self.fees_paid, "positions_value": self.positions_value(),
73
+ "total": self.cash + self.positions_value()}])
74
+
75
+ def history(self) -> pd.DataFrame:
76
+ return pd.DataFrame(self.trades, columns=TRADE_COLUMNS)
77
+
78
+ def load(self) -> bool:
79
+ """Read the saved book. False when this book has never been saved."""
80
+ self.database.connect()
81
+ account = self.database.find_one("account", {})
82
+ if account is None:
83
+ self.database.close()
84
+ return False
85
+ self.cash, self.start_cash, self.start_date = account["cash"], account["start_cash"], account["start_date"]
86
+ self.fees_paid = account["fees_paid"]
87
+ self.holdings = {row["ticker"]: {k: row[k] for k in ("shares", "avg_cost", "last_price", "price_date")}
88
+ for row in self.database.find_many("positions")}
89
+ self.trades = [{k: row.get(k) for k in TRADE_COLUMNS} for row in self.database.find_many("trades")]
90
+ self._saved_trades = len(self.trades)
91
+ self.database.close()
92
+ return True
93
+
94
+ def save(self, date, benchmark: float | None = None):
95
+ """Trades first, so a run that dies partway can be rebuilt. A second run on a date replaces that date's history."""
96
+ self.database.connect()
97
+ self.database.insert_many("trades", [dict(trade) for trade in self.trades[self._saved_trades:]])
98
+ self._saved_trades = len(self.trades)
99
+ positions = self.positions().to_dict("records")
100
+ self.database.drop_collection("positions")
101
+ self.database.insert_many("positions", [dict(row) for row in positions])
102
+ self.database.drop_collection("account")
103
+ self.database.insert_one("account", self.account().to_dict("records")[0])
104
+ self.database.delete_many("holdings_history", {"date": date})
105
+ self.database.insert_many("holdings_history", [{"date": date, **row} for row in positions])
106
+ self.database.upsert_by_field("value_history", "date", {"date": date, "cash": self.cash, "positions_value": self.positions_value(),
107
+ "total": self.cash + self.positions_value(), "benchmark": benchmark})
108
+ for collection in ("trades", "positions", "holdings_history"): # positions is dropped each save; a rebuild drops all three
109
+ self.database.create_index(collection, ["ticker"])
110
+ self.database.close()