eqdesk 0.1.1__py3-none-any.whl
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.
- eqdesk/__init__.py +1 -0
- eqdesk/book/book.py +144 -0
- eqdesk/brokers/base_broker.py +43 -0
- eqdesk/brokers/book_ledger.py +110 -0
- eqdesk/brokers/paper.py +76 -0
- eqdesk/brokers/paper_book.py +99 -0
- eqdesk/brokers/paper_reader.py +71 -0
- eqdesk/checks/__init__.py +1 -0
- eqdesk/checks/days.py +7 -0
- eqdesk/checks/inputs.py +34 -0
- eqdesk/checks/performance.py +64 -0
- eqdesk/checks/prices.py +67 -0
- eqdesk/checks/result.py +45 -0
- eqdesk/checks/settings.py +16 -0
- eqdesk/checks/statements.py +39 -0
- eqdesk/checks/trades.py +119 -0
- eqdesk/data_definitions/__init__.py +0 -0
- eqdesk/data_definitions/regions.py +17 -0
- eqdesk/data_definitions/trading_costs.py +9 -0
- eqdesk/data_definitions/universe.py +32 -0
- eqdesk/database/mongodb.py +174 -0
- eqdesk/pipeline/__init__.py +0 -0
- eqdesk/pipeline/price_updater.py +71 -0
- eqdesk/providers/__init__.py +0 -0
- eqdesk/providers/base_provider.py +10 -0
- eqdesk/providers/book_provider.py +10 -0
- eqdesk/providers/factor_provider.py +11 -0
- eqdesk/providers/financial_provider.py +11 -0
- eqdesk/providers/price_provider.py +11 -0
- eqdesk/strategy/__init__.py +0 -0
- eqdesk/strategy/afactorstrategy.py +63 -0
- eqdesk/strategy/amultifactorstrategy.py +65 -0
- eqdesk/strategy/asinglefactorstrategy.py +40 -0
- eqdesk/strategy/constituents.py +54 -0
- eqdesk-0.1.1.dist-info/METADATA +154 -0
- eqdesk-0.1.1.dist-info/RECORD +38 -0
- eqdesk-0.1.1.dist-info/WHEEL +4 -0
- eqdesk-0.1.1.dist-info/licenses/LICENSE +21 -0
eqdesk/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Run factor strategies as paper books."""
|
eqdesk/book/book.py
ADDED
|
@@ -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()
|
eqdesk/brokers/paper.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The pretend broker: fills orders at the prices it is given, with fees, and keeps its book's ledger."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
|
|
5
|
+
from eqdesk.brokers.base_broker import BaseBroker
|
|
6
|
+
from eqdesk.brokers.book_ledger import BookLedger
|
|
7
|
+
from eqdesk.data_definitions.regions import Regions
|
|
8
|
+
from eqdesk.data_definitions.trading_costs import COSTS
|
|
9
|
+
|
|
10
|
+
ROUNDING = 1e-9 # lets an order for exactly all the cash or all the shares through
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Paper(BaseBroker):
|
|
14
|
+
|
|
15
|
+
def __init__(self, region: Regions, ledger: BookLedger, slippage: float = 0.0):
|
|
16
|
+
"""slippage is a share of the price (0.001 = 0.1%). 0 by default: the US cost already includes the spread."""
|
|
17
|
+
self._region, self.ledger, self.slippage, self.costs = region, ledger, slippage, COSTS[region]
|
|
18
|
+
self.date, self.prices = None, {}
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def region(self) -> Regions:
|
|
22
|
+
return self._region
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def broker(self) -> str:
|
|
26
|
+
return "paper"
|
|
27
|
+
|
|
28
|
+
def set_prices(self, date, prices: dict[str, float]):
|
|
29
|
+
"""Today's prices: what orders fill at and what holdings are valued at."""
|
|
30
|
+
self.date, self.prices = date, prices
|
|
31
|
+
self.ledger.mark(date, prices)
|
|
32
|
+
|
|
33
|
+
def buy(self, ticker, notional, limit=None) -> DataFrame:
|
|
34
|
+
return self._order("buy", ticker, notional, limit)
|
|
35
|
+
|
|
36
|
+
def sell(self, ticker, notional, limit=None) -> DataFrame:
|
|
37
|
+
return self._order("sell", ticker, notional, limit)
|
|
38
|
+
|
|
39
|
+
def _order(self, side: str, ticker, notional, limit) -> DataFrame:
|
|
40
|
+
sign = 1 if side == "buy" else -1
|
|
41
|
+
price = self.prices.get(ticker)
|
|
42
|
+
fill_price = None if price is None else price * (1 + sign * self.slippage)
|
|
43
|
+
fee = notional * self.costs[side]
|
|
44
|
+
reason = self._refusal(side, ticker, notional, limit, price, fill_price, fee)
|
|
45
|
+
trade = {"order_id": self.ledger.next_order_id(), "date": self.date, "ticker": ticker, "side": side, "notional": notional,
|
|
46
|
+
"limit": limit, "shares": None, "fill_price": None, "fee": 0.0, "status": "refused", "reason": reason}
|
|
47
|
+
if reason is None:
|
|
48
|
+
trade.update(shares=notional / fill_price, fill_price=fill_price, fee=fee, status="filled")
|
|
49
|
+
self.ledger.record(trade)
|
|
50
|
+
return DataFrame([trade])
|
|
51
|
+
|
|
52
|
+
def _refusal(self, side, ticker, notional, limit, price, fill_price, fee) -> str | None:
|
|
53
|
+
if price is None:
|
|
54
|
+
return "no price"
|
|
55
|
+
if notional <= 0:
|
|
56
|
+
return "amount must be above zero"
|
|
57
|
+
if limit is not None and (fill_price > limit if side == "buy" else fill_price < limit):
|
|
58
|
+
return "limit not met"
|
|
59
|
+
if side == "buy" and notional + fee > self.ledger.cash * (1 + ROUNDING):
|
|
60
|
+
return "not enough cash"
|
|
61
|
+
if side == "sell" and notional / fill_price > self.ledger.shares(ticker) * (1 + ROUNDING):
|
|
62
|
+
return "more than held"
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
def positions(self) -> DataFrame:
|
|
66
|
+
return self.ledger.positions()
|
|
67
|
+
|
|
68
|
+
def account(self) -> DataFrame:
|
|
69
|
+
return self.ledger.account()
|
|
70
|
+
|
|
71
|
+
def history(self) -> DataFrame:
|
|
72
|
+
return self.ledger.history()
|
|
73
|
+
|
|
74
|
+
def fills(self, since) -> DataFrame:
|
|
75
|
+
trades = self.ledger.history()
|
|
76
|
+
return trades[(trades["status"] == "filled") & (pd.to_datetime(trades["date"]) >= pd.Timestamp(since))].reset_index(drop=True)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""One book's paper account: bought once from its allocations, then revalued at each new set of prices."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
from eqdesk.brokers.book_ledger import BookLedger
|
|
5
|
+
from eqdesk.brokers.paper import Paper
|
|
6
|
+
from eqdesk.database.mongodb import MongoDb
|
|
7
|
+
|
|
8
|
+
START_CASH = 1_000_000 # in the book's local currency
|
|
9
|
+
BIG_MOVE = 0.30 # worth a look: often a split, since new prices are adjusted and held shares are not
|
|
10
|
+
MIN_TRADE = 0.0001 # a rebalance skips trades smaller than 0.01% of the book
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def paper_book_name(strategy) -> str:
|
|
14
|
+
"""The paper book's database name: <strategy>_<universe>_paper."""
|
|
15
|
+
return f"{strategy.name}_{strategy.universe.name}_paper"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PaperBook:
|
|
19
|
+
"""A paper account for one strategy, stored in its own database <strategy>_<universe>_paper.
|
|
20
|
+
|
|
21
|
+
first_buy() buys the allocations with START_CASH; rebalance() trades to new weights;
|
|
22
|
+
revalue() marks holdings to new prices; save() writes the ledger."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, strategy, database=None):
|
|
25
|
+
name = paper_book_name(strategy)
|
|
26
|
+
self.name, self.region = name, strategy.universe.region
|
|
27
|
+
self.ledger = BookLedger(name, database if database is not None else MongoDb(name))
|
|
28
|
+
self.paper = Paper(self.region, self.ledger)
|
|
29
|
+
self.is_open = self.ledger.load()
|
|
30
|
+
self.big_moves, self.refused = [], []
|
|
31
|
+
|
|
32
|
+
def held(self) -> list[str]:
|
|
33
|
+
return list(self.ledger.holdings)
|
|
34
|
+
|
|
35
|
+
def last_trade_date(self):
|
|
36
|
+
return max((trade["date"] for trade in self.ledger.trades), default=None)
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def needs_rebalance(latest: pd.DataFrame, traded: pd.DataFrame) -> bool:
|
|
40
|
+
"""True when the latest allocations' weights differ from the ones the book last traded to (eq #51)."""
|
|
41
|
+
def weights(allocations): # rounded like backdate_paper.changes, so float noise isn't a new quarter
|
|
42
|
+
return allocations.groupby("ticker")["weight"].sum().round(8).sort_index().to_dict()
|
|
43
|
+
return not latest.empty and (traded.empty or weights(latest) != weights(traded))
|
|
44
|
+
|
|
45
|
+
def first_buy(self, allocations: pd.DataFrame, latest: pd.DataFrame):
|
|
46
|
+
"""Buys the allocations' weights at the latest prices, keeping enough cash for the fees."""
|
|
47
|
+
self.ledger.open(START_CASH, latest["date"].max().to_pydatetime())
|
|
48
|
+
self.rebalance(allocations, latest)
|
|
49
|
+
|
|
50
|
+
def rebalance(self, allocations: pd.DataFrame, latest: pd.DataFrame):
|
|
51
|
+
"""Moves the book to the allocations' weights at these prices: sells first, then buys with the cash there is."""
|
|
52
|
+
self.paper.set_prices(latest["date"].max().to_pydatetime(), dict(zip(latest["ticker"], latest["price"])))
|
|
53
|
+
total = self.ledger.cash + self.ledger.positions_value()
|
|
54
|
+
weights = allocations.groupby("ticker")["weight"].sum()
|
|
55
|
+
targets = (weights / weights.sum() * total).to_dict()
|
|
56
|
+
values = {ticker: held["shares"] * held["last_price"] for ticker, held in self.ledger.holdings.items()}
|
|
57
|
+
for ticker, value in values.items():
|
|
58
|
+
excess = value - targets.get(ticker, 0.0)
|
|
59
|
+
if excess > total * MIN_TRADE:
|
|
60
|
+
self._order(self.paper.sell, ticker, min(excess, value))
|
|
61
|
+
buys = {ticker: target - values.get(ticker, 0.0) for ticker, target in targets.items()}
|
|
62
|
+
buys = {ticker: amount for ticker, amount in buys.items() if amount > total * MIN_TRADE}
|
|
63
|
+
scale = min(1.0, self.ledger.cash / ((1 + self.paper.costs["buy"]) * sum(buys.values()))) if buys else 1.0
|
|
64
|
+
for ticker, amount in buys.items():
|
|
65
|
+
self._order(self.paper.buy, ticker, amount * scale)
|
|
66
|
+
|
|
67
|
+
def _order(self, side, ticker, amount):
|
|
68
|
+
order = side(ticker, amount).iloc[0]
|
|
69
|
+
if order["status"] != "filled":
|
|
70
|
+
self.refused.append((ticker, order["reason"]))
|
|
71
|
+
|
|
72
|
+
def revalue(self, latest: pd.DataFrame):
|
|
73
|
+
"""Oldest date first, so a stock that stopped trading keeps the date of its own last price."""
|
|
74
|
+
self.big_moves = self._big_moves(latest)
|
|
75
|
+
for date, prices in latest.sort_values("date").groupby("date"):
|
|
76
|
+
self.paper.set_prices(date.to_pydatetime(), dict(zip(prices["ticker"], prices["price"])))
|
|
77
|
+
|
|
78
|
+
def _big_moves(self, latest: pd.DataFrame) -> list[tuple[str, float]]:
|
|
79
|
+
moves = []
|
|
80
|
+
for row in latest.itertuples():
|
|
81
|
+
held = self.ledger.holdings.get(row.ticker)
|
|
82
|
+
if held and abs(row.price / held["last_price"] - 1) > BIG_MOVE:
|
|
83
|
+
moves.append((row.ticker, row.price / held["last_price"] - 1))
|
|
84
|
+
return moves
|
|
85
|
+
|
|
86
|
+
def save(self, benchmark: float | None):
|
|
87
|
+
self.ledger.save(self.paper.date, benchmark)
|
|
88
|
+
|
|
89
|
+
def summary(self) -> str:
|
|
90
|
+
account = self.ledger.account().iloc[0]
|
|
91
|
+
total, start = account["total"], account["start_cash"]
|
|
92
|
+
positions = self.ledger.positions()
|
|
93
|
+
latest = positions["price_date"].max() if not positions.empty else None
|
|
94
|
+
stale = int((positions["price_date"] < latest).sum()) if latest is not None else 0
|
|
95
|
+
lines = [f"{self.name}: {len(positions)} stocks at {str(latest)[:10]}, value {total:,.0f}, cash {account['cash']:,.0f}, "
|
|
96
|
+
f"fees {account['fees_paid']:,.0f}, {total / start - 1:+.2%} since {str(account['start_date'])[:10]}, older prices: {stale}"]
|
|
97
|
+
lines += [f" check {ticker}: {move:+.0%} since the last update" for ticker, move in self.big_moves]
|
|
98
|
+
lines += [f" refused {ticker}: {reason}" for ticker, reason in self.refused]
|
|
99
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Reads one paper book's saved records for the dashboard. Read only: it never writes or downloads."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
from eqdesk.brokers.book_ledger import POSITION_COLUMNS, TRADE_COLUMNS
|
|
5
|
+
from eqdesk.database.mongodb import MongoDb
|
|
6
|
+
|
|
7
|
+
VALUE_COLUMNS = ["date", "total", "benchmark", "book_index", "benchmark_index"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PaperReader:
|
|
11
|
+
|
|
12
|
+
def __init__(self, book: str, database=None):
|
|
13
|
+
self.book = book
|
|
14
|
+
self.database = database if database is not None else MongoDb(book)
|
|
15
|
+
|
|
16
|
+
def _rows(self, collection: str) -> list[dict]:
|
|
17
|
+
self.database.connect()
|
|
18
|
+
rows = [{k: v for k, v in row.items() if k != "_id"} for row in self.database.find_many(collection)]
|
|
19
|
+
self.database.close()
|
|
20
|
+
return rows
|
|
21
|
+
|
|
22
|
+
def account(self) -> dict | None:
|
|
23
|
+
rows = self._rows("account")
|
|
24
|
+
return rows[0] if rows else None
|
|
25
|
+
|
|
26
|
+
def value(self) -> pd.DataFrame:
|
|
27
|
+
"""One row per date. Book and benchmark are both indexed to 100 on the first date that has each."""
|
|
28
|
+
df = pd.DataFrame(self._rows("value_history"), columns=["date", "total", "benchmark"])
|
|
29
|
+
if df.empty:
|
|
30
|
+
return pd.DataFrame(columns=VALUE_COLUMNS)
|
|
31
|
+
df = df.sort_values("date").reset_index(drop=True)
|
|
32
|
+
df["benchmark"] = pd.to_numeric(df["benchmark"], errors="coerce") # None (no benchmark price) becomes NaN
|
|
33
|
+
df["book_index"] = df["total"] / df["total"].iloc[0] * 100
|
|
34
|
+
first_benchmark = df["benchmark"].dropna()
|
|
35
|
+
df["benchmark_index"] = df["benchmark"] / first_benchmark.iloc[0] * 100 if not first_benchmark.empty else float("nan")
|
|
36
|
+
return df[VALUE_COLUMNS]
|
|
37
|
+
|
|
38
|
+
def positions(self) -> pd.DataFrame:
|
|
39
|
+
df = pd.DataFrame(self._rows("positions"), columns=POSITION_COLUMNS)
|
|
40
|
+
return df.sort_values("weight", ascending=False).reset_index(drop=True)
|
|
41
|
+
|
|
42
|
+
def trades(self) -> pd.DataFrame:
|
|
43
|
+
df = pd.DataFrame(self._rows("trades"), columns=TRADE_COLUMNS)
|
|
44
|
+
return df.sort_values("date", ascending=False).reset_index(drop=True)
|
|
45
|
+
|
|
46
|
+
def holdings_history(self) -> pd.DataFrame:
|
|
47
|
+
"""Each saved day's positions (date, ticker, shares, value, weight, ...), for the book checks (eq #59)."""
|
|
48
|
+
return pd.DataFrame(self._rows("holdings_history"))
|
|
49
|
+
|
|
50
|
+
def performers(self) -> dict | None:
|
|
51
|
+
"""The held stocks with the biggest and smallest gain since bought (last price / average cost - 1),
|
|
52
|
+
as {"best": {...}, "worst": {...}}; None when nothing is held."""
|
|
53
|
+
df = self.positions()
|
|
54
|
+
if df.empty:
|
|
55
|
+
return None
|
|
56
|
+
gains = df["last_price"] / df["avg_cost"] - 1
|
|
57
|
+
pick = lambda i: {"ticker": df.at[i, "ticker"], "gain": gains[i], "value": df.at[i, "value"]}
|
|
58
|
+
return {"best": pick(gains.idxmax()), "worst": pick(gains.idxmin())}
|
|
59
|
+
|
|
60
|
+
def summary(self) -> dict | None:
|
|
61
|
+
"""What a book's card shows; None when the book has never been saved."""
|
|
62
|
+
account, value = self.account(), self.value()
|
|
63
|
+
if account is None:
|
|
64
|
+
return None
|
|
65
|
+
book_return = account["total"] / account["start_cash"] - 1
|
|
66
|
+
bench = value["benchmark_index"].dropna()
|
|
67
|
+
bench_return = bench.iloc[-1] / 100 - 1 if not bench.empty else None
|
|
68
|
+
positions = self.positions()
|
|
69
|
+
return {"total": account["total"], "start_date": account["start_date"], "return": book_return,
|
|
70
|
+
"vs_benchmark": book_return - bench_return if bench_return is not None else None,
|
|
71
|
+
"price_date": positions["price_date"].max() if not positions.empty else None}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Book checks (eq #57–#60): small functions that say whether a book's numbers can be trusted."""
|
eqdesk/checks/days.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Calendar days for the book checks: stored dates mix plain (Korea) and UTC (US benchmark) times of day."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def days(dates) -> pd.Series:
|
|
6
|
+
"""Each date as a plain calendar day: UTC times read as UTC, then the time and zone dropped."""
|
|
7
|
+
return pd.to_datetime(pd.Series(dates), utc=True).dt.tz_localize(None).dt.normalize()
|
eqdesk/checks/inputs.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Input checks for one book (eq #58): the right stocks, nothing skipped quietly, a benchmark that covers the book."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
from eqdesk.checks.days import days
|
|
5
|
+
from eqdesk.checks.result import CheckResult, Status
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def dated_index_members(allocations: pd.DataFrame, index_rows: pd.DataFrame) -> CheckResult:
|
|
9
|
+
"""Every held stock was in that quarter's own index (no stock picked with hindsight from today's members)."""
|
|
10
|
+
members = set(zip(index_rows["year"], index_rows["quarter"], index_rows["ticker"]))
|
|
11
|
+
held = allocations[["year", "quarter", "ticker"]].drop_duplicates()
|
|
12
|
+
broken = held[[(y, q, t) not in members for y, q, t in zip(held["year"], held["quarter"], held["ticker"])]]
|
|
13
|
+
return CheckResult.judge("dated_index_members", broken, f"all {len(held)} quarter holdings were in that quarter's index")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def skipped_stocks(universe: list[str], with_prices: set[str], with_factors: set[str], errors: pd.DataFrame) -> CheckResult:
|
|
17
|
+
"""Universe stocks left out for missing prices or factors, and anything in the book's `errors` (warnings)."""
|
|
18
|
+
rows = [{"ticker": t, "missing": "prices"} for t in universe if t not in with_prices]
|
|
19
|
+
rows += [{"ticker": t, "missing": "factors"} for t in universe if t in with_prices and t not in with_factors]
|
|
20
|
+
if not errors.empty:
|
|
21
|
+
rows += [{"ticker": e.get("ticker"), "missing": f"error: {e.get('message', e.get('error', ''))}"}
|
|
22
|
+
for e in errors.to_dict("records")]
|
|
23
|
+
return CheckResult.judge("skipped_stocks", pd.DataFrame(rows), f"none of {len(universe)} universe stocks skipped",
|
|
24
|
+
Status.WARN)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def benchmark_coverage(allocations: pd.DataFrame, market: pd.DataFrame) -> CheckResult:
|
|
28
|
+
"""The benchmark runs at least to the book's last day."""
|
|
29
|
+
book_last = days(allocations["date"]).max()
|
|
30
|
+
market_last = days(market["date"]).max() if not market.empty else None
|
|
31
|
+
if market_last is not None and market_last >= book_last:
|
|
32
|
+
return CheckResult("benchmark_coverage", Status.PASS, f"benchmark runs to {market_last:%Y-%m-%d}, book to {book_last:%Y-%m-%d}")
|
|
33
|
+
broken = pd.DataFrame([{"book_last": book_last, "benchmark_last": market_last}])
|
|
34
|
+
return CheckResult("benchmark_coverage", Status.FAIL, "benchmark ends before the book's last day", broken)
|