kepler.pulse 0.2.2__tar.gz → 0.2.4__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.
@@ -0,0 +1,12 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(tree:*)",
5
+ "Bash(python -m py_compile:*)",
6
+ "Bash(python:*)",
7
+ "Bash(find:*)"
8
+ ],
9
+ "deny": [],
10
+ "ask": []
11
+ }
12
+ }
@@ -0,0 +1,110 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+ MANIFEST
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ .hypothesis/
48
+ .pytest_cache/
49
+
50
+ # Translations
51
+ *.mo
52
+ *.pot
53
+
54
+ # Django stuff:
55
+ *.log
56
+ local_settings.py
57
+ db.sqlite3
58
+
59
+ # Flask stuff:
60
+ instance/
61
+ .webassets-cache
62
+
63
+ # Scrapy stuff:
64
+ .scrapy
65
+
66
+ # Sphinx documentation
67
+ docs/_build/
68
+
69
+ # PyBuilder
70
+ target/
71
+
72
+ # Jupyter Notebook
73
+ .ipynb_checkpoints
74
+
75
+ # pyenv
76
+ .python-version
77
+
78
+ # celery beat schedule file
79
+ celerybeat-schedule
80
+
81
+ # SageMath parsed files
82
+ *.sage.py
83
+
84
+ # Environments
85
+ .env
86
+ .venv
87
+ env/
88
+ venv/
89
+ ENV/
90
+ env.bak/
91
+ venv.bak/
92
+
93
+ # Spyder project settings
94
+ .spyderproject
95
+ .spyproject
96
+
97
+ # Rope project settings
98
+ .ropeproject
99
+
100
+ # mkdocs documentation
101
+ /site
102
+
103
+ # mypy
104
+ .mypy_cache/
105
+
106
+ # upload
107
+ upload.py
108
+
109
+ # vscode
110
+ .vscode/
@@ -1,39 +1,38 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: kepler.pulse
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Trade day handling utilities for A-share market
5
- Author-email: liubola <lby3523@gmail.com>
6
- Maintainer-email: liubola <lby3523@gmail.com>
7
- License-Expression: GPL-3.0-or-later
8
5
  Project-URL: Homepage, https://github.com/liubola/kepler-pulse
9
6
  Project-URL: Repository, https://github.com/liubola/kepler-pulse
10
7
  Project-URL: Bug Reports, https://github.com/liubola/kepler-pulse/issues
11
- Keywords: trading,calendar,financial,stock-market,china,a-share,trade-dates
8
+ Author-email: liubola <lby3523@gmail.com>
9
+ Maintainer-email: liubola <lby3523@gmail.com>
10
+ License-Expression: GPL-3.0-or-later
11
+ License-File: LICENSE
12
+ Keywords: a-share,calendar,china,financial,stock-market,trade-dates,trading
12
13
  Classifier: Development Status :: 4 - Beta
13
14
  Classifier: Intended Audience :: Developers
14
15
  Classifier: Intended Audience :: Financial and Insurance Industry
15
16
  Classifier: Operating System :: OS Independent
16
17
  Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
17
19
  Classifier: Programming Language :: Python :: 3.7
18
20
  Classifier: Programming Language :: Python :: 3.8
19
21
  Classifier: Programming Language :: Python :: 3.9
20
22
  Classifier: Programming Language :: Python :: 3.10
21
23
  Classifier: Programming Language :: Python :: 3.11
22
24
  Classifier: Programming Language :: Python :: 3.12
23
- Classifier: Programming Language :: Python :: 3 :: Only
24
25
  Classifier: Topic :: Office/Business :: Financial
25
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
26
  Classifier: Topic :: Office/Business :: Financial :: Investment
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
28
  Requires-Python: >=3.7
28
- Description-Content-Type: text/markdown
29
- License-File: LICENSE
30
29
  Requires-Dist: pandas>=1.0.0
31
30
  Provides-Extra: dev
32
- Requires-Dist: pytest>=6.0; extra == "dev"
33
- Requires-Dist: pytest-cov; extra == "dev"
34
- Requires-Dist: black; extra == "dev"
35
- Requires-Dist: flake8; extra == "dev"
36
- Dynamic: license-file
31
+ Requires-Dist: black; extra == 'dev'
32
+ Requires-Dist: flake8; extra == 'dev'
33
+ Requires-Dist: pytest-cov; extra == 'dev'
34
+ Requires-Dist: pytest>=6.0; extra == 'dev'
35
+ Description-Content-Type: text/markdown
37
36
 
38
37
  # kepler-pulse
39
38
 
