PaperTrade-India 0.1.0.dev0__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.
Files changed (101) hide show
  1. papertrade_india/__init__.py +250 -0
  2. papertrade_india/_context.py +144 -0
  3. papertrade_india/broker.py +546 -0
  4. papertrade_india/cli.py +474 -0
  5. papertrade_india/clock.py +29 -0
  6. papertrade_india/corporate_actions/__init__.py +10 -0
  7. papertrade_india/corporate_actions/bonus.py +105 -0
  8. papertrade_india/corporate_actions/dividends.py +99 -0
  9. papertrade_india/corporate_actions/rights.py +189 -0
  10. papertrade_india/corporate_actions/splits.py +111 -0
  11. papertrade_india/corporate_actions/store.py +247 -0
  12. papertrade_india/data/nse_holidays_2026.json +22 -0
  13. papertrade_india/data/nse_holidays_2027.json +9 -0
  14. papertrade_india/data/nse_universe_sample.csv +31 -0
  15. papertrade_india/domain/__init__.py +6 -0
  16. papertrade_india/domain/exceptions.py +183 -0
  17. papertrade_india/domain/models.py +213 -0
  18. papertrade_india/domain/rules/__init__.py +5 -0
  19. papertrade_india/domain/rules/risk.py +165 -0
  20. papertrade_india/domain/rules/tick_lot_band.py +139 -0
  21. papertrade_india/events.py +29 -0
  22. papertrade_india/exceptions.py +29 -0
  23. papertrade_india/execution/__init__.py +5 -0
  24. papertrade_india/execution/book.py +385 -0
  25. papertrade_india/execution/fees.py +213 -0
  26. papertrade_india/execution/settlement.py +360 -0
  27. papertrade_india/execution/simulation.py +176 -0
  28. papertrade_india/execution/slippage.py +120 -0
  29. papertrade_india/fees.py +29 -0
  30. papertrade_india/idempotency.py +29 -0
  31. papertrade_india/infrastructure/__init__.py +6 -0
  32. papertrade_india/infrastructure/clock.py +123 -0
  33. papertrade_india/infrastructure/events.py +137 -0
  34. papertrade_india/infrastructure/holidays.py +138 -0
  35. papertrade_india/infrastructure/idempotency.py +133 -0
  36. papertrade_india/infrastructure/ledger.py +141 -0
  37. papertrade_india/infrastructure/market_hours.py +200 -0
  38. papertrade_india/infrastructure/migrations.py +622 -0
  39. papertrade_india/infrastructure/observability.py +195 -0
  40. papertrade_india/infrastructure/persistence.py +130 -0
  41. papertrade_india/infrastructure/symbols.py +279 -0
  42. papertrade_india/infrastructure/watchlist.py +78 -0
  43. papertrade_india/interface.py +92 -0
  44. papertrade_india/ledger.py +29 -0
  45. papertrade_india/limit_orders.py +29 -0
  46. papertrade_india/market_hours.py +29 -0
  47. papertrade_india/microstructure.py +57 -0
  48. papertrade_india/migrations.py +29 -0
  49. papertrade_india/models.py +29 -0
  50. papertrade_india/observability.py +29 -0
  51. papertrade_india/orders/__init__.py +5 -0
  52. papertrade_india/orders/amo.py +98 -0
  53. papertrade_india/orders/book_helpers.py +111 -0
  54. papertrade_india/orders/bracket.py +115 -0
  55. papertrade_india/orders/limit.py +210 -0
  56. papertrade_india/orders/market.py +264 -0
  57. papertrade_india/orders/partial_fills.py +92 -0
  58. papertrade_india/orders/preopen.py +274 -0
  59. papertrade_india/orders/state.py +640 -0
  60. papertrade_india/orders/stop.py +122 -0
  61. papertrade_india/orders/submit.py +385 -0
  62. papertrade_india/partial_fills.py +29 -0
  63. papertrade_india/persistence.py +29 -0
  64. papertrade_india/preopen.py +29 -0
  65. papertrade_india/presets.py +120 -0
  66. papertrade_india/price_feed.py +316 -0
  67. papertrade_india/providers/__init__.py +123 -0
  68. papertrade_india/providers/alphavantage.py +180 -0
  69. papertrade_india/providers/base.py +256 -0
  70. papertrade_india/providers/cache.py +147 -0
  71. papertrade_india/providers/composite.py +244 -0
  72. papertrade_india/providers/dhan.py +266 -0
  73. papertrade_india/providers/finnhub.py +122 -0
  74. papertrade_india/providers/health.py +233 -0
  75. papertrade_india/providers/jugaad.py +142 -0
  76. papertrade_india/providers/kite.py +222 -0
  77. papertrade_india/providers/nse_bhavcopy.py +210 -0
  78. papertrade_india/providers/nsepython.py +98 -0
  79. papertrade_india/providers/registry.py +226 -0
  80. papertrade_india/providers/stooq.py +173 -0
  81. papertrade_india/providers/twelvedata.py +198 -0
  82. papertrade_india/providers/upstox.py +318 -0
  83. papertrade_india/providers/upstox_instruments.py +171 -0
  84. papertrade_india/providers/yfinance.py +205 -0
  85. papertrade_india/quickstart.py +111 -0
  86. papertrade_india/reads/__init__.py +6 -0
  87. papertrade_india/reads/account.py +140 -0
  88. papertrade_india/reads/orders.py +54 -0
  89. papertrade_india/reads/positions.py +188 -0
  90. papertrade_india/risk.py +29 -0
  91. papertrade_india/settlement.py +29 -0
  92. papertrade_india/simulation.py +29 -0
  93. papertrade_india/slippage.py +29 -0
  94. papertrade_india/symbols.py +29 -0
  95. papertrade_india/workers/__init__.py +6 -0
  96. papertrade_india/workers/limit_orders.py +390 -0
  97. papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
  98. papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
  99. papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
  100. papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  101. papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,99 @@
