seeddata-quant 1.0.3__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.
- seeddata/README.md +129 -0
- seeddata/__init__.py +29 -0
- seeddata/base_url_config.py +124 -0
- seeddata/calendars/__init__.py +13 -0
- seeddata/calendars/cn_futures.py +111 -0
- seeddata/calendars/data/__init__.py +1 -0
- seeddata/calendars/data/cn_futures_trade_date.parquet +0 -0
- seeddata/calendars/pmc_calendar.py +66 -0
- seeddata/calendars/registry.py +48 -0
- seeddata/calendars/us_equities.py +83 -0
- seeddata/calendars/valid_day_mixin.py +51 -0
- seeddata/client.py +639 -0
- seeddata/errors.py +10 -0
- seeddata_quant-1.0.3.dist-info/METADATA +153 -0
- seeddata_quant-1.0.3.dist-info/RECORD +17 -0
- seeddata_quant-1.0.3.dist-info/WHEEL +5 -0
- seeddata_quant-1.0.3.dist-info/top_level.txt +1 -0
seeddata/README.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# SeedData Python SDK
|
|
2
|
+
|
|
3
|
+
SeedData is a Python client SDK for accessing SeedData market data services.
|
|
4
|
+
|
|
5
|
+
This package only contains the client SDK. The server-side gateway and worker components are not included in this PyPI distribution.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install seeddata-quant
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import seeddata as sd
|
|
17
|
+
|
|
18
|
+
sd.set_token("YOUR_TOKEN")
|
|
19
|
+
|
|
20
|
+
result = sd.query("SELECT * FROM trade_date LIMIT 5")
|
|
21
|
+
print(result.df)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Common APIs
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import seeddata as sd
|
|
28
|
+
|
|
29
|
+
sd.set_token("YOUR_TOKEN")
|
|
30
|
+
|
|
31
|
+
df = sd.get_klines(
|
|
32
|
+
instruments=["000001.SZ"],
|
|
33
|
+
fields=["close"],
|
|
34
|
+
start_time="2024-01-01",
|
|
35
|
+
end_time="2024-01-31",
|
|
36
|
+
period="1d",
|
|
37
|
+
adjust="none",
|
|
38
|
+
market_type="cn_stock",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
realtime_1min = sd.query(
|
|
42
|
+
"SELECT * FROM cn_stock_1min_realtime_data "
|
|
43
|
+
"LATEST ON trade_time PARTITION BY ts_code LIMIT 20"
|
|
44
|
+
).df
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Trading Calendars
|
|
48
|
+
|
|
49
|
+
`seeddata.calendars` provides trading-calendar helpers. It is pure client-side
|
|
50
|
+
(no network calls): it reuses `pandas_market_calendars` for A-share / HK / US
|
|
51
|
+
equities and ships a packaged parquet for China futures.
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import seeddata.calendars as cal
|
|
55
|
+
|
|
56
|
+
cal.get_calendar_names() # supported MIC names
|
|
57
|
+
c = cal.get_calendar("XNYS") # NYSE-listed ordinary equities
|
|
58
|
+
|
|
59
|
+
c.valid_days("2026-06-01", "2026-06-30") # trading days in range
|
|
60
|
+
c.is_valid_day("2026-06-19") # False (Juneteenth)
|
|
61
|
+
c.date_to_valid_day("2026-06-06", direction="next") # next trading day
|
|
62
|
+
c.valid_days_window("2026-06-02", 5) # 5 trading days forward
|
|
63
|
+
|
|
64
|
+
c.schedule("2026-11-27") # regular session, 09:30-13:00 ET
|
|
65
|
+
c.schedule("2026-11-27", session="extended") # pre/open/close/post
|
|
66
|
+
c.schedule("2026-06-01", session="extended", tz="Asia/Shanghai")
|
|
67
|
+
c.early_closes("2026-01-01", "2026-12-31")
|
|
68
|
+
c.is_open_at("2026-06-01 22:00:00+08:00", session="regular")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Supported MICs: `CCFX GFEX XDCE XHKG XINE XNAS XNYS XSGE XSHE XSHG XZCE CN_FUTURES`.
|
|
72
|
+
China futures (`CCFX/XDCE/XZCE/XSGE/XINE/GFEX`) and `CN_FUTURES` (their union)
|
|
73
|
+
are backed by packaged data. A-share / HK / US calendars use
|
|
74
|
+
`pandas_market_calendars`; `XNYS` and `XNAS` map to its `NYSE` and `NASDAQ`
|
|
75
|
+
ordinary-equity rules. Names are ISO 10383 MIC only. Returns default to each
|
|
76
|
+
market's local timezone. US calendars additionally provide regular/extended
|
|
77
|
+
`schedule()`, `early_closes()`, `late_opens()`, and `is_open_at()`; China-futures
|
|
78
|
+
`schedule()` raises `NotImplementedError`.
|
|
79
|
+
|
|
80
|
+
## Token
|
|
81
|
+
|
|
82
|
+
Public SeedData gateways require a token:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
sd.set_token("YOUR_TOKEN")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
You can also set the token through an environment variable:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
export SEEDDATA_TOKEN="YOUR_TOKEN"
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Private deployments may allow anonymous local access. In that case the SDK can
|
|
95
|
+
send requests without `sd.set_token(...)`; the server decides whether anonymous
|
|
96
|
+
requests are allowed.
|
|
97
|
+
|
|
98
|
+
## Base URL
|
|
99
|
+
|
|
100
|
+
By default, the SDK configures only the public history gateway:
|
|
101
|
+
|
|
102
|
+
- history: `https://history.seeddata.cn`
|
|
103
|
+
- realtime: not configured until the public realtime service is deployed
|
|
104
|
+
|
|
105
|
+
Realtime calls fail locally with a configuration error until an address is set explicitly.
|
|
106
|
+
|
|
107
|
+
For local development or private deployments, configure the gateways in code:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
sd.set_base_url(
|
|
111
|
+
history="http://127.0.0.1:28637",
|
|
112
|
+
realtime="http://127.0.0.1:28637",
|
|
113
|
+
)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
You can set only one side if needed:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
sd.set_base_url(history="http://127.0.0.1:28637")
|
|
120
|
+
sd.set_base_url(realtime="http://127.0.0.1:28637")
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Missing arguments keep their current values. Trailing slashes are removed, and
|
|
124
|
+
empty values raise an error. This function only configures request URLs and does
|
|
125
|
+
not check network connectivity.
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
This package is proprietary software. Installation and use require authorization from SeedData.
|
seeddata/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from .client import (
|
|
2
|
+
get_constituents,
|
|
3
|
+
get_klines,
|
|
4
|
+
get_snapshot,
|
|
5
|
+
QueryResult,
|
|
6
|
+
get_token_info,
|
|
7
|
+
query,
|
|
8
|
+
set_base_url,
|
|
9
|
+
set_token,
|
|
10
|
+
)
|
|
11
|
+
from .errors import (
|
|
12
|
+
SeedDataAuthError,
|
|
13
|
+
SeedDataError,
|
|
14
|
+
SeedDataQueryError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"QueryResult",
|
|
19
|
+
"SeedDataAuthError",
|
|
20
|
+
"SeedDataError",
|
|
21
|
+
"SeedDataQueryError",
|
|
22
|
+
"get_constituents",
|
|
23
|
+
"get_klines",
|
|
24
|
+
"get_snapshot",
|
|
25
|
+
"get_token_info",
|
|
26
|
+
"query",
|
|
27
|
+
"set_base_url",
|
|
28
|
+
"set_token",
|
|
29
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
DEFAULT_HISTORY_BASE_URL = "https://history.seeddata.cn"
|
|
4
|
+
DEFAULT_REALTIME_BASE_URL: str | None = None
|
|
5
|
+
|
|
6
|
+
HISTORY_BASE_URL = DEFAULT_HISTORY_BASE_URL
|
|
7
|
+
REALTIME_BASE_URL = DEFAULT_REALTIME_BASE_URL
|
|
8
|
+
DEFAULT_BASE_URL = HISTORY_BASE_URL
|
|
9
|
+
DEFAULT_DATABASE = "qdb"
|
|
10
|
+
|
|
11
|
+
# Endpoint-level route targets.
|
|
12
|
+
#
|
|
13
|
+
API_BASE_TARGETS: dict[str, str] = {
|
|
14
|
+
"query": "history",
|
|
15
|
+
"get_klines": "history",
|
|
16
|
+
"get_snapshot": "realtime",
|
|
17
|
+
"get_constituents": "history",
|
|
18
|
+
"get_token_info": "history",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
# Table-level query route targets. Keys are normalized table names.
|
|
22
|
+
|
|
23
|
+
TABLE_BASE_TARGETS: dict[str, str] = {
|
|
24
|
+
"cn_stock_1min_realtime_data": "realtime",
|
|
25
|
+
"cn_fund_1min_realtime_data": "realtime",
|
|
26
|
+
"cn_index_1min_realtime_data": "realtime",
|
|
27
|
+
"cn_sw_industry_realtime_data": "realtime",
|
|
28
|
+
"cn_stock_realtime_data": "realtime",
|
|
29
|
+
"cn_fund_realtime_data": "realtime",
|
|
30
|
+
"cn_index_realtime_data": "realtime",
|
|
31
|
+
"hk_stock_realtime_data": "realtime",
|
|
32
|
+
"cn_ths_concept_realtime_data": "realtime",
|
|
33
|
+
"cn_stock_opening_auction_tick_data": "realtime",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
REALTIME_1MIN_TABLE_BY_MARKET_TYPE: dict[str, str] = {
|
|
37
|
+
"cn_stock": "cn_stock_1min_realtime_data",
|
|
38
|
+
"cn_fund": "cn_fund_1min_realtime_data",
|
|
39
|
+
"cn_index": "cn_index_1min_realtime_data",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _normalize_base_url(base_url: str) -> str:
|
|
44
|
+
value = base_url.strip().rstrip("/")
|
|
45
|
+
if not value:
|
|
46
|
+
raise ValueError("base_url is empty")
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def canonicalize_table_name(table_name: str, default_db: str = DEFAULT_DATABASE) -> str:
|
|
51
|
+
raw = table_name.strip().strip("`").strip('"').lower()
|
|
52
|
+
if not raw:
|
|
53
|
+
raise ValueError("table name is empty")
|
|
54
|
+
|
|
55
|
+
parts = [part.strip().strip("`").strip('"').lower() for part in raw.split(".") if part.strip()]
|
|
56
|
+
if len(parts) == 1:
|
|
57
|
+
return parts[0]
|
|
58
|
+
raise ValueError(f"invalid table name: {table_name}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_current_history_base_url = _normalize_base_url(DEFAULT_HISTORY_BASE_URL)
|
|
62
|
+
_current_realtime_base_url = DEFAULT_REALTIME_BASE_URL
|
|
63
|
+
|
|
64
|
+
_UNSET = object()
|
|
65
|
+
|
|
66
|
+
_NORMALIZED_TABLE_BASE_TARGETS = {
|
|
67
|
+
canonicalize_table_name(table_name): target
|
|
68
|
+
for table_name, target in TABLE_BASE_TARGETS.items()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def set_base_url(
|
|
73
|
+
history: str | None | object = _UNSET,
|
|
74
|
+
realtime: str | None | object = _UNSET,
|
|
75
|
+
) -> None:
|
|
76
|
+
global _current_history_base_url
|
|
77
|
+
global _current_realtime_base_url
|
|
78
|
+
global HISTORY_BASE_URL
|
|
79
|
+
global REALTIME_BASE_URL
|
|
80
|
+
global DEFAULT_BASE_URL
|
|
81
|
+
|
|
82
|
+
normalized_history = _normalize_base_url(history) if isinstance(history, str) else None
|
|
83
|
+
normalized_realtime = _normalize_base_url(realtime) if isinstance(realtime, str) else None
|
|
84
|
+
|
|
85
|
+
if history is not _UNSET:
|
|
86
|
+
if history is None:
|
|
87
|
+
raise ValueError("history base URL cannot be cleared")
|
|
88
|
+
assert normalized_history is not None
|
|
89
|
+
_current_history_base_url = normalized_history
|
|
90
|
+
HISTORY_BASE_URL = _current_history_base_url
|
|
91
|
+
DEFAULT_BASE_URL = _current_history_base_url
|
|
92
|
+
if realtime is not _UNSET:
|
|
93
|
+
_current_realtime_base_url = normalized_realtime
|
|
94
|
+
REALTIME_BASE_URL = _current_realtime_base_url
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _get_base_url_by_target(target: str) -> str:
|
|
98
|
+
if target == "history":
|
|
99
|
+
return _current_history_base_url
|
|
100
|
+
if target == "realtime":
|
|
101
|
+
if _current_realtime_base_url is None:
|
|
102
|
+
raise ValueError("realtime base URL is not configured; call set_base_url(realtime=...)")
|
|
103
|
+
return _current_realtime_base_url
|
|
104
|
+
raise ValueError(f"unknown base_url target: {target}")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def get_api_base_url(api_name: str) -> str:
|
|
108
|
+
target = API_BASE_TARGETS.get(api_name, "history")
|
|
109
|
+
return _get_base_url_by_target(target)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def get_explicit_table_base_url(table_name: str) -> str | None:
|
|
113
|
+
target = _NORMALIZED_TABLE_BASE_TARGETS.get(canonicalize_table_name(table_name))
|
|
114
|
+
if target is None:
|
|
115
|
+
return None
|
|
116
|
+
return _get_base_url_by_target(target)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_realtime_1min_table(market_type: str) -> str:
|
|
120
|
+
normalized_market_type = str(market_type).strip().lower()
|
|
121
|
+
try:
|
|
122
|
+
return REALTIME_1MIN_TABLE_BY_MARKET_TYPE[normalized_market_type]
|
|
123
|
+
except KeyError as exc:
|
|
124
|
+
raise ValueError(f"invalid market_type for realtime 1min klines: {market_type}") from exc
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from importlib import resources
|
|
6
|
+
from typing import Any
|
|
7
|
+
from zoneinfo import ZoneInfo
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from pandas.tseries.offsets import CustomBusinessDay
|
|
11
|
+
|
|
12
|
+
from .valid_day_mixin import ValidDayMixin
|
|
13
|
+
|
|
14
|
+
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
|
15
|
+
CN_FUTURES_DATA_FILE = "cn_futures_trade_date.parquet"
|
|
16
|
+
WEEKMASK = "Mon Tue Wed Thu Fri"
|
|
17
|
+
|
|
18
|
+
CN_FUTURES_MIC_CODES = ("CCFX", "XDCE", "XZCE", "XSGE", "XINE", "GFEX")
|
|
19
|
+
PACKAGED_CALENDAR_NAMES = (*CN_FUTURES_MIC_CODES, "CN_FUTURES")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class _CalendarDataset:
|
|
24
|
+
name: str
|
|
25
|
+
holidays: tuple[pd.Timestamp, ...]
|
|
26
|
+
last_session: pd.Timestamp
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@lru_cache(maxsize=1)
|
|
30
|
+
def _load_cn_futures_source() -> pd.DataFrame:
|
|
31
|
+
resource = resources.files(f"{__package__}.data").joinpath(CN_FUTURES_DATA_FILE)
|
|
32
|
+
with resources.as_file(resource) as path:
|
|
33
|
+
df = pd.read_parquet(path)
|
|
34
|
+
out = df.loc[:, ["trade_date", "exchange"]].copy()
|
|
35
|
+
out["trade_date"] = pd.to_datetime(out["trade_date"], errors="coerce").dt.tz_localize(None).dt.normalize()
|
|
36
|
+
out["exchange"] = out["exchange"].astype("string").str.strip().str.upper()
|
|
37
|
+
out = out.dropna(subset=["trade_date", "exchange"])
|
|
38
|
+
out = out.drop_duplicates(subset=["exchange", "trade_date"]).sort_values(["exchange", "trade_date"]).reset_index(drop=True)
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@lru_cache(maxsize=None)
|
|
43
|
+
def _calendar_dataset(name: str) -> _CalendarDataset:
|
|
44
|
+
source = _load_cn_futures_source()
|
|
45
|
+
if name == "CN_FUTURES":
|
|
46
|
+
sessions = pd.DatetimeIndex(
|
|
47
|
+
sorted(source.loc[source["exchange"].isin(CN_FUTURES_MIC_CODES), "trade_date"].unique())
|
|
48
|
+
)
|
|
49
|
+
else:
|
|
50
|
+
sessions = pd.DatetimeIndex(
|
|
51
|
+
sorted(source.loc[source["exchange"] == name, "trade_date"].unique())
|
|
52
|
+
)
|
|
53
|
+
if len(sessions) == 0:
|
|
54
|
+
raise ValueError(f"calendar has no packaged trade_date rows: {name}")
|
|
55
|
+
|
|
56
|
+
start = sessions.min()
|
|
57
|
+
end = sessions.max()
|
|
58
|
+
all_days = pd.date_range(start=start, end=end, freq="D")
|
|
59
|
+
weekdays = pd.DatetimeIndex(all_days[all_days.dayofweek < 5]).normalize()
|
|
60
|
+
holiday_index = weekdays.difference(sessions)
|
|
61
|
+
return _CalendarDataset(name=name, holidays=tuple(holiday_index.to_pydatetime()), last_session=sessions.max())
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class CnFuturesCalendar(ValidDayMixin):
|
|
65
|
+
"""国内期货交易日历:基于包内 parquet 的节假日反推交易日。
|
|
66
|
+
|
|
67
|
+
第一版只承诺 valid-day / session 级能力。schedule() 显式不支持,因为没有
|
|
68
|
+
夜盘 / 开收盘 / 午休 / 品种级交易时段的事实源。
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, calendar_id: str) -> None:
|
|
72
|
+
self._calendar_id = calendar_id
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def name(self) -> str:
|
|
76
|
+
return self._calendar_id
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def last_valid_day(self) -> pd.Timestamp:
|
|
80
|
+
"""包内数据覆盖的最后一个交易日;超出该日期的 valid-day 判断不可靠。"""
|
|
81
|
+
return _calendar_dataset(self.name).last_session
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def tz(self) -> Any:
|
|
85
|
+
return SHANGHAI_TZ
|
|
86
|
+
|
|
87
|
+
def _business_day(self) -> CustomBusinessDay:
|
|
88
|
+
dataset = _calendar_dataset(self.name)
|
|
89
|
+
return CustomBusinessDay(holidays=list(dataset.holidays), weekmask=WEEKMASK)
|
|
90
|
+
|
|
91
|
+
def valid_days(self, start_date: Any, end_date: Any = None, tz: Any = None) -> pd.DatetimeIndex:
|
|
92
|
+
start = pd.Timestamp(start_date).tz_localize(None).normalize()
|
|
93
|
+
end = start if end_date is None else pd.Timestamp(end_date).tz_localize(None).normalize()
|
|
94
|
+
return pd.date_range(start=start, end=end, freq=self._business_day(), tz=SHANGHAI_TZ if tz is None else tz)
|
|
95
|
+
|
|
96
|
+
def schedule(self, *args, **kwargs):
|
|
97
|
+
raise NotImplementedError(
|
|
98
|
+
"SeedData CN-futures calendar only supports valid-day/session-level APIs; schedule() is not supported."
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def make_cn_futures_calendar(calendar_id: str) -> CnFuturesCalendar:
|
|
103
|
+
return CnFuturesCalendar(calendar_id)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
__all__ = [
|
|
107
|
+
"CN_FUTURES_MIC_CODES",
|
|
108
|
+
"CnFuturesCalendar",
|
|
109
|
+
"PACKAGED_CALENDAR_NAMES",
|
|
110
|
+
"make_cn_futures_calendar",
|
|
111
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Packaged calendar data for seeddata SDK."""
|
|
Binary file
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import pandas_market_calendars as mcal
|
|
7
|
+
|
|
8
|
+
from .valid_day_mixin import ValidDayMixin
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
PMC_BACKEND_BY_MIC: dict[str, str] = {
|
|
12
|
+
"XSHG": "XSHG",
|
|
13
|
+
"XSHE": "XSHG",
|
|
14
|
+
"XHKG": "XHKG",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PmcCalendar(ValidDayMixin):
|
|
19
|
+
"""SeedData adapter for a pandas-market-calendars calendar."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, calendar_id: str, backend_name: str) -> None:
|
|
22
|
+
self._calendar_id = calendar_id
|
|
23
|
+
self._delegate = mcal.get_calendar(backend_name)
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def name(self) -> str:
|
|
27
|
+
return self._calendar_id
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def tz(self) -> Any:
|
|
31
|
+
return self._delegate.tz
|
|
32
|
+
|
|
33
|
+
def valid_days(self, start_date: Any, end_date: Any = None, tz: Any = None) -> pd.DatetimeIndex:
|
|
34
|
+
return self._delegate.valid_days(start_date, end_date, tz=self.tz if tz is None else tz)
|
|
35
|
+
|
|
36
|
+
def schedule(
|
|
37
|
+
self,
|
|
38
|
+
start_date: Any,
|
|
39
|
+
end_date: Any = None,
|
|
40
|
+
*,
|
|
41
|
+
session: str = "regular",
|
|
42
|
+
tz: Any = None,
|
|
43
|
+
) -> pd.DataFrame:
|
|
44
|
+
end_date = start_date if end_date is None else end_date
|
|
45
|
+
if session != "regular":
|
|
46
|
+
raise NotImplementedError(f"extended schedule is only supported for XNYS/XNAS, got {self.name}")
|
|
47
|
+
return self._schedule(start_date, end_date, ["market_open", "market_close"], tz)
|
|
48
|
+
|
|
49
|
+
def _schedule(self, start_date: Any, end_date: Any, market_times: list[str], tz: Any) -> pd.DataFrame:
|
|
50
|
+
return self._delegate.schedule(
|
|
51
|
+
start_date=start_date,
|
|
52
|
+
end_date=end_date,
|
|
53
|
+
tz=self.tz if tz is None else tz,
|
|
54
|
+
market_times=market_times,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def make_pmc_calendar(calendar_id: str) -> PmcCalendar:
|
|
59
|
+
return PmcCalendar(calendar_id, PMC_BACKEND_BY_MIC[calendar_id])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"PMC_BACKEND_BY_MIC",
|
|
64
|
+
"PmcCalendar",
|
|
65
|
+
"make_pmc_calendar",
|
|
66
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
|
|
5
|
+
from .cn_futures import PACKAGED_CALENDAR_NAMES, make_cn_futures_calendar
|
|
6
|
+
from .pmc_calendar import PMC_BACKEND_BY_MIC, make_pmc_calendar
|
|
7
|
+
from .us_equities import US_EQUITY_BACKEND_BY_MIC, make_us_equities_calendar
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
SUPPORTED_CALENDAR_NAMES = (
|
|
11
|
+
"CCFX",
|
|
12
|
+
"GFEX",
|
|
13
|
+
"XDCE",
|
|
14
|
+
"XHKG",
|
|
15
|
+
"XINE",
|
|
16
|
+
"XNAS",
|
|
17
|
+
"XNYS",
|
|
18
|
+
"XSGE",
|
|
19
|
+
"XSHE",
|
|
20
|
+
"XSHG",
|
|
21
|
+
"XZCE",
|
|
22
|
+
"CN_FUTURES",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _normalize_calendar_name(name: str) -> str:
|
|
27
|
+
text = str(name).strip().upper()
|
|
28
|
+
if text not in SUPPORTED_CALENDAR_NAMES:
|
|
29
|
+
raise ValueError(f"unsupported calendar name: {name!r}")
|
|
30
|
+
return text
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@lru_cache(maxsize=None)
|
|
34
|
+
def get_calendar(name: str):
|
|
35
|
+
calendar_name = _normalize_calendar_name(name)
|
|
36
|
+
if calendar_name in PACKAGED_CALENDAR_NAMES:
|
|
37
|
+
return make_cn_futures_calendar(calendar_name)
|
|
38
|
+
if calendar_name in US_EQUITY_BACKEND_BY_MIC:
|
|
39
|
+
return make_us_equities_calendar(calendar_name)
|
|
40
|
+
if calendar_name in PMC_BACKEND_BY_MIC:
|
|
41
|
+
return make_pmc_calendar(calendar_name)
|
|
42
|
+
raise ValueError(f"unsupported calendar name: {name!r}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"SUPPORTED_CALENDAR_NAMES",
|
|
47
|
+
"get_calendar",
|
|
48
|
+
]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from .pmc_calendar import PmcCalendar
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
US_EQUITY_BACKEND_BY_MIC = {
|
|
11
|
+
"XNYS": "NYSE",
|
|
12
|
+
"XNAS": "NASDAQ",
|
|
13
|
+
}
|
|
14
|
+
ScheduleSession = Literal["regular", "extended"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UsEquitiesCalendar(PmcCalendar):
|
|
18
|
+
"""Calendar for ordinary US equities, including pre/post-market times."""
|
|
19
|
+
|
|
20
|
+
def schedule(
|
|
21
|
+
self,
|
|
22
|
+
start_date: Any,
|
|
23
|
+
end_date: Any = None,
|
|
24
|
+
*,
|
|
25
|
+
session: ScheduleSession = "regular",
|
|
26
|
+
tz: Any = None,
|
|
27
|
+
) -> pd.DataFrame:
|
|
28
|
+
end_date = start_date if end_date is None else end_date
|
|
29
|
+
if session == "regular":
|
|
30
|
+
market_times = ["market_open", "market_close"]
|
|
31
|
+
elif session == "extended":
|
|
32
|
+
market_times = ["pre", "market_open", "market_close", "post"]
|
|
33
|
+
else:
|
|
34
|
+
raise ValueError(f"unsupported schedule session: {session!r}")
|
|
35
|
+
return self._schedule(start_date, end_date, market_times, tz)
|
|
36
|
+
|
|
37
|
+
def early_closes(
|
|
38
|
+
self,
|
|
39
|
+
start_date: Any,
|
|
40
|
+
end_date: Any = None,
|
|
41
|
+
*,
|
|
42
|
+
session: ScheduleSession = "regular",
|
|
43
|
+
tz: Any = None,
|
|
44
|
+
) -> pd.DataFrame:
|
|
45
|
+
schedule = self.schedule(start_date, end_date, session=session, tz=tz)
|
|
46
|
+
return self._delegate.early_closes(schedule)
|
|
47
|
+
|
|
48
|
+
def late_opens(
|
|
49
|
+
self,
|
|
50
|
+
start_date: Any,
|
|
51
|
+
end_date: Any = None,
|
|
52
|
+
*,
|
|
53
|
+
session: ScheduleSession = "regular",
|
|
54
|
+
tz: Any = None,
|
|
55
|
+
) -> pd.DataFrame:
|
|
56
|
+
schedule = self.schedule(start_date, end_date, session=session, tz=tz)
|
|
57
|
+
return self._delegate.late_opens(schedule)
|
|
58
|
+
|
|
59
|
+
def is_open_at(self, timestamp: Any, *, session: ScheduleSession = "regular") -> bool:
|
|
60
|
+
ts = pd.Timestamp(timestamp)
|
|
61
|
+
if ts.tz is None:
|
|
62
|
+
raise ValueError("timestamp must be timezone-aware")
|
|
63
|
+
local_ts = ts.tz_convert(self.tz)
|
|
64
|
+
schedule = self.schedule(local_ts.date(), session=session)
|
|
65
|
+
if schedule.empty:
|
|
66
|
+
return False
|
|
67
|
+
row = schedule.iloc[0]
|
|
68
|
+
if session == "regular":
|
|
69
|
+
start, end = row["market_open"], row["market_close"]
|
|
70
|
+
else:
|
|
71
|
+
start, end = row["pre"], row["post"]
|
|
72
|
+
return bool(start <= local_ts < end)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def make_us_equities_calendar(calendar_id: str) -> UsEquitiesCalendar:
|
|
76
|
+
return UsEquitiesCalendar(calendar_id, US_EQUITY_BACKEND_BY_MIC[calendar_id])
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
__all__ = [
|
|
80
|
+
"US_EQUITY_BACKEND_BY_MIC",
|
|
81
|
+
"UsEquitiesCalendar",
|
|
82
|
+
"make_us_equities_calendar",
|
|
83
|
+
]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ValidDayMixin:
|
|
7
|
+
def is_valid_day(self, date) -> bool:
|
|
8
|
+
ts = pd.Timestamp(date).tz_localize(None).normalize()
|
|
9
|
+
valid_days = self.valid_days(ts, ts)
|
|
10
|
+
return len(valid_days) == 1 and valid_days[0].tz_localize(None) == ts
|
|
11
|
+
|
|
12
|
+
def date_to_valid_day(self, date, direction: str = "previous") -> pd.Timestamp:
|
|
13
|
+
ts = pd.Timestamp(date).tz_localize(None).normalize()
|
|
14
|
+
if direction not in {"previous", "next"}:
|
|
15
|
+
raise ValueError(f"unsupported direction: {direction!r}")
|
|
16
|
+
|
|
17
|
+
valid_days = self.valid_days(ts, ts)
|
|
18
|
+
if len(valid_days) == 1:
|
|
19
|
+
return valid_days[0]
|
|
20
|
+
|
|
21
|
+
step = -1 if direction == "previous" else 1
|
|
22
|
+
offset = pd.Timedelta(days=step)
|
|
23
|
+
probe = ts
|
|
24
|
+
max_iterations = 366 * 200
|
|
25
|
+
for _ in range(max_iterations):
|
|
26
|
+
probe = probe + offset
|
|
27
|
+
matched = self.valid_days(probe, probe)
|
|
28
|
+
if len(matched) == 1:
|
|
29
|
+
return matched[0]
|
|
30
|
+
raise ValueError(f"no valid day found for {ts.date().isoformat()} direction={direction}")
|
|
31
|
+
|
|
32
|
+
def valid_days_window(self, valid_day, count: int) -> pd.DatetimeIndex:
|
|
33
|
+
if count == 0:
|
|
34
|
+
raise ValueError("count must not be zero")
|
|
35
|
+
|
|
36
|
+
anchor = self.date_to_valid_day(valid_day, direction="previous")
|
|
37
|
+
anchor_naive = anchor.tz_localize(None)
|
|
38
|
+
remaining = abs(count)
|
|
39
|
+
step = -1 if count < 0 else 1
|
|
40
|
+
collected = [anchor]
|
|
41
|
+
probe = anchor_naive
|
|
42
|
+
|
|
43
|
+
while len(collected) < remaining:
|
|
44
|
+
probe = probe + pd.Timedelta(days=step)
|
|
45
|
+
matched = self.valid_days(probe, probe)
|
|
46
|
+
if len(matched) == 1:
|
|
47
|
+
collected.append(matched[0])
|
|
48
|
+
|
|
49
|
+
if count < 0:
|
|
50
|
+
collected.reverse()
|
|
51
|
+
return pd.DatetimeIndex(collected)
|