@@ -0,0 +1,326 @@
1
+ # Sangreal Calendar 使用指南
2
+
3
+ ## 概述
4
+
5
+ Sangreal Calendar 是一个先进的交易日历管理系统,提供全面的交易日管理、周期性日期计算和期货相关操作功能。
6
+
7
+ ## 主要特性
8
+
9
+ - **交易日管理**: 交易日查询、调整、步进等操作
10
+ - **周期性计算**: 支持日、周、月、季、年等多种频率
11
+ - **期货操作**: 期货交割日期计算、合约切换逻辑
12
+ - **类型安全**: 完整的类型提示和错误处理
13
+ - **向后兼容**: 保持原有API不变
14
+
15
+ ## 快速开始
16
+
17
+ ### 基本交易日操作
18
+
19
+ ```python
20
+ from kepler.pulse import CALENDAR
21
+
22
+ # 注入交易日数据
23
+ CALENDAR.inject([
24
+ '20240102', '20240103', '20240104', '20240105',
25
+ '20240108', '20240109', '20240110', '20240111', '20240112'
26
+ ])
27
+
28
+ # 获取指定时间段的交易日
29
+ trade_dates = CALENDAR.get_trade_dts('20240101', '20240115')
30
+ print(trade_dates.tolist())
31
+ # 输出: ['20240102', '20240103', '20240104', '20240105', '20240108', '20240109', '20240110', '20240111', '20240112']
32
+
33
+ # 调整日期到最近的交易日
34
+ adjusted_next = CALENDAR.adjust_trade_dt('20240106', 'next') # 下一个交易日
35
+ adjusted_last = CALENDAR.adjust_trade_dt('20240106', 'last') # 上一个交易日
36
+ print(f"Next trade date: {adjusted_next}, Last trade date: {adjusted_last}")
37
+
38
+ # 按交易日步进
39
+ next_date = CALENDAR.step_trade_dt('20240108', 3) # 向前3个交易日
40
+ prev_date = CALENDAR.step_trade_dt('20240108', -2) # 向后2个交易日
41
+ print(f"Next: {next_date}, Previous: {prev_date}")
42
+
43
+ # 计算交易日数量
44
+ day_count = CALENDAR.delta_trade_dt('20240102', '20240112')
45
+ print(f"Trade days: {day_count}")
46
+ ```
47
+
48
+ ### 周期性日期计算
49
+
50
+ ```python
51
+ from kepler.pulse import Monthly, Weekly, Quarterly, Yearly
52
+
53
+ # 月度频率 - 每月最后一个交易日
54
+ monthly = Monthly(1)
55
+ month_ends = monthly.get('20240101', '20241231')
56
+ print("Monthly dates:", month_ends.tolist())
57
+
58
+ # 周度频率 - 每周五
59
+ weekly = Weekly(1)
60
+ fridays = weekly.get('20240101', '20240201')
61
+ print("Weekly dates (Fridays):", fridays.tolist())
62
+
63
+ # 季度频率 - 每季度最后一个交易日
64
+ quarterly = Quarterly(1)
65
+ quarter_ends = quarterly.get('20240101', '20241231')
66
+ print("Quarterly dates:", quarter_ends.tolist())
67
+
68
+ # 年度频率 - 每年最后一个交易日
69
+ yearly = Yearly(1)
70
+ year_ends = yearly.get('20230101', '20251231')
71
+ print("Yearly dates:", year_ends.tolist())
72
+
73
+ # 频率导航
74
+ next_month = monthly.next('20240115', 2) # 向前2个月
75
+ prev_month = monthly.prev('20240115', 1) # 向后1个月
76
+ print(f"Next month: {next_month}, Previous month: {prev_month}")
77
+ ```
78
+
79
+ ### 期货相关操作
80
+
81
+ ```python
82
+ from kepler.pulse import get_delistdate, get_contract
83
+
84
+ # 获取期货交割日期
85
+ delivery_dates = get_delistdate('20240115')
86
+ print("Delivery dates:", delivery_dates)
87
+
88
+ # 获取主力合约和次主力合约
89
+ contracts = get_contract('20240115')
90
+ print(f"Main contract: {contracts.iloc[0]}")
91
+ if len(contracts) > 1:
92
+ print(f"Secondary contract: {contracts.iloc[1]}")
93
+
94
+ # 高级期货操作
95
+ from kepler.pulse import FuturesCalendarService, get_futures_service
96
+
97
+ # 获取期货服务实例
98
+ futures_service = get_futures_service(CALENDAR.service)
99
+
100
+ # 获取所有交割日期
101
+ all_delivery_dates = futures_service.get_delivery_dates_all()
102
+ print("All delivery dates:", all_delivery_dates)
103
+
104
+ # 获取国债期货交割日期
105
+ treasury_dates = futures_service.get_treasury_delivery_dates_all()
106
+ print("Treasury delivery dates:", treasury_dates)
107
+
108
+ # 检查是否为合约切换日
109
+ is_switch = futures_service.is_contract_switch_date('20240115')
110
+ print(f"Is contract switch date: {is_switch}")
111
+
112
+ # 获取主力合约
113
+ main_contract = futures_service.get_main_contract('20240115')
114
+ print(f"Main contract: {main_contract}")
115
+ ```
116
+
117
+ ### 使用频率工厂
118
+
119
+ ```python
120
+ from kepler.pulse import FrequencyFactory
121
+
122
+ # 通过工厂创建频率实例
123
+ daily = FrequencyFactory.create('daily')
124
+ weekly = FrequencyFactory.create('weekly')
125
+ monthly = FrequencyFactory.create('monthly', 1, -1) # 支持多方向
126
+
127
+ # 获取可用频率类型
128
+ available_frequencies = FrequencyFactory.get_available_frequencies()
129
+ print("Available frequencies:", available_frequencies)
130
+ ```
131
+
132
+ ### 配置管理
133
+
134
+ ```python
135
+ from kepler.pulse import config, CalendarConfig
136
+
137
+ # 使用全局配置
138
+ print(f"Default begin date: {config.begin_date}")
139
+ print(f"Max step forward: {config.max_step}")
140
+
141
+ # 自定义配置
142
+ custom_config = CalendarConfig(
143
+ begin_date='20200101',
144
+ end_date='20301231',
145
+ max_step=1000,
146
+ cache_size=256
147
+ )
148
+
149
+ # 验证日期范围
150
+ is_valid = custom_config.validate_date_range('20200101', '20301231')
151
+ print(f"Date range valid: {is_valid}")
152
+ ```
153
+
154
+ ### 错误处理
155
+
156
+ ```python
157
+ from kepler.pulse import (
158
+ ValidationError, CalendarError, DateNotFoundError,
159
+ FrequencyCalculatorError
160
+ )
161
+
162
+ try:
163
+ # 无效的日期范围
164
+ CALENDAR.get_trade_dts('20241231', '20240101')
165
+ except CalendarError as e:
166
+ print(f"Calendar error: {e}")
167
+
168
+ try:
169
+ # 无效的调整参数
170
+ CALENDAR.adjust_trade_dt('20240115', 'invalid')
171
+ except ValidationError as e:
172
+ print(f"Validation error: {e}")
173
+
174
+ try:
175
+ # 无效的频率类型
176
+ FrequencyFactory.create('invalid_frequency')
177
+ except FrequencyCalculatorError as e:
178
+ print(f"Frequency error: {e}")
179
+ ```
180
+
181
+ ## 高级用法
182
+
183
+ ### 自定义日历服务
184
+
185
+ ```python
186
+ from kepler.pulse import CalendarService
187
+
188
+ # 创建自定义日历服务
189
+ custom_calendar = CalendarService(
190
+ dates=['20240101', '20240102', '20240103'],
191
+ config=custom_config
192
+ )
193
+
194
+ # 使用自定义服务
195
+ dates = custom_calendar.get_trade_dates('20240101', '20240103')
196
+ adjusted = custom_calendar.adjust_trade_date('20240102', 'next')
197
+ ```
198
+
199
+ ### 多市场支持
200
+
201
+ ```python
202
+ from kepler.pulse import set
203
+
204
+ # 设置支持的市场
205
+ set(['CN', 'US', 'HK']) # 中国、美国、香港
206
+
207
+ # 单一市场
208
+ set('CN')
209
+ ```
210
+
211
+ ### 类型安全使用
212
+
213
+ ```python
214
+ from typing import List
215
+ from kepler.pulse import CalendarService, Monthly
216
+
217
+ def calculate_monthly_dates(
218
+ calendar: CalendarService,
219
+ begin_date: str,
220
+ end_date: str
221
+ ) -> List[str]:
222
+ """
223
+ 计算指定时间段的月度日期
224
+
225
+ Args:
226
+ calendar: 日历服务实例
227
+ begin_date: 开始日期
228
+ end_date: 结束日期
229
+
230
+ Returns:
231
+ 月度日期列表
232
+ """
233
+ monthly = Monthly(1)
234
+ return monthly.get(begin_date, end_date).tolist()
235
+
236
+ # 使用类型安全的函数
237
+ monthly_dates = calculate_monthly_dates(CALENDAR.service, '20240101', '20241231')
238
+ print(f"Monthly dates: {monthly_dates}")
239
+ ```
240
+
241
+ ## 性能优化建议
242
+
243
+ 1. **使用缓存**: 所有核心函数都使用 `@lru_cache` 装饰器进行缓存优化
244
+ 2. **批量操作**: 尽量使用批量操作而非单个操作
245
+ 3. **预加载日期**: 在应用启动时注入所有需要的交易日数据
246
+ 4. **适当配置**: 根据使用场景调整缓存大小和步长限制
247
+
248
+ ```python
249
+ # 性能优化示例
250
+ # 一次性注入大量数据
251
+ all_trade_dates = [...] # 从数据源加载所有交易日
252
+ CALENDAR.inject(all_trade_dates)
253
+
254
+ # 批量查询
255
+ date_ranges = [
256
+ ('20240101', '20240131'),
257
+ ('20240201', '20240229'),
258
+ ('20240301', '20240331')
259
+ ]
260
+ results = [CALENDAR.get_trade_dts(start, end) for start, end in date_ranges]
261
+ ```
262
+
263
+ ## 最佳实践
264
+
265
+ 1. **初始化检查**: 在使用前确保日历已注入数据
266
+ 2. **错误处理**: 使用适当的异常处理机制
267
+ 3. **类型提示**: 充分利用类型提示提高代码质量
268
+ 4. **文档**: 为自定义函数编写详细的文档字符串
269
+
270
+ ```python
271
+ def safe_get_trade_dates(begin_date: str, end_date: str) -> List[str]:
272
+ """
273
+ 安全获取交易日列表
274
+
275
+ Args:
276
+ begin_date: 开始日期,格式YYYYMMDD
277
+ end_date: 结束日期,格式YYYYMMDD
278
+
279
+ Returns:
280
+ 交易日列表,如果出错则返回空列表
281
+
282
+ Examples:
283
+ >>> safe_get_trade_dates('20240101', '20240131')
284
+ ['20240102', '20240103', ...]
285
+ """
286
+ try:
287
+ if CALENDAR.service.is_empty:
288
+ return []
289
+
290
+ return CALENDAR.get_trade_dts(begin_date, end_date).tolist()
291
+ except Exception as e:
292
+ print(f"Error getting trade dates: {e}")
293
+ return []
294
+ ```
295
+
296
+ ## 故障排除
297
+
298
+ ### 常见问题
299
+
300
+ 1. **日历为空**: 确保在使用前注入了交易日数据
301
+ 2. **日期格式错误**: 使用YYYYMMDD格式的字符串
302
+ 3. **步长超限**: 检查步长是否超过配置的最大值
303
+ 4. **缓存问题**: 重启应用程序或清除缓存
304
+
305
+ ### 调试技巧
306
+
307
+ ```python
308
+ # 检查日历状态
309
+ print(f"Calendar empty: {CALENDAR.service.is_empty}")
310
+ print(f"Trade dates count: {len(CALENDAR.service.dates)}")
311
+ print(f"Date range: {CALENDAR.service.dates.min()} - {CALENDAR.service.dates.max()}")
312
+
313
+ # 检查配置
314
+ print(f"Max step: {config.max_step}")
315
+ print(f"Cache size: {config.cache_size}")
316
+ ```
317
+
318
+ 这个重构后的代码结构提供了:
319
+
320
+ 1. **更好的可读性**: 清晰的模块分离和类型提示
321
+ 2. **更强的扩展性**: 依赖注入模式和工厂模式
322
+ 3. **更完善的错误处理**: 自定义异常和验证机制
323
+ 4. **更全面的文档**: 详细的文档字符串和使用示例
324
+ 5. **向后兼容**: 保持原有API输出不变
325
+
326
+ 通过这些改进,代码变得更加健壮、可维护和易于扩展,同时保证了与现有代码的兼容性。
@@ -1,10 +1,9 @@
1
1
  [build-system]