1
+ """Cash dividend corporate action.
2
+
3
+ Credits ``amount_per_share * qty_held`` to the account's cash on the
4
+ ex-date and records a ``dividend`` row in the ledger.
5
+
6
+ Tax-aware behavior is *not* modeled: in reality, Indian dividend income
7
+ is taxable to the recipient (and TDS may apply for some holders), but
8
+ that's beyond the scope of a paper simulator.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ..infrastructure import ledger as _ledger
17
+ from . import store as _store
18
+
19
+ if TYPE_CHECKING: # pragma: no cover
20
+ from .._context import BrokerContext
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def apply(
26
+ ctx: BrokerContext,
27
+ symbol: str,
28
+ amount_per_share: float,
29
+ ex_date: str | None = None,
30
+ notes: str | None = None,
31
+ ) -> str:
32
+ """Apply a cash dividend to the broker's holding.
33
+
34
+ Returns the action id. Calling twice on the same dividend
35
+ double-credits — wrap in your own dedup if needed.
36
+ """
37
+ if amount_per_share <= 0:
38
+ raise ValueError("amount_per_share must be positive")
39
+ ex_date = ex_date or ctx.clock.now().date().isoformat()
40
+ now = ctx.now_iso()
41
+
42
+ with ctx.persistence.transaction() as conn:
43
+ action_id = _store.record_dividend(
44
+ conn,
45
+ symbol=symbol,
46
+ exchange=ctx.default_exchange.value,
47
+ amount_per_share=amount_per_share,
48
+ ex_date=ex_date,
49
+ applied_at_iso=now,
50
+ notes=notes,
51
+ )
52
+ row = conn.execute(
53
+ "SELECT qty FROM positions "
54
+ "WHERE account_id = ? AND symbol = ?",
55
+ (ctx.account_id, symbol),
56
+ ).fetchone()
57
+ if row is None or row["qty"] <= 0:
58
+ logger.info(
59
+ "DIVIDEND %s ₹%.4f/sh recorded; no holding to credit",
60
+ symbol, amount_per_share,
61
+ )
62
+ return action_id
63
+
64
+ credit = row["qty"] * amount_per_share
65
+ conn.execute(
66
+ "UPDATE account SET cash = cash + ? WHERE account_id = ?",
67
+ (credit, ctx.account_id),
68
+ )
69
+ _ledger.record(
70
+ conn,
71
+ account_id=ctx.account_id,
72
+ amount=credit,
73
+ reason="dividend",
74
+ recorded_at_iso=now,
75
+ symbol=symbol,
76
+ notes=f"Dividend ₹{amount_per_share}/sh × {row['qty']:g}",
77
+ )
78
+ ctx.emit(
79
+ conn,
80
+ event_type="corporate_action",
81
+ payload={
82
+ "type": "dividend",
83
+ "symbol": symbol,
84
+ "per_share": amount_per_share,
85
+ "qty": row["qty"],
86
+ "credit": credit,
87
+ "ex_date": ex_date,
88
+ },
89
+ )
90
+
91
+ ctx.drain_pending_events()
92
+ logger.info(
93
+ "DIVIDEND %s ₹%.4f/sh credited ₹%.2f to %s",
94
+ symbol, amount_per_share, credit, ctx.account_id,
95
+ )
96
+ return action_id
97
+
98
+
99
+ __all__ = ["apply"]
@@ -0,0 +1,189 @@
1
+ """Rights issue corporate action.
2
+
3
+ The user opts in via ``subscribe=True``. When subscribing, cash is
4
+ debited at ``subscription_price`` per new share, the position grows,
5
+ and the average cost is adjusted to preserve the round-trip P&L
6
+ invariant.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from fractions import Fraction
13
+ from typing import TYPE_CHECKING
14
+
15
+ from ..domain.exceptions import InsufficientFundsError
16
+ from ..infrastructure import ledger as _ledger
17
+ from . import store as _store
18
+
19
+ if TYPE_CHECKING: # pragma: no cover
20
+ from .._context import BrokerContext
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def apply(
26
+ ctx: BrokerContext,
27
+ symbol: str,
28
+ ratio_num: int,
29
+ ratio_den: int,
30
+ subscription_price: float,
31
+ subscribe: bool = False,
32
+ ex_date: str | None = None,
33
+ notes: str | None = None,
34
+ ) -> str:
35
+ """Record a rights issue and optionally subscribe.
36
+
37
+ Rights issue mechanics: holders receive a *right* (not an
38
+ obligation) to buy ``ratio_num`` new shares per ``ratio_den`` held,
39
+ at ``subscription_price`` per share — typically below market. The
40
+ user must opt in by passing ``subscribe=True``; otherwise the rights
41
+ lapse (no position change, no cash debit).
42
+
43
+ When ``subscribe=True``:
44
+
45
+ - ``new_shares = floor(qty_held * ratio_num / ratio_den)``
46
+ - Cash is debited by ``new_shares * subscription_price``.
47
+ - Position grows: new ``qty = old_qty + new_shares``,
48
+ ``avg_cost`` recomputed so total basis = old basis +
49
+ subscription cost (preserves the round-trip P&L invariant).
50
+ - Insufficient cash raises :class:`InsufficientFundsError`.
51
+
52
+ Returns the action id whether or not the user subscribes.
53
+ """
54
+ if ratio_num <= 0 or ratio_den <= 0:
55
+ raise ValueError("ratio components must be positive integers")
56
+ if subscription_price <= 0:
57
+ raise ValueError("subscription_price must be positive")
58
+ rights_ratio = Fraction(ratio_num, ratio_den)
59
+ ex_date = ex_date or ctx.clock.now().date().isoformat()
60
+ now = ctx.now_iso()
61
+
62
+ with ctx.persistence.transaction() as conn:
63
+ action_id = _store.record_rights(
64
+ conn,
65
+ symbol=symbol,
66
+ exchange=ctx.default_exchange.value,
67
+ ratio=rights_ratio,
68
+ subscription_price=subscription_price,
69
+ ex_date=ex_date,
70
+ applied_at_iso=now,
71
+ notes=notes,
72
+ )
73
+ existing = conn.execute(
74
+ "SELECT qty, avg_cost FROM positions "
75
+ "WHERE account_id = ? AND symbol = ?",
76
+ (ctx.account_id, symbol),
77
+ ).fetchone()
78
+
79
+ if not subscribe or existing is None:
80
+ logger.info(
81
+ "RIGHTS %s %d:%d recorded; subscribe=%s, holding=%s",
82
+ symbol, ratio_num, ratio_den, subscribe,
83
+ "none" if existing is None else f"{existing['qty']:g}",
84
+ )
85
+ ctx.emit(
86
+ conn,
87
+ event_type="corporate_action",
88
+ payload={
89
+ "type": "rights",
90
+ "symbol": symbol,
91
+ "ratio_num": ratio_num,
92
+ "ratio_den": ratio_den,
93
+ "subscription_price": subscription_price,
94
+ "subscribed": False,
95
+ "ex_date": ex_date,
96
+ },
97
+ )
98
+ ctx.drain_pending_events()
99
+ return action_id
100
+
101
+ # Subscribe path: integer-floor the entitlement, charge cash,
102
+ # add shares.
103
+ old_qty = existing["qty"]
104
+ old_avg = existing["avg_cost"]
105
+ new_shares = int(old_qty * ratio_num // ratio_den)
106
+ if new_shares <= 0:
107
+ logger.info(
108
+ "RIGHTS %s %d:%d subscribe=True but entitlement rounded to zero",
109
+ symbol, ratio_num, ratio_den,
110
+ )
111
+ ctx.emit(
112
+ conn,
113
+ event_type="corporate_action",
114
+ payload={
115
+ "type": "rights",
116
+ "symbol": symbol,
117
+ "ratio_num": ratio_num,
118
+ "ratio_den": ratio_den,
119
+ "subscription_price": subscription_price,
120
+ "subscribed": True,
121
+ "new_shares": 0,
122
+ "ex_date": ex_date,
123
+ },
124
+ )
125
+ ctx.drain_pending_events()
126
+ return action_id
127
+
128
+ cost = new_shares * subscription_price
129
+ cash = conn.execute(
130
+ "SELECT cash FROM account WHERE account_id = ?",
131
+ (ctx.account_id,),
132
+ ).fetchone()["cash"]
133
+ if cost > cash:
134
+ raise InsufficientFundsError(
135
+ f"Rights subscription needs ₹{cost:,.2f}, have ₹{cash:,.2f}",
136
+ )
137
+
138
+ conn.execute(
139
+ "UPDATE account SET cash = cash - ? WHERE account_id = ?",
140
+ (cost, ctx.account_id),
141
+ )
142
+ _ledger.record(
143
+ conn,
144
+ account_id=ctx.account_id,
145
+ amount=-cost,
146
+ reason="adjustment",
147
+ recorded_at_iso=now,
148
+ symbol=symbol,
149
+ notes=(
150
+ f"Rights subscription: {new_shares} sh × "
151
+ f"₹{subscription_price:.2f}"
152
+ ),
153
+ )
154
+
155
+ new_qty = old_qty + new_shares
156
+ new_basis = old_qty * old_avg + cost
157
+ new_avg = new_basis / new_qty
158
+ conn.execute(
159
+ "UPDATE positions SET qty = ?, avg_cost = ? "
160
+ "WHERE account_id = ? AND symbol = ?",
161
+ (new_qty, new_avg, ctx.account_id, symbol),
162
+ )
163
+ ctx.emit(
164
+ conn,
165
+ event_type="corporate_action",
166
+ payload={
167
+ "type": "rights",
168
+ "symbol": symbol,
169
+ "ratio_num": ratio_num,
170
+ "ratio_den": ratio_den,
171
+ "subscription_price": subscription_price,
172
+ "subscribed": True,
173
+ "new_shares": new_shares,
174
+ "cost": cost,
175
+ "ex_date": ex_date,
176
+ },
177
+ )
178
+
179
+ ctx.drain_pending_events()
180
+ logger.info(
181
+ "RIGHTS %s %d:%d subscribed: +%d sh @ ₹%.2f (₹%.2f total) "
182
+ "-> %g sh avg ₹%.4f",
183
+ symbol, ratio_num, ratio_den, new_shares, subscription_price,
184
+ cost, new_qty, new_avg,
185
+ )
186
+ return action_id
187
+
188
+
189
+ __all__ = ["apply"]
@@ -0,0 +1,111 @@
1
+ """Stock split corporate action.
2
+
3
+ A split adjusts the holding so the total cost basis is preserved:
4
+ ``new_qty = old_qty * num/den`` and ``new_avg = old_avg * den/num``.
5
+ The exchange mechanics are recorded for audit by
6
+ :func:`store.record_split`; this module owns the position adjustment.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from fractions import Fraction
13
+ from typing import TYPE_CHECKING
14
+
15
+ from . import store as _store
16
+
17
+ if TYPE_CHECKING: # pragma: no cover
18
+ from .._context import BrokerContext
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def apply(
24
+ ctx: BrokerContext,
25
+ symbol: str,
26
+ ratio_num: int,
27
+ ratio_den: int = 1,
28
+ ex_date: str | None = None,
29
+ notes: str | None = None,
30
+ ) -> str:
31
+ """Apply a stock split / bonus issue to the broker's holding.
32
+
33
+ Parameters
34
+ ----------
35
+ ctx:
36
+ Shared broker context.
37
+ symbol:
38
+ The split symbol.
39
+ ratio_num, ratio_den:
40
+ New shares per old. A 2:1 split is ``ratio_num=2``, ``ratio_den=1``
41
+ (qty doubles, avg_cost halves). A 1:5 reverse split is
42
+ ``ratio_num=1, ratio_den=5``.
43
+ ex_date:
44
+ ISO date string. Defaults to today (per the broker's clock).
45
+ notes:
46
+ Optional free-text annotation stored on the action row.
47
+
48
+ Returns the action id. Idempotency is *not* enforced — calling twice
49
+ applies the split twice. Wrap in your own dedup if needed.
50
+ """
51
+ if ratio_num <= 0 or ratio_den <= 0:
52
+ raise ValueError("ratio components must be positive integers")
53
+ ratio = Fraction(ratio_num, ratio_den)
54
+ ex_date = ex_date or ctx.clock.now().date().isoformat()
55
+ now = ctx.now_iso()
56
+
57
+ with ctx.persistence.transaction() as conn:
58
+ action_id = _store.record_split(
59
+ conn,
60
+ symbol=symbol,
61
+ exchange=ctx.default_exchange.value,
62
+ ratio=ratio,
63
+ ex_date=ex_date,
64
+ applied_at_iso=now,
65
+ notes=notes,
66
+ )
67
+ existing = conn.execute(
68
+ "SELECT qty, avg_cost FROM positions "
69
+ "WHERE account_id = ? AND symbol = ?",
70
+ (ctx.account_id, symbol),
71
+ ).fetchone()
72
+ if existing is None:
73
+ logger.info(
74
+ "SPLIT %s %d:%d recorded; no holding to adjust",
75
+ symbol, ratio_num, ratio_den,
76
+ )
77
+ return action_id
78
+
79
+ old_qty = existing["qty"]
80
+ old_avg = existing["avg_cost"]
81
+ new_qty = old_qty * (ratio_num / ratio_den)
82
+ new_avg = old_avg * (ratio_den / ratio_num)
83
+ conn.execute(
84
+ "UPDATE positions SET qty = ?, avg_cost = ? "
85
+ "WHERE account_id = ? AND symbol = ?",
86
+ (new_qty, new_avg, ctx.account_id, symbol),
87
+ )
88
+ ctx.emit(
89
+ conn,
90
+ event_type="corporate_action",
91
+ payload={
92
+ "type": "split",
93
+ "symbol": symbol,
94
+ "ratio_num": ratio_num,
95
+ "ratio_den": ratio_den,
96
+ "ex_date": ex_date,
97
+ "old_qty": old_qty,
98
+ "new_qty": new_qty,
99
+ },
100
+ )
101
+
102
+ ctx.drain_pending_events()
103
+ logger.info(
104
+ "SPLIT %s %d:%d applied to %s: %g → %g shares (avg ₹%.4f → ₹%.4f)",
105
+ symbol, ratio_num, ratio_den, ctx.account_id,
106
+ old_qty, new_qty, old_avg, new_avg,
107
+ )
108
+ return action_id
109
+
110
+
111
+ __all__ = ["apply"]
@@ -0,0 +1,247 @@
1
+ """Corporate actions: stock splits, bonus issues, rights issues, dividends.
2
+
3
+ Five methods on the broker — ``apply_split``, ``apply_bonus``,
4
+ ``apply_rights``, ``apply_dividend`` — each writes a row in
5
+ ``corporate_actions`` and atomically updates the relevant position(s)
6
+ and account cash.
7
+
8
+ What we model
9
+ -------------
10
+ - **Splits**: multiply ``qty`` by ``ratio.numerator/denominator``,
11
+ divide ``avg_cost`` by the same ratio. No cash impact. The position's
12
+ total cost basis (``qty * avg_cost``) is preserved, just spread over
13
+ more / fewer shares.
14
+ - **Bonus issues**: same arithmetic as a split, but recorded with
15
+ ``action_type='bonus'`` so the audit trail stays distinct. A 1:1
16
+ bonus = 2:1 split-equivalent.
17
+ - **Rights issues**: existing shareholders may subscribe to new shares
18
+ at a fixed ``subscription_price`` per the entitlement ratio. The
19
+ user opts in or lets the rights lapse — no automatic dilution.
20
+ - **Cash dividends**: credit ``per_share * qty`` to the holder's cash
21
+ on the ex-date. Tax is *not* withheld in the simulator — Indian
22
+ dividend TDS is recipient-specific and beyond scope.
23
+
24
+ What we don't model
25
+ -------------------
26
+ - **Demergers / spin-offs** (need a target-symbol mapping).
27
+ - **Special dividends with cash + shares**.
28
+ - **Mergers / acquisitions** (price discovery and ratio mapping).
29
+
30
+ Schema-wise, ``action_type`` accepts 'split', 'dividend', 'bonus',
31
+ 'rights', plus 'merger' and 'spinoff' as forward-compatible
32
+ placeholders (no broker methods yet).
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import sqlite3
38
+ import uuid
39
+ from dataclasses import dataclass
40
+ from datetime import datetime
41
+ from fractions import Fraction
42
+
43
+ SCHEMA = """
44
+ CREATE TABLE IF NOT EXISTS corporate_actions (
45
+ id TEXT PRIMARY KEY,
46
+ symbol TEXT NOT NULL,
47
+ exchange TEXT NOT NULL,
48
+ -- 'split': stock split / reverse split.
49
+ -- 'bonus': bonus issue (degenerate split with its own audit trail).
50
+ -- 'rights': rights issue (entitlement ratio + subscription_price).
51
+ -- 'dividend': cash dividend.
52
+ -- 'merger', 'spinoff' reserved for future use.
53
+ action_type TEXT NOT NULL CHECK(action_type IN (
54
+ 'split', 'dividend', 'bonus', 'rights', 'merger', 'spinoff'
55
+ )),
56
+ -- For splits / bonuses: numerator / denominator. Splits multiply
57
+ -- qty by num/den; bonuses give num new shares per den held.
58
+ -- For rights: entitlement ratio (num new shares per den held).
59
+ -- For dividends: leave NULL; use ``amount_per_share``.
60
+ ratio_num INTEGER,
61
+ ratio_den INTEGER,
62
+ -- For dividends: ₹ / share credit.
63
+ -- For rights: ₹ / share subscription price.
64
+ -- Otherwise NULL.
65
+ amount_per_share REAL,
66
+ ex_date TEXT NOT NULL,
67
+ notes TEXT,
68
+ applied_at TEXT NOT NULL
69
+ );
70
+
71
+ CREATE INDEX IF NOT EXISTS idx_corporate_actions_symbol_date
72
+ ON corporate_actions(symbol, ex_date);
73
+ """
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class CorporateAction:
78
+ id: str
79
+ symbol: str
80
+ exchange: str
81
+ action_type: str # 'split' | 'dividend'
82
+ ratio_num: int | None
83
+ ratio_den: int | None
84
+ amount_per_share: float | None
85
+ ex_date: str # ISO date string
86
+ notes: str | None
87
+ applied_at: datetime
88
+
89
+
90
+ def record_split(
91
+ conn: sqlite3.Connection,
92
+ symbol: str,
93
+ exchange: str,
94
+ ratio: Fraction,
95
+ ex_date: str,
96
+ applied_at_iso: str,
97
+ notes: str | None = None,
98
+ ) -> str:
99
+ return _record_ratio_action(
100
+ conn, symbol=symbol, exchange=exchange, action_type="split",
101
+ ratio=ratio, ex_date=ex_date, applied_at_iso=applied_at_iso,
102
+ notes=notes,
103
+ )
104
+
105
+
106
+ def record_bonus(
107
+ conn: sqlite3.Connection,
108
+ symbol: str,
109
+ exchange: str,
110
+ ratio: Fraction,
111
+ ex_date: str,
112
+ applied_at_iso: str,
113
+ notes: str | None = None,
114
+ ) -> str:
115
+ """Record a bonus issue.
116
+
117
+ A bonus issue gives existing shareholders ``num`` extra shares for
118
+ every ``den`` shares held — economically equivalent to a stock
119
+ split (``ratio_num+den : den``) but with its own audit trail.
120
+
121
+ Note that the *split-equivalent* ratio is ``(num + den) / den`` —
122
+ a 1:1 bonus doubles holdings (split-equivalent 2:1), 1:2 bonus =
123
+ 3:2 split-equivalent. We store the bonus's bonus-style ratio as
124
+ given so the audit trail stays honest, and the broker computes
125
+ the split equivalent at apply time.
126
+ """
127
+ return _record_ratio_action(
128
+ conn, symbol=symbol, exchange=exchange, action_type="bonus",
129
+ ratio=ratio, ex_date=ex_date, applied_at_iso=applied_at_iso,
130
+ notes=notes,
131
+ )
132
+
133
+
134
+ def record_rights(
135
+ conn: sqlite3.Connection,
136
+ symbol: str,
137
+ exchange: str,
138
+ ratio: Fraction,
139
+ subscription_price: float,
140
+ ex_date: str,
141
+ applied_at_iso: str,
142
+ notes: str | None = None,
143
+ ) -> str:
144
+ """Record a rights issue.
145
+
146
+ Existing shareholders are entitled to subscribe to ``num`` new
147
+ shares for every ``den`` held, at a fixed ``subscription_price``
148
+ that's typically below market. We store the entitlement ratio in
149
+ ``ratio_num`` / ``ratio_den`` and the price in ``amount_per_share``
150
+ (overloading that column — semantics swap based on
151
+ ``action_type``).
152
+
153
+ The simulator's :meth:`IndiaPaperBroker.apply_rights` records the
154
+ action and increments the position by the subscription if the
155
+ user opts in. Skipping is the default — the rights then lapse
156
+ (no position change).
157
+ """
158
+ action_id = uuid.uuid4().hex[:12]
159
+ conn.execute(
160
+ "INSERT INTO corporate_actions "
161
+ "(id, symbol, exchange, action_type, ratio_num, ratio_den, "
162
+ "amount_per_share, ex_date, notes, applied_at) "
163
+ "VALUES (?, ?, ?, 'rights', ?, ?, ?, ?, ?, ?)",
164
+ (
165
+ action_id, symbol, exchange,
166
+ ratio.numerator, ratio.denominator,
167
+ subscription_price, ex_date, notes, applied_at_iso,
168
+ ),
169
+ )
170
+ return action_id
171
+
172
+
173
+ def _record_ratio_action(
174
+ conn: sqlite3.Connection,
175
+ symbol: str,
176
+ exchange: str,
177
+ action_type: str,
178
+ ratio: Fraction,
179
+ ex_date: str,
180
+ applied_at_iso: str,
181
+ notes: str | None,
182
+ ) -> str:
183
+ action_id = uuid.uuid4().hex[:12]
184
+ conn.execute(
185
+ "INSERT INTO corporate_actions "
186
+ "(id, symbol, exchange, action_type, ratio_num, ratio_den, "
187
+ "amount_per_share, ex_date, notes, applied_at) "
188
+ "VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)",
189
+ (
190
+ action_id, symbol, exchange, action_type,
191
+ ratio.numerator, ratio.denominator,
192
+ ex_date, notes, applied_at_iso,
193
+ ),
194
+ )
195
+ return action_id
196
+
197
+
198
+ def record_dividend(
199
+ conn: sqlite3.Connection,
200
+ symbol: str,
201
+ exchange: str,
202
+ amount_per_share: float,
203
+ ex_date: str,
204
+ applied_at_iso: str,
205
+ notes: str | None = None,
206
+ ) -> str:
207
+ action_id = uuid.uuid4().hex[:12]
208
+ conn.execute(
209
+ "INSERT INTO corporate_actions "
210
+ "(id, symbol, exchange, action_type, ratio_num, ratio_den, "
211
+ "amount_per_share, ex_date, notes, applied_at) "
212
+ "VALUES (?, ?, ?, 'dividend', NULL, NULL, ?, ?, ?, ?)",
213
+ (
214
+ action_id, symbol, exchange, amount_per_share,
215
+ ex_date, notes, applied_at_iso,
216
+ ),
217
+ )
218
+ return action_id
219
+
220
+
221
+ def list_for_symbol(
222
+ conn: sqlite3.Connection,
223
+ symbol: str,
224
+ limit: int = 100,
225
+ ) -> list[CorporateAction]:
226
+ rows = conn.execute(
227
+ "SELECT id, symbol, exchange, action_type, ratio_num, ratio_den, "
228
+ "amount_per_share, ex_date, notes, applied_at "
229
+ "FROM corporate_actions WHERE symbol = ? "
230
+ "ORDER BY ex_date DESC, applied_at DESC LIMIT ?",
231
+ (symbol, limit),
232
+ ).fetchall()
233
+ return [
234
+ CorporateAction(
235
+ id=r["id"],
236
+ symbol=r["symbol"],
237
+ exchange=r["exchange"],
238
+ action_type=r["action_type"],
239
+ ratio_num=r["ratio_num"],
240
+ ratio_den=r["ratio_den"],
241
+ amount_per_share=r["amount_per_share"],
242
+ ex_date=r["ex_date"],
243
+ notes=r["notes"],
244
+ applied_at=datetime.fromisoformat(r["applied_at"]),
245
+ )
246
+ for r in rows
247
+ ]
@@ -0,0 +1,22 @@
1
+ {
2
+ "year": 2026,
3
+ "source": "NSE published trading holidays calendar (paraphrased; verify against https://www.nseindia.com/ before relying)",
4
+ "last_updated": "2025-12-15",
5
+ "note": "Best-effort weekday list. Update via scripts/update_nse_holidays.py once the official NSE calendar is published. Weekends are excluded (already non-trading).",
6
+ "holidays": [
7
+ "2026-01-26",
8
+ "2026-02-19",
9
+ "2026-03-03",
10
+ "2026-03-31",
11
+ "2026-04-03",
12
+ "2026-04-14",
13
+ "2026-05-01",
14
+ "2026-05-27",
15
+ "2026-08-26",
16
+ "2026-10-02",
17
+ "2026-10-21",
18
+ "2026-11-04",
19
+ "2026-11-24",
20
+ "2026-12-25"
21
+ ]
22
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "year": 2027,
3
+ "source": "Placeholder — refresh once NSE publishes the 2027 calendar.",
4
+ "last_updated": "2025-12-15",
5
+ "note": "Only fixed-date holidays that fall on a weekday in 2027. Holi/Diwali/Eid and other movable holidays must be added via scripts/update_nse_holidays.py once the official NSE calendar is published. Weekends are excluded (already non-trading).",
6
+ "holidays": [
7
+ "2027-01-26"
8
+ ]
9
+ }