darwin-calendar 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- darwin_calendar-0.1.0/PKG-INFO +139 -0
- darwin_calendar-0.1.0/README.md +123 -0
- darwin_calendar-0.1.0/pyproject.toml +34 -0
- darwin_calendar-0.1.0/pyproject.toml.orig +30 -0
- darwin_calendar-0.1.0/src/darwin_calendar/__init__.py +78 -0
- darwin_calendar-0.1.0/src/darwin_calendar/chunks.py +141 -0
- darwin_calendar-0.1.0/src/darwin_calendar/constants.py +65 -0
- darwin_calendar-0.1.0/src/darwin_calendar/core.py +240 -0
- darwin_calendar-0.1.0/src/darwin_calendar/exceptions.py +34 -0
- darwin_calendar-0.1.0/src/darwin_calendar/format.py +169 -0
- darwin_calendar-0.1.0/src/darwin_calendar/py.typed +0 -0
- darwin_calendar-0.1.0/src/darwin_calendar/ranges.py +73 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: darwin-calendar
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Trading-calendar and date utilities for Darwin data tools
|
|
5
|
+
Author: Hong
|
|
6
|
+
Author-email: Hong <sardineclub@126.com>
|
|
7
|
+
Requires-Dist: exchange-calendars>=4.13,<5
|
|
8
|
+
Requires-Dist: python-dateutil>=2.9
|
|
9
|
+
Requires-Dist: pytest>=7.0 ; extra == 'all'
|
|
10
|
+
Requires-Dist: pytest>=7.0 ; extra == 'test'
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Project-URL: Chinese Documentation, https://github.com/darwinalpha/darwin-calendar/blob/main/README.cn.md
|
|
13
|
+
Provides-Extra: all
|
|
14
|
+
Provides-Extra: test
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# darwin-calendar
|
|
18
|
+
|
|
19
|
+
[简体中文](https://github.com/darwinalpha/darwin-calendar/blob/main/README.cn.md)
|
|
20
|
+
|
|
21
|
+
Trading-day queries and date utilities for Darwin data tools, built on
|
|
22
|
+
`exchange_calendars` 4.13+.
|
|
23
|
+
|
|
24
|
+
- No bundled static calendar data. Calendars are instantiated with an explicit
|
|
25
|
+
early `start`, extending coverage back to 1990-12-19 (XTKS: 1997-01-01),
|
|
26
|
+
which supersedes the legacy CSV fallback.
|
|
27
|
+
- Domain-level exchange labels (`SSE`, `SZSE`, `HKEX`, `NASDAQ`, `NYSE`, `AMEX`,
|
|
28
|
+
`TSE`, `KRX`) map to official calendar names; labels sharing a market share
|
|
29
|
+
one cached calendar instance.
|
|
30
|
+
- Consistent `trading_day(s)` naming throughout the public API.
|
|
31
|
+
- Pure date helpers (formatting, chunking, millisecond conversion) are usable
|
|
32
|
+
without calendar configuration.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install darwin-calendar
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Python >= 3.12.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 1. Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from darwin_calendar import (
|
|
46
|
+
get_last_trading_day,
|
|
47
|
+
is_trading_day,
|
|
48
|
+
previous_trading_days,
|
|
49
|
+
trading_days_in_range,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
is_trading_day("2026-11-27", "SSE") # True
|
|
53
|
+
previous_trading_days("2026-11-27", 3, "SSE") # ['20261126', '20261125', '20261124']
|
|
54
|
+
trading_days_in_range("2026-11-23", "2026-11-27", "SSE")
|
|
55
|
+
get_last_trading_day("SSE") # 'YYYY-MM-DD'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`get_last_trading_day` treats a session as available only after its close plus
|
|
59
|
+
`cutoff_hours` (default `3.0`). Override the threshold explicitly, or pass a
|
|
60
|
+
`now` value for deterministic tests:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from datetime import datetime, timezone
|
|
64
|
+
|
|
65
|
+
get_last_trading_day("SSE", cutoff_hours=4)
|
|
66
|
+
get_last_trading_day("SSE", now=datetime(2026, 11, 27, 8, 0, tzinfo=timezone.utc))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## 2. Public API
|
|
72
|
+
|
|
73
|
+
### Trading days (`core.py`)
|
|
74
|
+
|
|
75
|
+
| Function | Returns |
|
|
76
|
+
| --- | --- |
|
|
77
|
+
| `get_calendar(exchange="SSE")` | Cached `ExchangeCalendar` instance |
|
|
78
|
+
| `is_trading_day(date, exchange="SSE")` | `bool` |
|
|
79
|
+
| `previous_trading_days(date, n=1, exchange="SSE")` | `list[str]`, newest first, `YYYYMMDD` |
|
|
80
|
+
| `trading_days_in_range(start, end, exchange="SSE")` | `list[str]`, newest first, `YYYYMMDD` |
|
|
81
|
+
| `next_trading_day(date, exchange="SSE")` | `str`, `YYYYMMDD` |
|
|
82
|
+
| `get_last_trading_day(exchange="SSE", cutoff_hours=3.0, now=None)` | `str`, `YYYY-MM-DD` |
|
|
83
|
+
|
|
84
|
+
### Date formatting (`format.py`)
|
|
85
|
+
|
|
86
|
+
| Function | Returns |
|
|
87
|
+
| --- | --- |
|
|
88
|
+
| `normalize_date(value)` | `YYYY-MM-DD` |
|
|
89
|
+
| `compact_date(value)` | `YYYYMMDD` |
|
|
90
|
+
| `parse_flexible_date(value)` | naive `datetime` |
|
|
91
|
+
| `date_to_millis_start(value)` | UTC+8 millisecond timestamp at 00:00:00.000 |
|
|
92
|
+
| `date_to_millis_end(value)` | UTC+8 millisecond timestamp at 23:59:59.999 |
|
|
93
|
+
| `normalize_date_input(start_date, end_date, since_ts_millis, until_ts_millis)` | `(start, end)` in `YYYYMMDD` |
|
|
94
|
+
|
|
95
|
+
### Range chunking (`chunks.py`)
|
|
96
|
+
|
|
97
|
+
| Function | Returns |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `chunk_days_range(start, end, chunk_days)` | `list[(start, end)]` in `YYYYMMDD` |
|
|
100
|
+
| `chunk_months_range(start, end, chunk_months)` | `list[(start, end, start_ms, end_ms)]`; `12` aligns to years, `1` to months |
|
|
101
|
+
|
|
102
|
+
### Range expansion (`ranges.py`)
|
|
103
|
+
|
|
104
|
+
| Function | Returns |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| `get_trade_date(date_str=None)` | Supplied date or latest trading day |
|
|
107
|
+
| `parse_date_range_from_date(date_str)` | `(start, end)` for a single day |
|
|
108
|
+
| `parse_date_range_from_year(year)` | `(start, end)`, capped at the latest trading day |
|
|
109
|
+
|
|
110
|
+
### Constants and exceptions
|
|
111
|
+
|
|
112
|
+
`CST`, `DEFAULT_EXCHANGE`, `DEFAULT_CUTOFF_HOURS`, `EXCHANGE_MAP`,
|
|
113
|
+
`DATES_SINGLE`, `DATES_RANGE`, `DATES_LIST`; `CalendarError`,
|
|
114
|
+
`UnknownExchangeError`.
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 3. Design notes
|
|
119
|
+
|
|
120
|
+
See [development guide](docs/development-guide.md) for design decisions,
|
|
121
|
+
including why no static CSV is shipped and which `dates.py` helpers were
|
|
122
|
+
intentionally left out of this library.
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 4. Conventions
|
|
127
|
+
|
|
128
|
+
- UTF-8 + LF everywhere; source files are checked by contract tests.
|
|
129
|
+
- Bilingual documentation and docstrings; public APIs are documented.
|
|
130
|
+
- Fast, offline unit tests with a fake calendar; real-calendar integration
|
|
131
|
+
tests use bundled data and need no network.
|
|
132
|
+
- Typed exceptions with context; `UnknownExchangeError` remains a `ValueError`
|
|
133
|
+
subclass for legacy-handler compatibility.
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## 5. License
|
|
138
|
+
|
|
139
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# darwin-calendar
|
|
2
|
+
|
|
3
|
+
[简体中文](https://github.com/darwinalpha/darwin-calendar/blob/main/README.cn.md)
|
|
4
|
+
|
|
5
|
+
Trading-day queries and date utilities for Darwin data tools, built on
|
|
6
|
+
`exchange_calendars` 4.13+.
|
|
7
|
+
|
|
8
|
+
- No bundled static calendar data. Calendars are instantiated with an explicit
|
|
9
|
+
early `start`, extending coverage back to 1990-12-19 (XTKS: 1997-01-01),
|
|
10
|
+
which supersedes the legacy CSV fallback.
|
|
11
|
+
- Domain-level exchange labels (`SSE`, `SZSE`, `HKEX`, `NASDAQ`, `NYSE`, `AMEX`,
|
|
12
|
+
`TSE`, `KRX`) map to official calendar names; labels sharing a market share
|
|
13
|
+
one cached calendar instance.
|
|
14
|
+
- Consistent `trading_day(s)` naming throughout the public API.
|
|
15
|
+
- Pure date helpers (formatting, chunking, millisecond conversion) are usable
|
|
16
|
+
without calendar configuration.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install darwin-calendar
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Python >= 3.12.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 1. Quick start
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from darwin_calendar import (
|
|
30
|
+
get_last_trading_day,
|
|
31
|
+
is_trading_day,
|
|
32
|
+
previous_trading_days,
|
|
33
|
+
trading_days_in_range,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
is_trading_day("2026-11-27", "SSE") # True
|
|
37
|
+
previous_trading_days("2026-11-27", 3, "SSE") # ['20261126', '20261125', '20261124']
|
|
38
|
+
trading_days_in_range("2026-11-23", "2026-11-27", "SSE")
|
|
39
|
+
get_last_trading_day("SSE") # 'YYYY-MM-DD'
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`get_last_trading_day` treats a session as available only after its close plus
|
|
43
|
+
`cutoff_hours` (default `3.0`). Override the threshold explicitly, or pass a
|
|
44
|
+
`now` value for deterministic tests:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from datetime import datetime, timezone
|
|
48
|
+
|
|
49
|
+
get_last_trading_day("SSE", cutoff_hours=4)
|
|
50
|
+
get_last_trading_day("SSE", now=datetime(2026, 11, 27, 8, 0, tzinfo=timezone.utc))
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 2. Public API
|
|
56
|
+
|
|
57
|
+
### Trading days (`core.py`)
|
|
58
|
+
|
|
59
|
+
| Function | Returns |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| `get_calendar(exchange="SSE")` | Cached `ExchangeCalendar` instance |
|
|
62
|
+
| `is_trading_day(date, exchange="SSE")` | `bool` |
|
|
63
|
+
| `previous_trading_days(date, n=1, exchange="SSE")` | `list[str]`, newest first, `YYYYMMDD` |
|
|
64
|
+
| `trading_days_in_range(start, end, exchange="SSE")` | `list[str]`, newest first, `YYYYMMDD` |
|
|
65
|
+
| `next_trading_day(date, exchange="SSE")` | `str`, `YYYYMMDD` |
|
|
66
|
+
| `get_last_trading_day(exchange="SSE", cutoff_hours=3.0, now=None)` | `str`, `YYYY-MM-DD` |
|
|
67
|
+
|
|
68
|
+
### Date formatting (`format.py`)
|
|
69
|
+
|
|
70
|
+
| Function | Returns |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `normalize_date(value)` | `YYYY-MM-DD` |
|
|
73
|
+
| `compact_date(value)` | `YYYYMMDD` |
|
|
74
|
+
| `parse_flexible_date(value)` | naive `datetime` |
|
|
75
|
+
| `date_to_millis_start(value)` | UTC+8 millisecond timestamp at 00:00:00.000 |
|
|
76
|
+
| `date_to_millis_end(value)` | UTC+8 millisecond timestamp at 23:59:59.999 |
|
|
77
|
+
| `normalize_date_input(start_date, end_date, since_ts_millis, until_ts_millis)` | `(start, end)` in `YYYYMMDD` |
|
|
78
|
+
|
|
79
|
+
### Range chunking (`chunks.py`)
|
|
80
|
+
|
|
81
|
+
| Function | Returns |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| `chunk_days_range(start, end, chunk_days)` | `list[(start, end)]` in `YYYYMMDD` |
|
|
84
|
+
| `chunk_months_range(start, end, chunk_months)` | `list[(start, end, start_ms, end_ms)]`; `12` aligns to years, `1` to months |
|
|
85
|
+
|
|
86
|
+
### Range expansion (`ranges.py`)
|
|
87
|
+
|
|
88
|
+
| Function | Returns |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `get_trade_date(date_str=None)` | Supplied date or latest trading day |
|
|
91
|
+
| `parse_date_range_from_date(date_str)` | `(start, end)` for a single day |
|
|
92
|
+
| `parse_date_range_from_year(year)` | `(start, end)`, capped at the latest trading day |
|
|
93
|
+
|
|
94
|
+
### Constants and exceptions
|
|
95
|
+
|
|
96
|
+
`CST`, `DEFAULT_EXCHANGE`, `DEFAULT_CUTOFF_HOURS`, `EXCHANGE_MAP`,
|
|
97
|
+
`DATES_SINGLE`, `DATES_RANGE`, `DATES_LIST`; `CalendarError`,
|
|
98
|
+
`UnknownExchangeError`.
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## 3. Design notes
|
|
103
|
+
|
|
104
|
+
See [development guide](docs/development-guide.md) for design decisions,
|
|
105
|
+
including why no static CSV is shipped and which `dates.py` helpers were
|
|
106
|
+
intentionally left out of this library.
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## 4. Conventions
|
|
111
|
+
|
|
112
|
+
- UTF-8 + LF everywhere; source files are checked by contract tests.
|
|
113
|
+
- Bilingual documentation and docstrings; public APIs are documented.
|
|
114
|
+
- Fast, offline unit tests with a fake calendar; real-calendar integration
|
|
115
|
+
tests use bundled data and need no network.
|
|
116
|
+
- Typed exceptions with context; `UnknownExchangeError` remains a `ValueError`
|
|
117
|
+
subclass for legacy-handler compatibility.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 5. License
|
|
122
|
+
|
|
123
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "darwin-calendar"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Trading-calendar and date utilities for Darwin data tools"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"exchange-calendars>=4.13,<5",
|
|
9
|
+
"python-dateutil>=2.9",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
[[project.authors]]
|
|
13
|
+
name = "Hong"
|
|
14
|
+
email = "sardineclub@126.com"
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
"Chinese Documentation" = "https://github.com/darwinalpha/darwin-calendar/blob/main/README.cn.md"
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
test = ["pytest>=7.0"]
|
|
21
|
+
all = ["pytest>=7.0"]
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.10,<0.14.0"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
pythonpath = [
|
|
29
|
+
"src",
|
|
30
|
+
".",
|
|
31
|
+
]
|
|
32
|
+
testpaths = ["tests"]
|
|
33
|
+
python_files = "test_*.py"
|
|
34
|
+
addopts = "-v"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "darwin-calendar"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Trading-calendar and date utilities for Darwin data tools"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Hong", email = "sardineclub@126.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"exchange-calendars>=4.13,<5",
|
|
12
|
+
"python-dateutil>=2.9",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
"Chinese Documentation" = "https://github.com/darwinalpha/darwin-calendar/blob/main/README.cn.md"
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
test = ["pytest>=7.0"]
|
|
20
|
+
all = ["pytest>=7.0"]
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["uv_build>=0.13.10,<0.14.0"]
|
|
24
|
+
build-backend = "uv_build"
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
pythonpath = ["src", "."]
|
|
28
|
+
testpaths = ["tests"]
|
|
29
|
+
python_files = "test_*.py"
|
|
30
|
+
addopts = "-v"
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""darwin-calendar: trading-day queries and date utilities.
|
|
2
|
+
|
|
3
|
+
Built on ``exchange_calendars`` 4.13+. No static calendar data is shipped:
|
|
4
|
+
modern library versions cover XSHG from 1990-12-03 onward.
|
|
5
|
+
|
|
6
|
+
基于 ``exchange_calendars`` 4.13+ 的交易日查询与日期工具。本库不分发静态
|
|
7
|
+
日历数据:新版库已覆盖 XSHG 自 1990-12-03 起的交易日。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .constants import (
|
|
11
|
+
CST,
|
|
12
|
+
DATES_LIST,
|
|
13
|
+
DATES_RANGE,
|
|
14
|
+
DATES_SINGLE,
|
|
15
|
+
DEFAULT_CUTOFF_HOURS,
|
|
16
|
+
DEFAULT_EXCHANGE,
|
|
17
|
+
EXCHANGE_MAP,
|
|
18
|
+
)
|
|
19
|
+
from .exceptions import CalendarError, UnknownExchangeError
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"CST",
|
|
25
|
+
"DATES_LIST",
|
|
26
|
+
"DATES_RANGE",
|
|
27
|
+
"DATES_SINGLE",
|
|
28
|
+
"DEFAULT_CUTOFF_HOURS",
|
|
29
|
+
"DEFAULT_EXCHANGE",
|
|
30
|
+
"EXCHANGE_MAP",
|
|
31
|
+
"CalendarError",
|
|
32
|
+
"UnknownExchangeError",
|
|
33
|
+
"__version__",
|
|
34
|
+
]
|
|
35
|
+
# Submodule symbols are re-exported below via explicit imports to keep the
|
|
36
|
+
# public surface discoverable without wildcard imports.
|
|
37
|
+
from .chunks import chunk_days_range, chunk_months_range # noqa: E402
|
|
38
|
+
from .core import ( # noqa: E402
|
|
39
|
+
get_calendar,
|
|
40
|
+
get_last_trading_day,
|
|
41
|
+
is_trading_day,
|
|
42
|
+
next_trading_day,
|
|
43
|
+
previous_trading_days,
|
|
44
|
+
trading_days_in_range,
|
|
45
|
+
)
|
|
46
|
+
from .format import ( # noqa: E402
|
|
47
|
+
compact_date,
|
|
48
|
+
date_to_millis_end,
|
|
49
|
+
date_to_millis_start,
|
|
50
|
+
normalize_date,
|
|
51
|
+
normalize_date_input,
|
|
52
|
+
parse_flexible_date,
|
|
53
|
+
)
|
|
54
|
+
from .ranges import ( # noqa: E402
|
|
55
|
+
get_trade_date,
|
|
56
|
+
parse_date_range_from_date,
|
|
57
|
+
parse_date_range_from_year,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
__all__ += [
|
|
61
|
+
"chunk_days_range",
|
|
62
|
+
"chunk_months_range",
|
|
63
|
+
"compact_date",
|
|
64
|
+
"date_to_millis_end",
|
|
65
|
+
"date_to_millis_start",
|
|
66
|
+
"get_calendar",
|
|
67
|
+
"get_last_trading_day",
|
|
68
|
+
"get_trade_date",
|
|
69
|
+
"is_trading_day",
|
|
70
|
+
"next_trading_day",
|
|
71
|
+
"normalize_date",
|
|
72
|
+
"normalize_date_input",
|
|
73
|
+
"parse_date_range_from_date",
|
|
74
|
+
"parse_date_range_from_year",
|
|
75
|
+
"parse_flexible_date",
|
|
76
|
+
"previous_trading_days",
|
|
77
|
+
"trading_days_in_range",
|
|
78
|
+
]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Date-range chunking helpers.
|
|
2
|
+
|
|
3
|
+
Chunk boundaries are calendar-independent: they split wall-clock ranges, not
|
|
4
|
+
trading sessions. Return shapes match the legacy helpers so a future migration
|
|
5
|
+
of ``darwin-fetch`` can replace imports without rewriting call sites.
|
|
6
|
+
|
|
7
|
+
日期区间切片辅助函数。切片边界与交易日历无关:切分的是自然日区间,而非交易日。
|
|
8
|
+
返回结构刻意保持与旧版一致,便于后续迁移 ``darwin-fetch`` 时直接替换导入。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from datetime import datetime, timedelta
|
|
12
|
+
from typing import List, Tuple
|
|
13
|
+
|
|
14
|
+
from dateutil.relativedelta import relativedelta
|
|
15
|
+
|
|
16
|
+
from .format import date_to_millis_end, date_to_millis_start, parse_flexible_date
|
|
17
|
+
|
|
18
|
+
__all__ = ["chunk_days_range", "chunk_months_range"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def chunk_days_range(
|
|
22
|
+
start_str: str,
|
|
23
|
+
end_str: str,
|
|
24
|
+
chunk_days: int,
|
|
25
|
+
) -> List[Tuple[str, str]]:
|
|
26
|
+
"""Split a range into fixed-width day chunks.
|
|
27
|
+
|
|
28
|
+
将日期区间按固定天数切片。
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
start_str: Inclusive start, ``YYYYMMDD`` or ``YYYY-MM-DD``.
|
|
32
|
+
end_str: Inclusive end, same forms.
|
|
33
|
+
chunk_days: Days per chunk; must be positive.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
List of ``(start, end)`` pairs in ``YYYYMMDD`` form.
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
ValueError: If the range is inverted or ``chunk_days`` is not positive.
|
|
40
|
+
"""
|
|
41
|
+
if chunk_days < 1:
|
|
42
|
+
raise ValueError(f"chunk_days 必须为正整数: {chunk_days}")
|
|
43
|
+
|
|
44
|
+
start = parse_flexible_date(start_str)
|
|
45
|
+
end = parse_flexible_date(end_str)
|
|
46
|
+
if start > end:
|
|
47
|
+
raise ValueError(f"start_date ({start_str}) 晚于 end_date ({end_str})")
|
|
48
|
+
|
|
49
|
+
chunks: List[Tuple[str, str]] = []
|
|
50
|
+
current = start
|
|
51
|
+
while current <= end:
|
|
52
|
+
chunk_end = min(current + timedelta(days=chunk_days - 1), end)
|
|
53
|
+
chunks.append(
|
|
54
|
+
(current.strftime("%Y%m%d"), chunk_end.strftime("%Y%m%d"))
|
|
55
|
+
)
|
|
56
|
+
current = chunk_end + timedelta(days=1)
|
|
57
|
+
return chunks
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def chunk_months_range(
|
|
61
|
+
start_str: str,
|
|
62
|
+
end_str: str,
|
|
63
|
+
chunk_months: int,
|
|
64
|
+
) -> List[Tuple[str, str, int, int]]:
|
|
65
|
+
"""Split a range into month-aligned chunks with millisecond bounds.
|
|
66
|
+
|
|
67
|
+
将日期区间按自然月/月数切片,并附带毫秒时间戳边界。
|
|
68
|
+
|
|
69
|
+
``chunk_months == 12`` aligns chunks to calendar years; other values
|
|
70
|
+
advance in fixed month steps from ``start``. This matches the legacy
|
|
71
|
+
``darwin-fetch`` contract so imports can be swapped without behaviour
|
|
72
|
+
changes.
|
|
73
|
+
12 表示按自然年,其他值从起始日按固定月数推进。与旧版 ``darwin-fetch``
|
|
74
|
+
行为一致,便于后续迁移时直接替换导入。
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
start_str: Inclusive start, ``YYYYMMDD`` or ``YYYY-MM-DD``.
|
|
78
|
+
end_str: Inclusive end, same forms.
|
|
79
|
+
chunk_months: Months per chunk; must be positive.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
List of ``(start, end, start_ms, end_ms)`` tuples. Dates are
|
|
83
|
+
``YYYYMMDD``; millisecond bounds use UTC+8.
|
|
84
|
+
|
|
85
|
+
Raises:
|
|
86
|
+
ValueError: If the range is inverted or ``chunk_months`` is not positive.
|
|
87
|
+
"""
|
|
88
|
+
if chunk_months < 1:
|
|
89
|
+
raise ValueError(f"chunk_months 必须为正整数: {chunk_months}")
|
|
90
|
+
|
|
91
|
+
start = parse_flexible_date(start_str)
|
|
92
|
+
end = parse_flexible_date(end_str)
|
|
93
|
+
if start > end:
|
|
94
|
+
raise ValueError(f"start_date ({start_str}) 晚于 end_date ({end_str})")
|
|
95
|
+
|
|
96
|
+
if chunk_months == 12:
|
|
97
|
+
boundaries = _year_boundaries(start, end)
|
|
98
|
+
else:
|
|
99
|
+
boundaries = _n_month_boundaries(start, end, chunk_months)
|
|
100
|
+
|
|
101
|
+
return [_make_chunk(begin, finish) for begin, finish in boundaries]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _year_boundaries(
|
|
105
|
+
start: datetime, end: datetime
|
|
106
|
+
) -> List[Tuple[datetime, datetime]]:
|
|
107
|
+
"""Yield calendar-year aligned ``(start, end)`` pairs."""
|
|
108
|
+
result: List[Tuple[datetime, datetime]] = []
|
|
109
|
+
current = start
|
|
110
|
+
while current <= end:
|
|
111
|
+
year_end = datetime(current.year, 12, 31)
|
|
112
|
+
chunk_end = min(year_end, end)
|
|
113
|
+
result.append((current, chunk_end))
|
|
114
|
+
current = chunk_end + timedelta(days=1)
|
|
115
|
+
return result
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _n_month_boundaries(
|
|
119
|
+
start: datetime, end: datetime, months: int
|
|
120
|
+
) -> List[Tuple[datetime, datetime]]:
|
|
121
|
+
"""Yield fixed month-step ``(start, end)`` pairs anchored at ``start``."""
|
|
122
|
+
result: List[Tuple[datetime, datetime]] = []
|
|
123
|
+
current = start
|
|
124
|
+
while current <= end:
|
|
125
|
+
chunk_end = current + relativedelta(months=months) - timedelta(days=1)
|
|
126
|
+
chunk_end = min(chunk_end, end)
|
|
127
|
+
result.append((current, chunk_end))
|
|
128
|
+
current = chunk_end + timedelta(days=1)
|
|
129
|
+
return result
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _make_chunk(start: datetime, end: datetime) -> Tuple[str, str, int, int]:
|
|
133
|
+
"""Build one chunk tuple with compact dates and UTC+8 millisecond bounds."""
|
|
134
|
+
start_s = start.strftime("%Y%m%d")
|
|
135
|
+
end_s = end.strftime("%Y%m%d")
|
|
136
|
+
return (
|
|
137
|
+
start_s,
|
|
138
|
+
end_s,
|
|
139
|
+
date_to_millis_start(start_s),
|
|
140
|
+
date_to_millis_end(end_s),
|
|
141
|
+
)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Shared constants: timezone, exchange mapping and date-parameter groups.
|
|
2
|
+
|
|
3
|
+
Exchange names map the short labels used across Darwin projects to the official
|
|
4
|
+
``exchange_calendars`` names. Several labels share one calendar on purpose
|
|
5
|
+
(SSE/SZSE trade the same sessions; NASDAQ/NYSE/AMEX likewise), so callers can
|
|
6
|
+
keep using domain-level labels without knowing the library's naming scheme.
|
|
7
|
+
|
|
8
|
+
共享常量:时区、交易所映射与日期参数分组。交易所短名映射到
|
|
9
|
+
``exchange_calendars`` 的官方名称;多个标签刻意共用同一日历(沪深交易日一致,
|
|
10
|
+
美股三家交易所一致),调用方因此可以继续使用业务层标签。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from datetime import timedelta, timezone
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"CALENDAR_START",
|
|
17
|
+
"CST",
|
|
18
|
+
"DATES_LIST",
|
|
19
|
+
"DATES_RANGE",
|
|
20
|
+
"DATES_SINGLE",
|
|
21
|
+
"DEFAULT_CUTOFF_HOURS",
|
|
22
|
+
"DEFAULT_EXCHANGE",
|
|
23
|
+
"EXCHANGE_MAP",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
#: China Standard Time (UTC+8), used for compact-date millisecond boundaries.
|
|
27
|
+
CST = timezone(timedelta(hours=8))
|
|
28
|
+
|
|
29
|
+
#: Default label passed to calendar APIs.
|
|
30
|
+
DEFAULT_EXCHANGE = "SSE"
|
|
31
|
+
|
|
32
|
+
#: Hours after the session close at which today's data is considered ready.
|
|
33
|
+
#: A policy value, kept here so callers can override it explicitly.
|
|
34
|
+
DEFAULT_CUTOFF_HOURS = 3.0
|
|
35
|
+
|
|
36
|
+
#: Domain label -> exchange_calendars calendar name.
|
|
37
|
+
EXCHANGE_MAP = {
|
|
38
|
+
"SSE": "XSHG",
|
|
39
|
+
"SZSE": "XSHG",
|
|
40
|
+
"HKEX": "XHKG",
|
|
41
|
+
"NASDAQ": "XNYS",
|
|
42
|
+
"NYSE": "XNYS",
|
|
43
|
+
"AMEX": "XNYS",
|
|
44
|
+
"TSE": "XTKS",
|
|
45
|
+
"KRX": "XKRX",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
#: Earliest start accepted by each calendar. ``exchange_calendars`` defaults to
|
|
49
|
+
#: 2006-11-29, which would silently drop the pre-2006 history the legacy CSV
|
|
50
|
+
#: used to provide. Requesting the earliest supported start avoids that; XTKS
|
|
51
|
+
#: is the sole exception with a 1997 floor.
|
|
52
|
+
#: 各日历支持的最早起始日。exchange_calendars 默认从 2006-11-29 开始,会静默
|
|
53
|
+
#: 丢弃旧版 CSV 覆盖的历史区间;显式请求最早可用起始日可避免该问题(XTKS 最早 1997)。
|
|
54
|
+
CALENDAR_START = {
|
|
55
|
+
"XSHG": "1990-12-19",
|
|
56
|
+
"XHKG": "1990-12-19",
|
|
57
|
+
"XNYS": "1990-12-19",
|
|
58
|
+
"XTKS": "1997-01-01",
|
|
59
|
+
"XKRX": "1990-12-19",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
#: Date parameters consumed by the legacy template renderer.
|
|
63
|
+
DATES_SINGLE = ["date", "year", "month"]
|
|
64
|
+
DATES_RANGE = ["start_date", "end_date"]
|
|
65
|
+
DATES_LIST = DATES_SINGLE + DATES_RANGE
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Trading-day queries backed by ``exchange_calendars``.
|
|
2
|
+
|
|
3
|
+
The library never ships a static calendar file. Modern ``exchange_calendars``
|
|
4
|
+
(4.13+) covers XSHG from 1990-12-03 onward, which supersedes the legacy CSV
|
|
5
|
+
fallback that existed only for older library versions.
|
|
6
|
+
|
|
7
|
+
基于 ``exchange_calendars`` 的交易日查询。本库不分发静态日历文件:新版
|
|
8
|
+
``exchange_calendars``(4.13+)的 XSHG 从 1990-12-03 起覆盖,已取代旧版
|
|
9
|
+
仅为老库版本准备的 CSV 回退。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
import pandas as pd
|
|
16
|
+
from exchange_calendars import ExchangeCalendar, get_calendar as _xcals_get_calendar
|
|
17
|
+
|
|
18
|
+
from .constants import (
|
|
19
|
+
CALENDAR_START,
|
|
20
|
+
CST,
|
|
21
|
+
DEFAULT_CUTOFF_HOURS,
|
|
22
|
+
DEFAULT_EXCHANGE,
|
|
23
|
+
EXCHANGE_MAP,
|
|
24
|
+
)
|
|
25
|
+
from .exceptions import UnknownExchangeError
|
|
26
|
+
from .format import compact_date, normalize_date
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"get_calendar",
|
|
30
|
+
"get_last_trading_day",
|
|
31
|
+
"is_trading_day",
|
|
32
|
+
"next_trading_day",
|
|
33
|
+
"previous_trading_days",
|
|
34
|
+
"trading_days_in_range",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
# Cache by domain label; ``exchange_calendars`` caches by official name, but
|
|
38
|
+
# mapping several labels to one official name still needs one stable handle.
|
|
39
|
+
_CALENDAR_CACHE: Dict[str, ExchangeCalendar] = {}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_calendar(exchange: str = DEFAULT_EXCHANGE) -> ExchangeCalendar:
|
|
43
|
+
"""Return a cached ``ExchangeCalendar`` for a Darwin exchange label.
|
|
44
|
+
|
|
45
|
+
返回 Darwin 交易所标签对应的缓存 ``ExchangeCalendar`` 对象。
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
exchange: One of :data:`~darwin_calendar.constants.EXCHANGE_MAP`.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
The calendar instance, cached for the lifetime of the process.
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
UnknownExchangeError: If the label is not registered.
|
|
55
|
+
"""
|
|
56
|
+
label = exchange.upper()
|
|
57
|
+
if label in _CALENDAR_CACHE:
|
|
58
|
+
return _CALENDAR_CACHE[label]
|
|
59
|
+
|
|
60
|
+
name = EXCHANGE_MAP.get(label)
|
|
61
|
+
if name is None:
|
|
62
|
+
raise UnknownExchangeError(exchange, EXCHANGE_MAP)
|
|
63
|
+
|
|
64
|
+
# Pass an explicit start: the library default (2006-11-29) would drop the
|
|
65
|
+
# pre-2006 sessions that the legacy static CSV used to supply.
|
|
66
|
+
calendar = _xcals_get_calendar(name, start=CALENDAR_START[name])
|
|
67
|
+
_CALENDAR_CACHE[label] = calendar
|
|
68
|
+
return calendar
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _session_to_compact(session: Any) -> str:
|
|
72
|
+
"""Convert a pandas session timestamp to ``YYYYMMDD``."""
|
|
73
|
+
return pd.Timestamp(session).strftime("%Y%m%d")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_trading_day(date: str, exchange: str = DEFAULT_EXCHANGE) -> bool:
|
|
77
|
+
"""Check whether a date is a trading session.
|
|
78
|
+
|
|
79
|
+
判断某日是否为交易日。
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
date: ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
83
|
+
exchange: Exchange label, defaults to ``SSE``.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
``True`` if the date is a session of that exchange.
|
|
87
|
+
"""
|
|
88
|
+
calendar = get_calendar(exchange)
|
|
89
|
+
return bool(calendar.is_session(normalize_date(date)))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def previous_trading_days(
|
|
93
|
+
date: str,
|
|
94
|
+
n: int = 1,
|
|
95
|
+
exchange: str = DEFAULT_EXCHANGE,
|
|
96
|
+
) -> List[str]:
|
|
97
|
+
"""Return the ``n`` sessions strictly before ``date``, newest first.
|
|
98
|
+
|
|
99
|
+
返回 ``date`` 之前(不含当日)的 ``n`` 个交易日,最近的在前。
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
date: Reference date, ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
103
|
+
n: Number of sessions to return.
|
|
104
|
+
exchange: Exchange label, defaults to ``SSE``.
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
Compact ``YYYYMMDD`` strings. The list is shorter than ``n`` when the
|
|
108
|
+
calendar does not have enough prior sessions.
|
|
109
|
+
|
|
110
|
+
Raises:
|
|
111
|
+
ValueError: If ``n`` is negative.
|
|
112
|
+
"""
|
|
113
|
+
if n < 0:
|
|
114
|
+
raise ValueError(f"n 必须非负: {n}")
|
|
115
|
+
if n == 0:
|
|
116
|
+
return []
|
|
117
|
+
|
|
118
|
+
calendar = get_calendar(exchange)
|
|
119
|
+
day = pd.Timestamp(normalize_date(date))
|
|
120
|
+
|
|
121
|
+
# ``date_to_session(previous)`` returns the day itself when it is a
|
|
122
|
+
# session. A left insertion point gives an exact "strictly before" bound
|
|
123
|
+
# for both session and non-session reference dates.
|
|
124
|
+
index = int(calendar.sessions.searchsorted(day, side="left"))
|
|
125
|
+
start = max(0, index - n)
|
|
126
|
+
return [_session_to_compact(s) for s in calendar.sessions[start:index][::-1]]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def trading_days_in_range(
|
|
130
|
+
start: str,
|
|
131
|
+
end: str,
|
|
132
|
+
exchange: str = DEFAULT_EXCHANGE,
|
|
133
|
+
) -> List[str]:
|
|
134
|
+
"""Return all sessions in ``[start, end]``, newest first.
|
|
135
|
+
|
|
136
|
+
返回 ``[start, end]`` 区间内的全部交易日,最近的在前。
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
start: Inclusive range start, ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
140
|
+
end: Inclusive range end, same forms.
|
|
141
|
+
exchange: Exchange label, defaults to ``SSE``.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
Compact ``YYYYMMDD`` strings in descending order.
|
|
145
|
+
"""
|
|
146
|
+
calendar = get_calendar(exchange)
|
|
147
|
+
first = pd.Timestamp(normalize_date(start))
|
|
148
|
+
last = pd.Timestamp(normalize_date(end))
|
|
149
|
+
|
|
150
|
+
if first > last:
|
|
151
|
+
return []
|
|
152
|
+
|
|
153
|
+
# Clamp to the calendar's covered range; ``sessions_in_range`` indexes into
|
|
154
|
+
# ``sessions`` and would otherwise return empty or raise for future dates.
|
|
155
|
+
first = max(first, calendar.first_session)
|
|
156
|
+
last = min(last, calendar.last_session)
|
|
157
|
+
if first > last:
|
|
158
|
+
return []
|
|
159
|
+
|
|
160
|
+
sessions = calendar.sessions_in_range(first, last)
|
|
161
|
+
return [_session_to_compact(s) for s in sessions[::-1]]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def next_trading_day(date: str, exchange: str = DEFAULT_EXCHANGE) -> str:
|
|
165
|
+
"""Return the first session strictly after ``date``.
|
|
166
|
+
|
|
167
|
+
返回 ``date`` 之后(不含当日)的第一个交易日。
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
date: Reference date, ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
171
|
+
exchange: Exchange label, defaults to ``SSE``.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
Compact ``YYYYMMDD`` string.
|
|
175
|
+
|
|
176
|
+
Raises:
|
|
177
|
+
ValueError: If the date is at or beyond the calendar's last session.
|
|
178
|
+
"""
|
|
179
|
+
calendar = get_calendar(exchange)
|
|
180
|
+
day = pd.Timestamp(normalize_date(date))
|
|
181
|
+
# A right insertion point skips the reference day even when it is a
|
|
182
|
+
# session, matching the "strictly after" contract.
|
|
183
|
+
index = int(calendar.sessions.searchsorted(day, side="right"))
|
|
184
|
+
if index >= len(calendar.sessions):
|
|
185
|
+
raise ValueError(f"日期超出日历范围: {date}")
|
|
186
|
+
return _session_to_compact(calendar.sessions[index])
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def get_last_trading_day(
|
|
190
|
+
exchange: str = DEFAULT_EXCHANGE,
|
|
191
|
+
cutoff_hours: float = DEFAULT_CUTOFF_HOURS,
|
|
192
|
+
now: Optional[datetime] = None,
|
|
193
|
+
) -> str:
|
|
194
|
+
"""Return the latest session whose data is considered available.
|
|
195
|
+
|
|
196
|
+
返回当前时刻下数据可用的最近交易日。
|
|
197
|
+
|
|
198
|
+
A session counts as available only after its close plus ``cutoff_hours``;
|
|
199
|
+
before that boundary the previous session is returned. This is a data
|
|
200
|
+
readiness policy, exposed as a parameter rather than hard-coded so callers
|
|
201
|
+
can choose a different threshold.
|
|
202
|
+
|
|
203
|
+
只有当交易日收盘时间加上 ``cutoff_hours`` 之后,当日数据才算可用;
|
|
204
|
+
在此之前返回上一个交易日。这是数据就绪策略,作为参数暴露而非硬编码,
|
|
205
|
+
调用方可自行选择阈值。
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
exchange: Exchange label, defaults to ``SSE``.
|
|
209
|
+
cutoff_hours: Hours after session close before data is deemed ready.
|
|
210
|
+
now: Injectable reference time for deterministic tests. Naive values
|
|
211
|
+
are interpreted in UTC+8; timezone-aware values are converted to
|
|
212
|
+
UTC+8 for the local-date decision.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
Date string in ``YYYY-MM-DD`` form.
|
|
216
|
+
"""
|
|
217
|
+
calendar = get_calendar(exchange)
|
|
218
|
+
|
|
219
|
+
reference = pd.Timestamp.now(tz="UTC") if now is None else pd.Timestamp(now)
|
|
220
|
+
if reference.tzinfo is None:
|
|
221
|
+
reference = reference.tz_localize(CST)
|
|
222
|
+
reference = reference.tz_convert(CST)
|
|
223
|
+
local_date = reference.strftime("%Y-%m-%d")
|
|
224
|
+
day = pd.Timestamp(local_date)
|
|
225
|
+
|
|
226
|
+
if day < calendar.first_session:
|
|
227
|
+
raise ValueError(f"日期超出日历范围: {local_date}")
|
|
228
|
+
|
|
229
|
+
if day > calendar.last_session:
|
|
230
|
+
day = calendar.last_session
|
|
231
|
+
|
|
232
|
+
if calendar.is_session(day):
|
|
233
|
+
close = pd.Timestamp(calendar.session_close(day)).tz_convert(CST)
|
|
234
|
+
if reference >= close + pd.Timedelta(hours=cutoff_hours):
|
|
235
|
+
return local_date
|
|
236
|
+
session = calendar.previous_session(day)
|
|
237
|
+
else:
|
|
238
|
+
session = calendar.date_to_session(day, direction="previous")
|
|
239
|
+
|
|
240
|
+
return pd.Timestamp(session).strftime("%Y-%m-%d")
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Typed exceptions raised by this library.
|
|
2
|
+
|
|
3
|
+
Exceptions carry enough context for callers to log and act on them without
|
|
4
|
+
parsing messages. They subclass ``ValueError`` where the legacy code did, so
|
|
5
|
+
existing ``except ValueError`` handlers keep working after migration.
|
|
6
|
+
|
|
7
|
+
本库的类型化异常。异常携带足够上下文,调用方无需解析消息即可记录和处理。
|
|
8
|
+
在旧代码使用 ``ValueError`` 的地方保持继承关系,使迁移后的
|
|
9
|
+
``except ValueError`` 处理器继续有效。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
__all__ = ["CalendarError", "UnknownExchangeError"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CalendarError(ValueError):
|
|
18
|
+
"""Base error for this library."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UnknownExchangeError(CalendarError):
|
|
22
|
+
"""Raised when an exchange label has no registered calendar.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
exchange: The label that was requested.
|
|
26
|
+
supported: Sorted list of accepted labels, for actionable error messages.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, exchange: str, supported: Any) -> None:
|
|
30
|
+
self.exchange = exchange
|
|
31
|
+
self.supported = sorted(supported)
|
|
32
|
+
super().__init__(
|
|
33
|
+
f"未知交易所: {exchange},支持: {', '.join(self.supported)}"
|
|
34
|
+
)
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Date parsing, formatting and millisecond conversion (pure functions).
|
|
2
|
+
|
|
3
|
+
These helpers have no calendar dependency. They are intentionally separate from
|
|
4
|
+
``core.py`` so callers that only need string normalization do not pay for
|
|
5
|
+
``exchange_calendars`` import time.
|
|
6
|
+
|
|
7
|
+
日期解析、格式化与毫秒时间戳转换(纯函数)。这些辅助函数不依赖交易日历,
|
|
8
|
+
刻意与 ``core.py`` 分离,使只需要字符串规范化的调用方无需承担
|
|
9
|
+
``exchange_calendars`` 的导入开销。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from typing import Optional, Tuple
|
|
14
|
+
|
|
15
|
+
from .constants import CST
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"compact_date",
|
|
19
|
+
"date_to_millis_end",
|
|
20
|
+
"date_to_millis_start",
|
|
21
|
+
"normalize_date",
|
|
22
|
+
"normalize_date_input",
|
|
23
|
+
"parse_flexible_date",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def normalize_date(date_str: str) -> str:
|
|
28
|
+
"""Normalize a date string to ``YYYY-MM-DD``.
|
|
29
|
+
|
|
30
|
+
Accepted forms are ``YYYY-MM-DD`` and ``YYYYMMDD``. Whitespace is stripped;
|
|
31
|
+
anything else raises ``ValueError`` rather than being silently passed
|
|
32
|
+
through, so invalid input cannot reach a calendar lookup.
|
|
33
|
+
|
|
34
|
+
将日期字符串规范化为 ``YYYY-MM-DD``。接受 ``YYYY-MM-DD`` 与 ``YYYYMMDD``
|
|
35
|
+
两种形式。去除首尾空白;其他形式直接抛出 ``ValueError``,避免无效输入
|
|
36
|
+
静默流入日历查询。
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
date_str: Date string in one of the two accepted forms.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Date string in ``YYYY-MM-DD`` form.
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
ValueError: If the input is empty or in an unsupported form.
|
|
46
|
+
"""
|
|
47
|
+
if not date_str:
|
|
48
|
+
raise ValueError("日期字符串为空")
|
|
49
|
+
|
|
50
|
+
value = str(date_str).strip()
|
|
51
|
+
|
|
52
|
+
if len(value) == 10 and value[4] == "-" and value[7] == "-":
|
|
53
|
+
normalized = value
|
|
54
|
+
elif len(value) == 8 and value.isdigit():
|
|
55
|
+
normalized = f"{value[:4]}-{value[4:6]}-{value[6:8]}"
|
|
56
|
+
else:
|
|
57
|
+
raise ValueError(f"无法解析日期: {date_str}")
|
|
58
|
+
|
|
59
|
+
# Reject impossible dates such as 2026-13-45 instead of letting them
|
|
60
|
+
# surface later as an opaque pandas parse error.
|
|
61
|
+
try:
|
|
62
|
+
datetime.strptime(normalized, "%Y-%m-%d")
|
|
63
|
+
except ValueError:
|
|
64
|
+
raise ValueError(f"无法解析日期: {date_str}") from None
|
|
65
|
+
return normalized
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def compact_date(date_str: str) -> str:
|
|
69
|
+
"""Convert a date string to ``YYYYMMDD``.
|
|
70
|
+
|
|
71
|
+
将日期字符串转换为 ``YYYYMMDD``。
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
date_str: ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
Compact ``YYYYMMDD`` form.
|
|
78
|
+
"""
|
|
79
|
+
return normalize_date(date_str).replace("-", "")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def parse_flexible_date(value: str) -> datetime:
|
|
83
|
+
"""Parse ``YYYYMMDD`` or ``YYYY-MM-DD`` into a naive ``datetime``.
|
|
84
|
+
|
|
85
|
+
解析 ``YYYYMMDD`` 或 ``YYYY-MM-DD`` 为无时区的 ``datetime``。
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
value: Date string in either accepted form.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Naive ``datetime`` at midnight.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
ValueError: If the input cannot be parsed.
|
|
95
|
+
"""
|
|
96
|
+
text = str(value).strip().replace("-", "")
|
|
97
|
+
if len(text) != 8 or not text.isdigit():
|
|
98
|
+
raise ValueError(f"无法解析日期: {value}")
|
|
99
|
+
return datetime.strptime(text, "%Y%m%d")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def date_to_millis_start(date_c: str) -> int:
|
|
103
|
+
"""Return the UTC+8 millisecond timestamp at 00:00:00.000 of a day.
|
|
104
|
+
|
|
105
|
+
返回某日(UTC+8)00:00:00.000 的毫秒时间戳。
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
date_c: ``YYYYMMDD`` or ``YYYY-MM-DD``.
|
|
109
|
+
"""
|
|
110
|
+
day = compact_date(date_c)
|
|
111
|
+
dt = datetime.strptime(day, "%Y%m%d").replace(tzinfo=CST)
|
|
112
|
+
return int(dt.timestamp() * 1000)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def date_to_millis_end(date_c: str) -> int:
|
|
116
|
+
"""Return the UTC+8 millisecond timestamp at 23:59:59.999 of a day.
|
|
117
|
+
|
|
118
|
+
返回某日(UTC+8)23:59:59.999 的毫秒时间戳。
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
date_c: ``YYYYMMDD`` or ``YYYY-MM-DD``.
|
|
122
|
+
"""
|
|
123
|
+
day = compact_date(date_c)
|
|
124
|
+
dt = datetime.strptime(day, "%Y%m%d").replace(
|
|
125
|
+
hour=23, minute=59, second=59, microsecond=999000, tzinfo=CST
|
|
126
|
+
)
|
|
127
|
+
return int(dt.timestamp() * 1000)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def normalize_date_input(
|
|
131
|
+
start_date: Optional[str] = None,
|
|
132
|
+
end_date: Optional[str] = None,
|
|
133
|
+
since_ts_millis: Optional[int] = None,
|
|
134
|
+
until_ts_millis: Optional[int] = None,
|
|
135
|
+
) -> Tuple[str, str]:
|
|
136
|
+
"""Resolve a date range from either strings or millisecond timestamps.
|
|
137
|
+
|
|
138
|
+
String inputs take precedence. Timestamp inputs are interpreted in UTC+8,
|
|
139
|
+
matching ``date_to_millis_start`` / ``date_to_millis_end``.
|
|
140
|
+
|
|
141
|
+
从字符串或毫秒时间戳中解析日期区间。字符串输入优先;时间戳按 UTC+8
|
|
142
|
+
解释,与 ``date_to_millis_start`` / ``date_to_millis_end`` 保持一致。
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
start_date: Range start, ``YYYYMMDD`` or ``YYYY-MM-DD``.
|
|
146
|
+
end_date: Range end, same forms.
|
|
147
|
+
since_ts_millis: Start timestamp in milliseconds (UTC+8).
|
|
148
|
+
until_ts_millis: End timestamp in milliseconds (UTC+8).
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
``(start, end)`` pair in ``YYYYMMDD`` form.
|
|
152
|
+
|
|
153
|
+
Raises:
|
|
154
|
+
ValueError: If neither a complete string pair nor a full timestamp
|
|
155
|
+
pair is supplied.
|
|
156
|
+
"""
|
|
157
|
+
if start_date and end_date:
|
|
158
|
+
return compact_date(start_date), compact_date(end_date)
|
|
159
|
+
|
|
160
|
+
if since_ts_millis is not None and until_ts_millis is not None:
|
|
161
|
+
start_dt = datetime.fromtimestamp(int(since_ts_millis) / 1000, CST)
|
|
162
|
+
end_dt = datetime.fromtimestamp(int(until_ts_millis) / 1000, CST)
|
|
163
|
+
return start_dt.strftime("%Y%m%d"), end_dt.strftime("%Y%m%d")
|
|
164
|
+
|
|
165
|
+
raise ValueError(
|
|
166
|
+
"无法归一化日期: "
|
|
167
|
+
f"start_date={start_date}, end_date={end_date}, "
|
|
168
|
+
f"since_ts_millis={since_ts_millis}, until_ts_millis={until_ts_millis}"
|
|
169
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Date-range expansion helpers.
|
|
2
|
+
|
|
3
|
+
These functions combine pure date parsing with the trading-day policy from
|
|
4
|
+
``core.py``. They are kept in a separate module so the low-level helpers remain
|
|
5
|
+
usable without pulling in calendar logic.
|
|
6
|
+
|
|
7
|
+
日期区间展开辅助函数。这些函数把纯日期解析与 ``core.py`` 的交易日策略组合起来。
|
|
8
|
+
单独成模块,使底层辅助函数在不引入日历逻辑的情况下仍可使用。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import Optional, Tuple
|
|
13
|
+
|
|
14
|
+
from .constants import CST
|
|
15
|
+
from .core import get_last_trading_day
|
|
16
|
+
from .format import normalize_date
|
|
17
|
+
|
|
18
|
+
__all__ = ["get_trade_date", "parse_date_range_from_date", "parse_date_range_from_year"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_trade_date(date_str: Optional[str] = None) -> str:
|
|
22
|
+
"""Return a user-supplied date or the latest available trading day.
|
|
23
|
+
|
|
24
|
+
返回用户指定的日期,或最近一个数据可用的交易日。
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
date_str: Optional date, ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
Date string in ``YYYY-MM-DD`` form.
|
|
31
|
+
"""
|
|
32
|
+
if date_str is not None:
|
|
33
|
+
return normalize_date(date_str)
|
|
34
|
+
return get_last_trading_day()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_date_range_from_date(date_str: str) -> Tuple[str, str]:
|
|
38
|
+
"""Expand a single date into a one-day range.
|
|
39
|
+
|
|
40
|
+
将单日日期展开为起止相同的区间。
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
date_str: ``YYYY-MM-DD`` or ``YYYYMMDD``.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
``(start, end)`` pair in ``YYYY-MM-DD`` form.
|
|
47
|
+
"""
|
|
48
|
+
day = normalize_date(date_str)
|
|
49
|
+
return day, day
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_date_range_from_year(year: str) -> Tuple[str, str]:
|
|
53
|
+
"""Expand a year into a date range, capped at the latest trading day.
|
|
54
|
+
|
|
55
|
+
将年份展开为日期区间;未来或当年区间的结束日截断到最近交易日。
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
year: Four-digit year string.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
``(start, end)`` pair in ``YYYY-MM-DD`` form.
|
|
62
|
+
"""
|
|
63
|
+
start_date = f"{year}-01-01"
|
|
64
|
+
end_date = f"{year}-12-31"
|
|
65
|
+
|
|
66
|
+
# Clamp only when the year has not fully elapsed; historical years keep
|
|
67
|
+
# their literal Dec 31 boundary.
|
|
68
|
+
today = datetime.now(CST).date()
|
|
69
|
+
end_date_obj = datetime.strptime(end_date, "%Y-%m-%d").date()
|
|
70
|
+
if end_date_obj >= today:
|
|
71
|
+
end_date = get_last_trading_day()
|
|
72
|
+
|
|
73
|
+
return start_date, end_date
|