2
- requires = [ "setuptools>=61.0", "wheel",]
3
- build-backend = "setuptools.build_meta"
4
-
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
5
4
  [project]
6
5
  name = "kepler.pulse"
7
- version = "0.2.2"
6
+ version = "0.2.4"
8
7
  description = "Trade day handling utilities for A-share market"
9
8
  readme = "README.md"
10
9
  license = "GPL-3.0-or-later"
@@ -28,13 +27,6 @@ Homepage = "https://github.com/liubola/kepler-pulse"
28
27
  Repository = "https://github.com/liubola/kepler-pulse"
29
28
  "Bug Reports" = "https://github.com/liubola/kepler-pulse/issues"
30
29
 
31
- [tool.setuptools]
32
- include-package-data = true
33
- zip-safe = false
34
-
35
- [tool.setuptools.package-data]
36
- "*" = [ "*.txt", "*.json", "*.csv", "*.xlsx", "*.xls",]
37
-
38
- [tool.setuptools.packages.find]
39
- where = [ "src",]
40
- exclude = [ "tests*",]
30
+ [tool.hatch.build.targets.wheel]
31
+ # 命名空间包 kepler 的外层目录(src/ 下只有本包);git 跟踪的非 .py 文件默认一起打包
32
+ packages = ["src/kepler"]
@@ -25,8 +25,12 @@ Examples:
25
25
  """
26
26
 
27
27
  from .core.trading_calendar import Calendar, CalendarError
28
+ from importlib import metadata
28
29
 
29
- __version__ = '2.0.0'
30
+ try:
31
+ __version__ = metadata.version("kepler.pulse")
32
+ except metadata.PackageNotFoundError: # 未安装时(直接从源码目录导入)
33
+ __version__ = "unknown"
30
34
  __author__ = 'liubola'
31
35
 
32
36
  __all__ = [
@@ -3,6 +3,7 @@ Trading Calendar Module.
3
3
  """
