kepler.pulse 0.1.7__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.
- kepler/pulse/__init__.py +76 -0
- kepler/pulse/config.py +154 -0
- kepler/pulse/core/__init__.py +0 -0
- kepler/pulse/core/refresh_rate_handle.py +459 -0
- kepler/pulse/core/trade_dt_futures.py +78 -0
- kepler/pulse/core/trade_dt_handle.py +307 -0
- kepler/pulse/utils.py +68 -0
- kepler_pulse-0.1.7.dist-info/METADATA +144 -0
- kepler_pulse-0.1.7.dist-info/RECORD +12 -0
- kepler_pulse-0.1.7.dist-info/WHEEL +5 -0
- kepler_pulse-0.1.7.dist-info/licenses/LICENSE +674 -0
- kepler_pulse-0.1.7.dist-info/top_level.txt +1 -0
kepler/pulse/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sangreal Calendar - Advanced Trading Date Management System.
|
|
3
|
+
|
|
4
|
+
This package provides comprehensive functionality for managing trading calendars,
|
|
5
|
+
calculating periodic dates, and handling futures-related trading date operations.
|
|
6
|
+
|
|
7
|
+
Key Features:
|
|
8
|
+
- Trade date manipulation and adjustment
|
|
9
|
+
- Periodic frequency calculations (daily, weekly, monthly, quarterly, etc.)
|
|
10
|
+
- Futures delivery date calculations
|
|
11
|
+
- Contract switching logic
|
|
12
|
+
- Type-safe operations with comprehensive error handling
|
|
13
|
+
- Backward compatibility with existing code
|
|
14
|
+
|
|
15
|
+
Main Components:
|
|
16
|
+
- Enhanced core modules with type hints and better error handling
|
|
17
|
+
- Configuration management for better maintainability
|
|
18
|
+
- Improved documentation and examples
|
|
19
|
+
|
|
20
|
+
Basic Usage:
|
|
21
|
+
>>> from kepler.pulse import CALENDAR
|
|
22
|
+
>>> CALENDAR.inject(['20240101', '20240102', '20240103']) # Inject trade dates
|
|
23
|
+
>>> dates = CALENDAR.get_trade_dts('20240101', '20240131') # Get trade dates
|
|
24
|
+
>>> adjusted = CALENDAR.adjust_trade_dt('20240101', 'next') # Adjust to next trade date
|
|
25
|
+
|
|
26
|
+
# Frequency calculations
|
|
27
|
+
>>> from kepler.pulse.core.refresh_rate_handle import Monthly, Weekly
|
|
28
|
+
>>> monthly = Monthly(1)
|
|
29
|
+
>>> month_ends = monthly.get('20240101', '20241231')
|
|
30
|
+
|
|
31
|
+
# Futures operations
|
|
32
|
+
>>> from kepler.pulse.core.trade_dt_futures import get_delistdate
|
|
33
|
+
>>> delivery_dates = get_delistdate('20240115')
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
# Import all core modules for backward compatibility
|
|
37
|
+
from .core.trade_dt_handle import *
|
|
38
|
+
from .core.trade_dt_futures import *
|
|
39
|
+
from .core.refresh_rate_handle import *
|
|
40
|
+
|
|
41
|
+
# Import utilities
|
|
42
|
+
from .utils import dt_handle, set
|
|
43
|
+
|
|
44
|
+
# Import enhanced configuration
|
|
45
|
+
from .config import config, CalendarConfig
|
|
46
|
+
|
|
47
|
+
# Version information
|
|
48
|
+
__version__ = '1.0.0'
|
|
49
|
+
__author__ = 'liubola'
|
|
50
|
+
__email__ = 'lby3523@gmail.com'
|
|
51
|
+
__license__ = 'GNU General Public License v3.0'
|
|
52
|
+
|
|
53
|
+
# Export all public components
|
|
54
|
+
__all__ = [
|
|
55
|
+
# Core calendar from trade_dt_handle
|
|
56
|
+
'CALENDAR', 'get_trade_dts', 'adjust_trade_dt', 'step_trade_dt', 'delta_trade_dt',
|
|
57
|
+
|
|
58
|
+
# Frequency classes from refresh_rate_handle
|
|
59
|
+
'RefreshBase', 'Daily', 'Weekly', 'BiWeekly', 'Monthly', 'Quarterly',
|
|
60
|
+
'Reportly', 'Halfyearly', 'Yearly',
|
|
61
|
+
|
|
62
|
+
# Futures functions from trade_dt_futures
|
|
63
|
+
'get_delistdate_all', 'get_delistdate_tf_all', 'get_delistdate', 'get_contract',
|
|
64
|
+
|
|
65
|
+
# Utilities
|
|
66
|
+
'dt_handle', 'set',
|
|
67
|
+
|
|
68
|
+
# Configuration
|
|
69
|
+
'config', 'CalendarConfig',
|
|
70
|
+
|
|
71
|
+
# Meta
|
|
72
|
+
'__version__', '__author__', '__email__', '__license__',
|
|
73
|
+
|
|
74
|
+
# Enhanced types from core modules
|
|
75
|
+
'CalendarBase', 'CalendarError', # From enhanced trade_dt_handle
|
|
76
|
+
]
|
kepler/pulse/config.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration module for kepler-pulse.
|
|
3
|
+
|
|
4
|
+
This module centralizes all configuration constants and settings
|
|
5
|
+
to improve maintainability and reduce magic numbers throughout the codebase.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Dict, Any
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
# Date range constants
|
|
12
|
+
DEFAULT_BEGIN_DATE: str = '19900101'
|
|
13
|
+
DEFAULT_END_DATE: str = '20990101'
|
|
14
|
+
MAX_STEP_FORWARD: int = 600 # Maximum forward step for trade date navigation
|
|
15
|
+
|
|
16
|
+
# Environment variable names
|
|
17
|
+
ENV_COUNTRY: str = 'CN' # Default country for market operations
|
|
18
|
+
|
|
19
|
+
# Frequency calculation constants
|
|
20
|
+
WEEKLY_DAYS: Dict[int, int] = {
|
|
21
|
+
1: 0, # Monday
|
|
22
|
+
2: 1, # Tuesday
|
|
23
|
+
3: 2, # Wednesday
|
|
24
|
+
4: 3, # Thursday
|
|
25
|
+
5: 4, # Friday
|
|
26
|
+
6: -1, # Saturday (invalid)
|
|
27
|
+
7: -2, # Sunday (invalid)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
# Frequency search steps
|
|
31
|
+
DAILY_SEARCH_STEPS: int = 600
|
|
32
|
+
WEEKLY_OFFSET: int = 20
|
|
33
|
+
MONTHLY_OFFSET: int = 40
|
|
34
|
+
QUARTERLY_OFFSET: int = 120
|
|
35
|
+
YEARLY_OFFSET: int = 300
|
|
36
|
+
|
|
37
|
+
# Futures configuration constants
|
|
38
|
+
FUTURES_START_DATE: str = '20150501'
|
|
39
|
+
TREASURY_START_DATE: str = '20151231'
|
|
40
|
+
CONTRACT_SWITCH_DAYS: int = 4
|
|
41
|
+
YEARS_FORWARD: int = 2
|
|
42
|
+
|
|
43
|
+
# Format constants
|
|
44
|
+
DEFAULT_DATE_FORMAT: str = '%Y%m%d'
|
|
45
|
+
FUTURE_DATE_FORMAT: str = '%Y%m%d'
|
|
46
|
+
|
|
47
|
+
# Futures configuration
|
|
48
|
+
FUTURES_DELIVERY_CODES: Dict[str, str] = {
|
|
49
|
+
'TF': 'TF', # Treasury futures
|
|
50
|
+
'T': 'T', # Treasury futures
|
|
51
|
+
'TS': 'TS', # Treasury futures
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
# Calendar cache configuration
|
|
55
|
+
CACHE_SIZE: int = 128 # Default cache size for LRU cache
|
|
56
|
+
|
|
57
|
+
# Error messages
|
|
58
|
+
ERROR_MESSAGES: Dict[str, str] = {
|
|
59
|
+
'empty_dates': 'Trade dates series is empty',
|
|
60
|
+
'date_not_found': 'Date not found in calendar',
|
|
61
|
+
'invalid_date_range': 'Invalid date range: begin date must be before end date',
|
|
62
|
+
'step_limit_exceeded': f'Step limit exceeded (max: {MAX_STEP_FORWARD})',
|
|
63
|
+
'invalid_frequency': 'Invalid frequency specified',
|
|
64
|
+
'calendar_not_initialized': 'Calendar not initialized with trade dates',
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Validation patterns
|
|
68
|
+
DATE_PATTERN: str = r'^\d{8}$' # YYYYMMDD format validation
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CalendarConfig:
|
|
72
|
+
"""
|
|
73
|
+
Centralized configuration class for calendar operations.
|
|
74
|
+
|
|
75
|
+
This class provides a single point of configuration management
|
|
76
|
+
and allows for easy customization of calendar behavior.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self,
|
|
80
|
+
begin_date: str = DEFAULT_BEGIN_DATE,
|
|
81
|
+
end_date: str = DEFAULT_END_DATE,
|
|
82
|
+
max_step: int = MAX_STEP_FORWARD,
|
|
83
|
+
cache_size: int = CACHE_SIZE,
|
|
84
|
+
country: str = ENV_COUNTRY):
|
|
85
|
+
"""
|
|
86
|
+
Initialize calendar configuration.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
begin_date: Default begin date for operations
|
|
90
|
+
end_date: Default end date for operations
|
|
91
|
+
max_step: Maximum forward step for navigation
|
|
92
|
+
cache_size: Cache size for LRU caching
|
|
93
|
+
country: Country code for market operations
|
|
94
|
+
"""
|
|
95
|
+
self.begin_date = begin_date
|
|
96
|
+
self.end_date = end_date
|
|
97
|
+
self.max_step = max_step
|
|
98
|
+
self.cache_size = cache_size
|
|
99
|
+
self.country = country
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def default_country(self) -> str:
|
|
103
|
+
"""Get the default country code."""
|
|
104
|
+
return self.country
|
|
105
|
+
|
|
106
|
+
@default_country.setter
|
|
107
|
+
def default_country(self, country: str) -> None:
|
|
108
|
+
"""
|
|
109
|
+
Set the default country code.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
country: Country code to set
|
|
113
|
+
"""
|
|
114
|
+
self.country = country
|
|
115
|
+
os.environ('COUNTRY', country)
|
|
116
|
+
|
|
117
|
+
def validate_date_range(self, begin_date: str, end_date: str) -> bool:
|
|
118
|
+
"""
|
|
119
|
+
Validate that a date range is within acceptable bounds.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
begin_date: Begin date in YYYYMMDD format
|
|
123
|
+
end_date: End date in YYYYMMDD format
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
True if date range is valid, False otherwise
|
|
127
|
+
"""
|
|
128
|
+
try:
|
|
129
|
+
begin_int = int(begin_date)
|
|
130
|
+
end_int = int(end_date)
|
|
131
|
+
min_date = int(self.begin_date)
|
|
132
|
+
max_date = int(self.end_date)
|
|
133
|
+
|
|
134
|
+
return (min_date <= begin_int <= max_date and
|
|
135
|
+
min_date <= end_int <= max_date and
|
|
136
|
+
begin_int <= end_int)
|
|
137
|
+
except ValueError:
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
def get_error_message(self, error_key: str) -> str:
|
|
141
|
+
"""
|
|
142
|
+
Get error message by key.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
error_key: Key for the error message
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
Error message string
|
|
149
|
+
"""
|
|
150
|
+
return ERROR_MESSAGES.get(error_key, 'Unknown error')
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# Global configuration instance
|
|
154
|
+
config = CalendarConfig()
|
|
File without changes
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Frequency calculation module for periodic date operations.
|
|
3
|
+
|
|
4
|
+
This module provides base classes and implementations for calculating
|
|
5
|
+
periodic dates such as daily, weekly, monthly, quarterly, etc.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
from typing import Union, List
|
|
14
|
+
|
|
15
|
+
from ..config import (
|
|
16
|
+
DEFAULT_BEGIN_DATE,
|
|
17
|
+
DEFAULT_END_DATE,
|
|
18
|
+
DAILY_SEARCH_STEPS,
|
|
19
|
+
WEEKLY_OFFSET,
|
|
20
|
+
MONTHLY_OFFSET,
|
|
21
|
+
QUARTERLY_OFFSET,
|
|
22
|
+
YEARLY_OFFSET
|
|
23
|
+
)
|
|
24
|
+
from ..utils import dt_handle
|
|
25
|
+
from .trade_dt_handle import adjust_trade_dt, get_trade_dts, step_trade_dt
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FrequencyError(Exception):
|
|
29
|
+
"""Custom exception for frequency calculation errors."""
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class RefreshBase(ABC):
|
|
34
|
+
"""
|
|
35
|
+
获取调仓日期的基类.
|
|
36
|
+
|
|
37
|
+
This abstract base class defines the interface for all frequency
|
|
38
|
+
calculation classes including daily, weekly, monthly, quarterly, etc.
|
|
39
|
+
|
|
40
|
+
Attributes:
|
|
41
|
+
*args: Direction indicators, must be -1 or 1
|
|
42
|
+
|
|
43
|
+
Examples:
|
|
44
|
+
>>> class CustomFrequency(RefreshBase):
|
|
45
|
+
... def get(self, begin_dt, end_dt):
|
|
46
|
+
... # Custom logic here
|
|
47
|
+
... return dates
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, *args: int) -> None:
|
|
51
|
+
"""
|
|
52
|
+
Initialize frequency with direction indicators.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
*args: Direction indicators, must be -1 or 1
|
|
56
|
+
|
|
57
|
+
Raises:
|
|
58
|
+
ValueError: If args are not -1 or 1, or sum exceeds 1
|
|
59
|
+
|
|
60
|
+
Examples:
|
|
61
|
+
>>> freq = RefreshBase(1) # Forward direction
|
|
62
|
+
>>> freq = RefreshBase(-1) # Backward direction
|
|
63
|
+
>>> freq = RefreshBase(1, -1) # Both directions
|
|
64
|
+
"""
|
|
65
|
+
if not args:
|
|
66
|
+
raise ValueError("At least one argument required")
|
|
67
|
+
|
|
68
|
+
# Validate all arguments
|
|
69
|
+
for arg in args:
|
|
70
|
+
if not isinstance(arg, (int, np.integer)) or arg not in (-1, 1):
|
|
71
|
+
raise ValueError(f"Arguments must be -1 or 1 (integer), got {arg} (type: {type(arg)})")
|
|
72
|
+
|
|
73
|
+
if abs(sum(args)) > 1:
|
|
74
|
+
raise ValueError(f"Sum of arguments must not exceed 1, got {sum(args)}")
|
|
75
|
+
|
|
76
|
+
self.args = sorted(args, reverse=True)
|
|
77
|
+
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def get(self, begin_dt: Union[str, int], end_dt: Union[str, int]) -> pd.Series:
|
|
80
|
+
"""
|
|
81
|
+
Get dates within the specified range.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
begin_dt: Begin date (YYYYMMDD format or datetime)
|
|
85
|
+
end_dt: End date (YYYYMMDD format or datetime)
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
pandas Series of dates in YYYYMMDD format
|
|
89
|
+
|
|
90
|
+
Raises:
|
|
91
|
+
NotImplementedError: If not implemented by subclass
|
|
92
|
+
"""
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
@lru_cache(maxsize=512)
|
|
96
|
+
def next(self, date: Union[str, int], step: int = 1, adjust: bool = True) -> str:
|
|
97
|
+
"""
|
|
98
|
+
获取下一个频率日期.
|
|
99
|
+
|
|
100
|
+
Examples: Monthly(-1): 20180921 -> 20180928
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
date: Starting date (YYYYMMDD format or datetime)
|
|
104
|
+
step: Number of steps forward (default: 1)
|
|
105
|
+
adjust: Whether to adjust if date is exactly on a frequency boundary (default: True)
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
Next date in the class frequency (YYYYMMDD format)
|
|
109
|
+
|
|
110
|
+
Examples:
|
|
111
|
+
>>> monthly = Monthly(1)
|
|
112
|
+
>>> monthly.next('20240115') # Get next month-end
|
|
113
|
+
'20240131'
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
FrequencyError: If calculation fails or step is invalid
|
|
117
|
+
"""
|
|
118
|
+
if not isinstance(step, (int, np.integer)) or step < 1:
|
|
119
|
+
raise FrequencyError(f"Step must be a positive integer, got {step} (type: {type(step)})")
|
|
120
|
+
|
|
121
|
+
date = dt_handle(date)
|
|
122
|
+
end_dt = step_trade_dt(date, DAILY_SEARCH_STEPS)
|
|
123
|
+
df = self.get(date, end_dt).tolist()
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
if df and df[0] == date:
|
|
127
|
+
if adjust and len(df) > step:
|
|
128
|
+
return df[step]
|
|
129
|
+
elif len(df) > step:
|
|
130
|
+
return df[step]
|
|
131
|
+
|
|
132
|
+
if df and len(df) >= step:
|
|
133
|
+
return df[step - 1]
|
|
134
|
+
elif df:
|
|
135
|
+
return df[-1]
|
|
136
|
+
else:
|
|
137
|
+
raise FrequencyError(f"No frequency dates found after {date}")
|
|
138
|
+
except IndexError as e:
|
|
139
|
+
if df:
|
|
140
|
+
return df[-1]
|
|
141
|
+
raise FrequencyError(f"Cannot get next date from {date}: {e}")
|
|
142
|
+
|
|
143
|
+
@lru_cache(maxsize=512)
|
|
144
|
+
def prev(self, date: Union[str, int], step: int = 1, adjust: bool = True) -> str:
|
|
145
|
+
"""
|
|
146
|
+
获取上一个频率日期.
|
|
147
|
+
|
|
148
|
+
Examples: Monthly(-1): 20180921 -> 20180831
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
date: Starting date (YYYYMMDD format or datetime)
|
|
152
|
+
step: Number of steps backward (default: 1)
|
|
153
|
+
adjust: Whether to adjust if date is exactly on a frequency boundary (default: True)
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
Previous date in the class frequency (YYYYMMDD format)
|
|
157
|
+
|
|
158
|
+
Examples:
|
|
159
|
+
>>> monthly = Monthly(1)
|
|
160
|
+
>>> monthly.prev('20240115') # Get previous month-end
|
|
161
|
+
'20231229'
|
|
162
|
+
|
|
163
|
+
Raises:
|
|
164
|
+
FrequencyError: If calculation fails or step is invalid
|
|
165
|
+
"""
|
|
166
|
+
if not isinstance(step, (int, np.integer)) or step < 1:
|
|
167
|
+
raise FrequencyError(f"Step must be a positive integer, got {step} (type: {type(step)})")
|
|
168
|
+
|
|
169
|
+
date = dt_handle(date)
|
|
170
|
+
begin_dt = step_trade_dt(date, -DAILY_SEARCH_STEPS)
|
|
171
|
+
df = self.get(begin_dt, date).tolist()
|
|
172
|
+
|
|
173
|
+
try:
|
|
174
|
+
if df and df[-1] == date:
|
|
175
|
+
if adjust and len(df) > step:
|
|
176
|
+
return df[-step - 1]
|
|
177
|
+
elif len(df) > step:
|
|
178
|
+
return df[-step - 1]
|
|
179
|
+
|
|
180
|
+
if df and len(df) >= step:
|
|
181
|
+
return df[-step]
|
|
182
|
+
elif df:
|
|
183
|
+
return df[0]
|
|
184
|
+
else:
|
|
185
|
+
raise FrequencyError(f"No frequency dates found before {date}")
|
|
186
|
+
except IndexError as e:
|
|
187
|
+
if df:
|
|
188
|
+
return df[0]
|
|
189
|
+
raise FrequencyError(f"Cannot get previous date from {date}: {e}")
|
|
190
|
+
|
|
191
|
+
@staticmethod
|
|
192
|
+
def freq_handle(arg, df, step=1):
|
|
193
|
+
if arg == 1:
|
|
194
|
+
tmp_df = df.map(lambda x: adjust_trade_dt(x[:6] + '01', 'next'))
|
|
195
|
+
else:
|
|
196
|
+
tmp_df = df.map(lambda x: step_trade_dt(
|
|
197
|
+
str(int(x[:6]) + step) + '01', -1))
|
|
198
|
+
|
|
199
|
+
return tmp_df
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def df_handle(begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE, func=None):
|
|
203
|
+
begin_dt = dt_handle(begin_dt)
|
|
204
|
+
end_dt = dt_handle(end_dt)
|
|
205
|
+
df = get_trade_dts(begin_dt, end_dt).copy()
|
|
206
|
+
|
|
207
|
+
df = df.map(func)
|
|
208
|
+
df.drop_duplicates(inplace=True)
|
|
209
|
+
return df
|
|
210
|
+
|
|
211
|
+
def _get(self,
|
|
212
|
+
begin_dt=DEFAULT_BEGIN_DATE,
|
|
213
|
+
end_dt=DEFAULT_END_DATE,
|
|
214
|
+
func=None,
|
|
215
|
+
offset=None):
|
|
216
|
+
begin_dt, end_dt = dt_handle(begin_dt), dt_handle(end_dt)
|
|
217
|
+
df = get_trade_dts(
|
|
218
|
+
step_trade_dt(begin_dt, -1 * offset),
|
|
219
|
+
step_trade_dt(end_dt, offset)).to_frame('trade_dt')
|
|
220
|
+
df['_trade_dt'] = pd.to_datetime(df['trade_dt'])
|
|
221
|
+
df['period'] = df['_trade_dt'].map(func)
|
|
222
|
+
all_trade_dt = pd.Series(dtype=object)
|
|
223
|
+
for arg in self.args:
|
|
224
|
+
if arg == 1:
|
|
225
|
+
tmp_df = df.drop_duplicates('period', keep='first')['trade_dt']
|
|
226
|
+
else:
|
|
227
|
+
tmp_df = df.drop_duplicates('period', keep='last')['trade_dt']
|
|
228
|
+
all_trade_dt = pd.concat([all_trade_dt, tmp_df])
|
|
229
|
+
all_trade_dt.sort_values(inplace=True)
|
|
230
|
+
all_trade_dt = all_trade_dt[
|
|
231
|
+
(all_trade_dt >= begin_dt)
|
|
232
|
+
& (all_trade_dt <= end_dt)].drop_duplicates()
|
|
233
|
+
all_trade_dt.reset_index(drop=True, inplace=True)
|
|
234
|
+
return all_trade_dt
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class Daily(RefreshBase):
|
|
238
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
239
|
+
"""[get trade_dt Series with class freq]
|
|
240
|
+
|
|
241
|
+
Arguments:
|
|
242
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
243
|
+
|
|
244
|
+
Keyword Arguments:
|
|
245
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
246
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
[pd.Series] -- [trade_dt Series]
|
|
250
|
+
"""
|
|
251
|
+
return get_trade_dts(begin_dt, end_dt).copy()
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class Monthly(RefreshBase):
|
|
255
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
256
|
+
"""[get trade_dt Series with class freq]
|
|
257
|
+
|
|
258
|
+
Arguments:
|
|
259
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
260
|
+
|
|
261
|
+
Keyword Arguments:
|
|
262
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
263
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
[pd.Series] -- [trade_dt Series]
|
|
267
|
+
"""
|
|
268
|
+
def func(x):
|
|
269
|
+
return f"{x.year}{x.month}"
|
|
270
|
+
|
|
271
|
+
return self._get(
|
|
272
|
+
begin_dt=begin_dt, end_dt=end_dt, func=func, offset=MONTHLY_OFFSET)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class Weekly(RefreshBase):
|
|
276
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
277
|
+
"""[get trade_dt Series with class freq]
|
|
278
|
+
|
|
279
|
+
Arguments:
|
|
280
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
281
|
+
|
|
282
|
+
Keyword Arguments:
|
|
283
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
284
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
285
|
+
|
|
286
|
+
Returns:
|
|
287
|
+
[pd.Series] -- [trade_dt Series]
|
|
288
|
+
"""
|
|
289
|
+
def func(x):
|
|
290
|
+
tmpx = x.isocalendar()
|
|
291
|
+
return f"{tmpx[0]}{tmpx[1]}"
|
|
292
|
+
|
|
293
|
+
return self._get(
|
|
294
|
+
begin_dt=begin_dt, end_dt=end_dt, func=func, offset=WEEKLY_OFFSET)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class BiWeekly(RefreshBase):
|
|
298
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
299
|
+
"""[get trade_dt Series with class freq]
|
|
300
|
+
|
|
301
|
+
Arguments:
|
|
302
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
303
|
+
|
|
304
|
+
Keyword Arguments:
|
|
305
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
306
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
307
|
+
|
|
308
|
+
Returns:
|
|
309
|
+
[pd.Series] -- [trade_dt Series]
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
all_trade_dt = pd.Series()
|
|
313
|
+
for arg in self.args:
|
|
314
|
+
if arg == 1:
|
|
315
|
+
tmp_df = Weekly(1).get(begin_dt, end_dt)[::2]
|
|
316
|
+
else:
|
|
317
|
+
tmp_df = Weekly(-1).get(begin_dt, end_dt)[::2]
|
|
318
|
+
all_trade_dt = pd.concat([all_trade_dt, tmp_df])
|
|
319
|
+
all_trade_dt.sort_values(inplace=True)
|
|
320
|
+
all_trade_dt.drop_duplicates(inplace=True)
|
|
321
|
+
all_trade_dt.reset_index(drop=True, inplace=True)
|
|
322
|
+
return all_trade_dt
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
class Quarterly(RefreshBase):
|
|
326
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
327
|
+
"""[get trade_dt Series with class freq]
|
|
328
|
+
|
|
329
|
+
Arguments:
|
|
330
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
331
|
+
|
|
332
|
+
Keyword Arguments:
|
|
333
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
334
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
335
|
+
|
|
336
|
+
Returns:
|
|
337
|
+
[pd.Series] -- [trade_dt Series]
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
def func(x):
|
|
341
|
+
return f"{x.year}{x.quarter}"
|
|
342
|
+
|
|
343
|
+
return self._get(
|
|
344
|
+
begin_dt=begin_dt, end_dt=end_dt, func=func, offset=QUARTERLY_OFFSET)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
class Reportly(RefreshBase):
|
|
348
|
+
@staticmethod
|
|
349
|
+
def _report(x):
|
|
350
|
+
# Convert to integer for proper date comparison
|
|
351
|
+
date_int = int(x)
|
|
352
|
+
if date_int <= int(x[:4] + '0430'):
|
|
353
|
+
return str(int(x[:4]) - 1) + '11'
|
|
354
|
+
elif date_int <= int(x[:4] + '0831'):
|
|
355
|
+
return x[:4] + '05'
|
|
356
|
+
elif date_int <= int(x[:4] + '1031'):
|
|
357
|
+
return x[:4] + '09'
|
|
358
|
+
elif date_int <= int(x[:4] + '1231'):
|
|
359
|
+
return x[:4] + '11'
|
|
360
|
+
|
|
361
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
362
|
+
"""[get trade_dt Series with class freq]
|
|
363
|
+
|
|
364
|
+
Arguments:
|
|
365
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
366
|
+
|
|
367
|
+
Keyword Arguments:
|
|
368
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
369
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
370
|
+
|
|
371
|
+
Returns:
|
|
372
|
+
[pd.Series] -- [trade_dt Series]
|
|
373
|
+
"""
|
|
374
|
+
|
|
375
|
+
begin_dt, end_dt = dt_handle(begin_dt), dt_handle(end_dt)
|
|
376
|
+
df = self.df_handle(begin_dt, end_dt, self._report)
|
|
377
|
+
all_trade_dt = pd.Series()
|
|
378
|
+
for arg in self.args:
|
|
379
|
+
if arg == 1:
|
|
380
|
+
tmp_df = df.map(
|
|
381
|
+
lambda x: adjust_trade_dt(x[:6] + '01', 'next'))
|
|
382
|
+
else:
|
|
383
|
+
def neg_report(x):
|
|
384
|
+
if x[-2:] == '11':
|
|
385
|
+
return step_trade_dt(str(int(x[:4]) + 1) + '0501', -1)
|
|
386
|
+
elif x[-2:] == '09':
|
|
387
|
+
return step_trade_dt(x[:4] + '1101', -1)
|
|
388
|
+
elif x[-2:] == '05':
|
|
389
|
+
return step_trade_dt(x[:4] + '0901', -1)
|
|
390
|
+
|
|
391
|
+
tmp_df = df.map(neg_report)
|
|
392
|
+
all_trade_dt = pd.concat([all_trade_dt, tmp_df])
|
|
393
|
+
all_trade_dt.sort_values(inplace=True)
|
|
394
|
+
all_trade_dt = all_trade_dt[(all_trade_dt >= begin_dt)
|
|
395
|
+
& (all_trade_dt <= end_dt)].copy()
|
|
396
|
+
all_trade_dt.reset_index(drop=True, inplace=True)
|
|
397
|
+
return all_trade_dt
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
class Yearly(RefreshBase):
|
|
401
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
402
|
+
"""[get trade_dt Series with class freq]
|
|
403
|
+
|
|
404
|
+
Arguments:
|
|
405
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
406
|
+
|
|
407
|
+
Keyword Arguments:
|
|
408
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
409
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
410
|
+
|
|
411
|
+
Returns:
|
|
412
|
+
[pd.Series] -- [trade_dt Series]
|
|
413
|
+
"""
|
|
414
|
+
def func(x):
|
|
415
|
+
return f"{x.year}"
|
|
416
|
+
|
|
417
|
+
return self._get(
|
|
418
|
+
begin_dt=begin_dt, end_dt=end_dt, func=func, offset=YEARLY_OFFSET)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class Halfyearly(RefreshBase):
|
|
422
|
+
@staticmethod
|
|
423
|
+
def _year(x):
|
|
424
|
+
# Convert to integer for proper date comparison
|
|
425
|
+
date_int = int(x)
|
|
426
|
+
if date_int <= int(x[:4] + '0630'):
|
|
427
|
+
return x[:4] + '01'
|
|
428
|
+
elif date_int <= int(x[:4] + '1231'):
|
|
429
|
+
return x[:4] + '07'
|
|
430
|
+
|
|
431
|
+
def get(self, begin_dt=DEFAULT_BEGIN_DATE, end_dt=DEFAULT_END_DATE):
|
|
432
|
+
"""[get trade_dt Series with class freq]
|
|
433
|
+
|
|
434
|
+
Arguments:
|
|
435
|
+
RefreshBase {[cls]} -- [refreshbase]
|
|
436
|
+
|
|
437
|
+
Keyword Arguments:
|
|
438
|
+
begin_dt {str or datetime} -- [begin_dt] (default: {'19900101'})
|
|
439
|
+
end_dt {str or datetime} -- [end_dt] (default: {'20990101'})
|
|
440
|
+
|
|
441
|
+
Returns:
|
|
442
|
+
[pd.Series] -- [trade_dt Series]
|
|
443
|
+
"""
|
|
444
|
+
|
|
445
|
+
begin_dt, end_dt = dt_handle(begin_dt), dt_handle(end_dt)
|
|
446
|
+
df = self.df_handle(begin_dt, end_dt, self._year)
|
|
447
|
+
all_trade_dt = pd.Series()
|
|
448
|
+
for arg in self.args:
|
|
449
|
+
tmp_df = self.freq_handle(arg, df, 6)
|
|
450
|
+
all_trade_dt = pd.concat([all_trade_dt, tmp_df])
|
|
451
|
+
all_trade_dt.sort_values(inplace=True)
|
|
452
|
+
all_trade_dt = all_trade_dt[(all_trade_dt >= begin_dt)
|
|
453
|
+
& (all_trade_dt <= end_dt)].copy()
|
|
454
|
+
all_trade_dt.reset_index(drop=True, inplace=True)
|
|
455
|
+
return all_trade_dt
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
if __name__ == '__main__':
|
|
459
|
+
pass
|