4
4
 
5
5
  import datetime as dt
6
+ from functools import lru_cache
6
7
  from typing import Union, Literal
7
8
 
8
9
  import numpy as np
@@ -330,9 +331,14 @@ class Calendar:
330
331
  'daily': {'offset': 0},
331
332
  'weekly': {'offset': WEEKLY_OFFSET, 'period': lambda x: f"{x.isocalendar()[0]}{x.isocalendar()[1]}"},
332
333
  'biweekly': {'offset': WEEKLY_OFFSET, 'period': lambda x: f"{x.isocalendar()[0]}{x.isocalendar()[1]}"},
333
- 'monthly': {'offset': MONTHLY_OFFSET, 'period': lambda x: f"{x.year}{x.month}"},
334
- 'quarterly': {'offset': QUARTERLY_OFFSET, 'period': lambda x: f"{x.year}{x.quarter}"},
335
- 'yearly': {'offset': YEARLY_OFFSET, 'period': lambda x: f"{x.year}"},
334
+ # 字符串向量化路径(_get_frequency 直接用 YYYYMMDD 切片,省 pd.to_datetime):
335
+ # period 语义与 to_datetime 版本位级一致(YYYYMM / YYYYQ / YYYY)。
336
+ 'monthly': {'offset': MONTHLY_OFFSET, 'period': lambda x: f"{x.year}{x.month}",
337
+ 'str_period': lambda s: s[:6]},
338
+ 'quarterly': {'offset': QUARTERLY_OFFSET, 'period': lambda x: f"{x.year}{x.quarter}",
339
+ 'str_period': lambda s: s[:4] + str((int(s[4:6]) - 1) // 3 + 1)},
340
+ 'yearly': {'offset': YEARLY_OFFSET, 'period': lambda x: f"{x.year}",
341
+ 'str_period': lambda s: s[:4]},
336
342
  'halfyearly': {'offset': MONTHLY_OFFSET},
337
343
  'reportly': {'offset': QUARTERLY_OFFSET},
338
344
  }
@@ -351,19 +357,31 @@ class Calendar:
351
357
  elif freq == 'reportly':
352
358
  return self._get_reportly(begin, end, keep)
353
359
  elif freq == 'biweekly':
354
- dates = self._get_frequency(begin, end, config['period'], offset, keep)
360
+ dates = self._get_frequency(freq, begin, end, config['period'], offset, keep)
355
361
  return dates[::2].reset_index(drop=True)
356
362
  else:
357
- return self._get_frequency(begin, end, config['period'], offset, keep)
363
+ return self._get_frequency(freq, begin, end, config['period'], offset, keep)
358
364
 
359
- def _get_frequency(self, begin, end, period_func, offset, keep):
365
+ def _get_frequency(self, freq, begin, end, period_func, offset, keep):
360
366
  begin, end = validate_date(begin), validate_date(end)
361
367
  df = self.range(
362
368
  self.step(begin, -offset),
363
369
  self.step(end, offset)
364
370
  ).to_frame('trade_dt')
365
- df['_dt'] = pd.to_datetime(df['trade_dt'])
366
- df['period'] = df['_dt'].map(period_func)
371
+ str_period = self.FREQ_CONFIG.get(freq, {}).get('str_period')
372
+ if str_period is not None:
373
+ # 字符串向量化:YYYYMMDD 切片直接得 period,免去整段 pd.to_datetime
374
+ # + 逐元素 map(月度/季度/年度在 12000 交易日上 ~10ms → <1ms)。
375
+ if freq == 'monthly':
376
+ df['period'] = df['trade_dt'].str[:6]
377
+ elif freq == 'quarterly':
378
+ m = df['trade_dt'].str[4:6].astype(int)
379
+ df['period'] = df['trade_dt'].str[:4] + ((m - 1) // 3 + 1).astype(str)
380
+ else: # yearly
381
+ df['period'] = df['trade_dt'].str[:4]
382
+ else:
383
+ df['_dt'] = pd.to_datetime(df['trade_dt'])
384
+ df['period'] = df['_dt'].map(period_func)
367
385
  result = df.drop_duplicates('period', keep=keep)['trade_dt']
368
386
  result = result[(result >= begin) & (result <= end)].reset_index(drop=True)
369
387
  return result
@@ -456,7 +474,11 @@ class Calendar:
456
474
 
457
475
  # ============ 期货内部实现 ============
458
476
 
477
+ @lru_cache(maxsize=8)
459
478
  def _stock_delivery_dates_all(self) -> list:
479
+ """股票期货全部交割日。交割日由合约规则决定、不随调用变化,
480
+ 全量重算涉及全历史月度序列 + to_datetime + 逐日 adjust(~200ms),
481
+ 用 lru_cache 缓存(真实 downloader 反复调用 futures.stock)。"""
460
482
  today = dt.datetime.today().strftime('%Y%m%d')
461
483
  dates = self.monthly.first(FUTURES_START_DATE, f'{int(today[:4]) + YEARS_FORWARD}0101')
462
484
  dates = pd.to_datetime(dates).dt.date + WeekOfMonth(1, week=2, weekday=4)
@@ -477,9 +499,12 @@ class Calendar:
477
499
  today = dt.datetime.today().strftime('%Y%m%d')
478
500
  dates = self.quarterly.last(TREASURY_START_DATE, f'{int(today[:4]) + YEARS_FORWARD}0101')
479
501
  dates = dates.map(lambda x: self.step(self.monthly.first.prev(x), -2))
502
+ # 只用 `< _dates.iloc[-1]` 收尾,不要再加 "<= 未来第 N 个季初" 的 cap:
503
+ # tqsdk 交易日历止于当年 12-31,Q3/Q4 时 quarterly.first.next(today, 2)
504
+ # 需要的次年季初在日历外,_next_freq_date 静默回退 df[-1] 后会把下一个
505
+ # 真实交割日(如 20261127)错误过滤掉,downloader 拿不到换月配对。
480
506
  dates = dates[dates < self._dates.iloc[-1]].copy()
481
- dates = sorted([d for d in dates if d <= self.quarterly.first.next(today, 2)])
482
- return dates
507
+ return sorted(dates)
483
508
 
484
509
  def _main_contracts(self, date: str) -> pd.Series:
485
510
  delivery = self._stock_delivery_dates(date).iloc[-1]
@@ -1,257 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: kepler.pulse
3
- Version: 0.2.2
4
- Summary: Trade day handling utilities for A-share market
5
- Author-email: liubola <lby3523@gmail.com>
6
- Maintainer-email: liubola <lby3523@gmail.com>
7
- License-Expression: GPL-3.0-or-later
8
- Project-URL: Homepage, https://github.com/liubola/kepler-pulse
9
- Project-URL: Repository, https://github.com/liubola/kepler-pulse
10
- Project-URL: Bug Reports, https://github.com/liubola/kepler-pulse/issues
11
- Keywords: trading,calendar,financial,stock-market,china,a-share,trade-dates
12
- Classifier: Development Status :: 4 - Beta
13
- Classifier: Intended Audience :: Developers
14
- Classifier: Intended Audience :: Financial and Insurance Industry
15
- Classifier: Operating System :: OS Independent
16
- Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.7
18
- Classifier: Programming Language :: Python :: 3.8
19
- Classifier: Programming Language :: Python :: 3.9
20
- Classifier: Programming Language :: Python :: 3.10
21
- Classifier: Programming Language :: Python :: 3.11
22
- Classifier: Programming Language :: Python :: 3.12
23
- Classifier: Programming Language :: Python :: 3 :: Only
24
- Classifier: Topic :: Office/Business :: Financial
25
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
- Classifier: Topic :: Office/Business :: Financial :: Investment
27
- Requires-Python: >=3.7
28
- Description-Content-Type: text/markdown
29
- License-File: LICENSE
30
- Requires-Dist: pandas>=1.0.0
31
- Provides-Extra: dev
32
- Requires-Dist: pytest>=6.0; extra == "dev"
33
- Requires-Dist: pytest-cov; extra == "dev"
34
- Requires-Dist: black; extra == "dev"
35
- Requires-Dist: flake8; extra == "dev"
36
- Dynamic: license-file
37
-
38
- # kepler-pulse
39
-
40
- 交易日历工具库,支持多套日历实例、多种频率周期。
41
-
42
- ## 安装
43
-
44
- ```bash
45
- pip install kepler-pulse
46
- ```
47
-
48
- ## 快速开始
49
-
50
- ```python
51
- from kepler.pulse import Calendar
52
-
53
- # 创建日历实例(需自行注入交易日数据)
54
- cal = Calendar()
55
-
56
- # 注入交易日数据(支持 list/tuple/pd.Series)
57
- cal.inject(trade_dates)
58
-
59
- # 或者创建时直接传入
60
- cal = Calendar(trade_dates)
61
- ```
62
-
63
- ## 基础操作
64
-
65
- ### 获取日期范围
66
-
67
- ```python
68
- cal.range('20240101', '20240131')
69
- # → pd.Series: ['20240102', '20240103', ..., '20240131']
70
- ```
71
-
72
- ### 调整到最近交易日
73
-
74
- ```python
75
- # 向前找(默认)
76
- cal.adjust('20240101', 'prev')
77
- # → '20231229'(上一个交易日)
78
-
79
- # 向后找
80
- cal.adjust('20240101', 'next')
81
- # → '20240102'(下一个交易日)
82
- ```
83
-
84
- ### 按步长跳转
85
-
86
- ```python
87
- # 正数向前
88
- cal.step('20240102', 3)
89
- # → '20240105'(后第3个交易日)
90
-
91
- # 负数向后
92
- cal.step('20240105', -2)
93
- # → '20240103'(前第2个交易日)
94
- ```
95
-
96
- ### 计算交易日数量
97
-
98
- ```python
99
- cal.delta('20240101', '20240131')
100
- # → 22(两个日期间的交易日数量)
101
- ```
102
-
103
- ## 频率操作
104
-
105
- 支持的频率类型:
106
- - `daily` — 日频
107
- - `weekly` — 周频
108
- - `biweekly` — 双周频
109
- - `monthly` — 月频
110
- - `quarterly` — 季频
111
- - `halfyearly` — 半年频
112
- - `yearly` — 年频
113
- - `reportly` — 财报频
114
-
115
- ### 获取周期边界日期
116
-
117
- ```python
118
- # 获取每月第一个交易日
119
- cal.monthly.first('20240101', '20241231')
120
- # → pd.Series: ['20240102', '20240201', '20240301', ...]
121
-
122
- # 获取每月最后一个交易日
123
- cal.monthly.last('20240101', '20241231')
124
- # → pd.Series: ['20240131', '20240229', '20240329', ...]
125
-
126
- # 获取月初+月末(去重排序)
127
- cal.monthly.both('20240101', '20240331')
128
- # → pd.Series: ['20240102', '20240131', '20240201', '20240229', ...]
129
- ```
130
-
131
- ### 获取下一个/上一个边界日期
132
-
133
- ```python
134
- # 下一个月初
135
- cal.monthly.first.next('20240115')
136
- # → '20240201'
137
-
138
- # 下一个月末
139
- cal.monthly.last.next('20240115')
140
- # → '20240131'
141
-
142
- # 上一个月初
143
- cal.monthly.first.prev('20240115')
144
- # → '20240102'
145
-
146
- # 上一个月末
147
- cal.monthly.last.prev('20240115')
148
- # → '20231229'
149
-
150
- # 支持步长
151
- cal.monthly.first.next('20240115', step=2)
152
- # → '20240301'(下下个月初)
153
- ```
154
-
155
- ### 其他频率示例
156
-
157
- ```python
158
- # 周频
159
- cal.weekly.first('20240101', '20240131')
160
- cal.weekly.last.next('20240115')
161
-
162
- # 季频
163
- cal.quarterly.first('20240101', '20241231')
164
- cal.quarterly.last.prev('20240615')
165
-
166
- # 年频
167
- cal.yearly.first('20200101', '20241231')
168
- cal.yearly.last.next('20240601')
169
- ```
170
-
171
- ## 期货操作
172
-
173
- ### 股指期货交割日
174
-
175
- ```python
176
- # 获取指定日期之前的交割日
177
- cal.futures.stock('20240115')
178
- # → pd.Series: ['20231117', '20231215', '20240119', ...]
179
-
180
- # 获取所有交割日
181
- cal.futures.stock(all=True)
182
- # → list: ['20231117', '20231215', '20240119', ...]
183
- ```
184
-
185
- ### 国债期货交割日
186
-
187
- ```python
188
- cal.futures.treasury()
189
- # → list: ['20231215', '20240315', ...]
190
- ```
191
-
192
- ### 主力合约
193
-
194
- ```python
195
- cal.futures.contracts('20240115')
196
- # → pd.Series: ['2401', '2402'](当月+次月合约)
197
-
198
- # 非换合约期
199
- cal.futures.contracts('20240102')
200
- # → pd.Series: ['2401'](仅当月合约)
201
- ```
202
-
203
- ## 多日历支持
204
-
205
- ```python
206
- # A股日历
207
- cal_a = Calendar(a_share_dates)
208
-
209
- # 港股日历
210
- cal_hk = Calendar(hk_share_dates)
211
-
212
- # 美股日历
213
- cal_us = Calendar(us_share_dates)
214
-
215
- # 独立使用
216
- cal_a.monthly.first('20240101', '20241231')
217
- cal_hk.monthly.first('20240101', '20241231')
218
- ```
219
-
220
- ## API 对照表
221
-
222
- ### 基础操作
223
-
224
- | 旧 API | 新 API |
225
- |--------|--------|
226
- | `get_trade_dts(begin, end)` | `cal.range(begin, end)` |
227
- | `adjust_trade_dt(date, 'last')` | `cal.adjust(date, 'prev')` |
228
- | `adjust_trade_dt(date, 'next')` | `cal.adjust(date, 'next')` |
229
- | `step_trade_dt(date, n)` | `cal.step(date, n)` |
230
- | `delta_trade_dt(begin, end)` | `cal.delta(begin, end)` |
231
-
232
- ### 频率操作
233
-
234
- | 旧 API | 新 API |
235
- |--------|--------|
236
- | `Monthly(1).get(begin, end)` | `cal.monthly.first(begin, end)` |
237
- | `Monthly(-1).get(begin, end)` | `cal.monthly.last(begin, end)` |
238
- | `Monthly(1, -1).get(begin, end)` | `cal.monthly.both(begin, end)` |
239
- | `Monthly(1).next(date)` | `cal.monthly.first.next(date)` |
240
- | `Monthly(-1).next(date)` | `cal.monthly.last.next(date)` |
241
- | `Monthly(1).prev(date)` | `cal.monthly.first.prev(date)` |
242
- | `Monthly(-1).prev(date)` | `cal.monthly.last.prev(date)` |
243
-
244
- ### 期货操作
245
-
246
- | 旧 API | 新 API |
247
- |--------|--------|
248
- | `get_delistdate(date)` | `cal.futures.stock(date)` |
249
- | `get_delistdate_all()` | `cal.futures.stock(all=True)` |
250
- | `get_delistdate_tf_all()` | `cal.futures.treasury()` |
251
- | `get_contract(date)` | `cal.futures.contracts(date)` |
252
-
253
- ## 注意事项
254
-
255
- 1. **日期格式**:仅支持 `YYYYMMDD` 格式的字符串或整数
256
- 2. **日历实例化**:不再使用全局单例,需自行创建 `Calendar` 实例并注入交易日数据
257
- 3. **缓存机制**:每个 `Calendar` 实例内部有缓存,相同参数不会重复计算
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
@@ -1,14 +0,0 @@
1
- LICENSE
2
- README.md
3
- pyproject.toml
4
- src/kepler.pulse.egg-info/PKG-INFO
5
- src/kepler.pulse.egg-info/SOURCES.txt
6
- src/kepler.pulse.egg-info/dependency_links.txt
7
- src/kepler.pulse.egg-info/not-zip-safe
8
- src/kepler.pulse.egg-info/requires.txt
9
- src/kepler.pulse.egg-info/top_level.txt
10
- src/kepler/pulse/__init__.py
11
- src/kepler/pulse/config.py
12
- src/kepler/pulse/utils.py
13
- src/kepler/pulse/core/__init__.py
14
- src/kepler/pulse/core/trading_calendar.py
@@ -1,7 +0,0 @@
1
- pandas>=1.0.0
2
-
3
- [dev]
4
- pytest>=6.0
5
- pytest-cov
6
- black
7
- flake8
File without changes
File without changes