-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnews_data.py
More file actions
261 lines (218 loc) · 8.28 KB
/
news_data.py
File metadata and controls
261 lines (218 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
新闻公告数据获取模块
包含新闻和公告相关的数据获取方法
"""
import pandas as pd
from typing import List, Optional, Dict, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
# 设置环境变量,确保Python使用UTF-8编码处理所有I/O
import os
os.environ['PYTHONIOENCODING'] = 'utf-8'
# 使用共享日志模块
try:
from .shared_logger import get_logger
except ImportError:
from shared_logger import get_logger
# 设置日志
logger = get_logger(__name__)
class NewsDataMixin:
"""新闻公告数据获取混入类"""
def news(self, src: str = '', start_date: str = '', end_date: str = '',
fields: List[str] = None, use_cache: bool = True) -> pd.DataFrame:
"""
获取新闻快讯(带智能缓存)
Args:
src: 新闻来源(可选)
start_date: 开始日期(格式:20240101)
end_date: 结束日期(格式:20241231)
fields: 字段列表,可选
use_cache: 是否使用缓存
Returns:
包含新闻快讯的DataFrame
"""
# 生成缓存键
symbol = f"news_{src}"
cache_key = self._get_cache_key(
data_type='news',
symbol=symbol,
start_date=start_date,
end_date=end_date,
src=src,
fields=fields
)
# 检查缓存
if use_cache:
cached_data = self._get_from_cache(cache_key)
if cached_data is not None:
return cached_data
# 默认字段
if not fields:
fields = ['datetime', 'content', 'title', 'channels', 'score']
# 从Tushare获取数据
if self.pro:
try:
df = self.pro.news(
src=src,
start_date=start_date,
end_date=end_date,
fields=','.join(fields)
)
if df.empty:
logger.error(f"❌ Tushare API返回空数据: news")
return pd.DataFrame()
# 保存到缓存
if use_cache:
self._save_to_cache(cache_key, df)
return df
except Exception as e:
logger.error(f"获取新闻快讯失败: {e}")
return pd.DataFrame()
else:
logger.error("❌ 未初始化Tushare Pro API")
return pd.DataFrame()
def notice(self, ann_id: str = '', ts_code: str = '', start_date: str = '',
end_date: str = '', fields: List[str] = None,
use_cache: bool = True) -> pd.DataFrame:
"""
获取公告(带智能缓存)
Args:
ann_id: 公告ID
ts_code: 股票代码(格式:000001.SZ)
start_date: 开始日期(格式:20240101)
end_date: 结束日期(格式:20241231)
fields: 字段列表,可选
use_cache: 是否使用缓存
Returns:
包含公告的DataFrame
"""
# 生成缓存键
symbol = f"notice_{ts_code}"
cache_key = self._get_cache_key(
data_type='notice',
symbol=symbol,
start_date=start_date,
end_date=end_date,
ann_id=ann_id,
ts_code=ts_code,
fields=fields
)
# 检查缓存
if use_cache:
cached_data = self._get_from_cache(cache_key)
if cached_data is not None:
return cached_data
# 默认字段
if not fields:
fields = ['ann_id', 'ts_code', 'ann_date', 'title', 'ann_type',
'ann_content', 'market', 'src', 'url']
# 从Tushare获取数据
if self.pro:
try:
df = self.pro.notice(
ann_id=ann_id,
ts_code=ts_code,
start_date=start_date,
end_date=end_date,
fields=','.join(fields)
)
if df.empty:
logger.error(f"❌ Tushare API返回空数据: notice")
return pd.DataFrame()
# 保存到缓存
if use_cache:
self._save_to_cache(cache_key, df)
return df
except Exception as e:
logger.error(f"获取公告失败: {e}")
return pd.DataFrame()
else:
logger.error("❌ 未初始化Tushare Pro API")
return pd.DataFrame()
def major_news(self, src: str = '', start_date: str = '', end_date: str = '',
fields: List[str] = None, use_cache: bool = True) -> pd.DataFrame:
"""
获取要闻(带智能缓存)
Args:
src: 新闻来源(可选)
start_date: 开始日期(格式:20240101)
end_date: 结束日期(格式:20241231)
fields: 字段列表,可选
use_cache: 是否使用缓存
Returns:
包含要闻的DataFrame
"""
# 生成缓存键
symbol = f"major_news_{src}"
cache_key = self._get_cache_key(
data_type='major_news',
symbol=symbol,
start_date=start_date,
end_date=end_date,
src=src,
fields=fields
)
# 检查缓存
if use_cache:
cached_data = self._get_from_cache(cache_key)
if cached_data is not None:
return cached_data
# 默认字段
if not fields:
fields = ['datetime', 'content', 'title', 'channels', 'score']
# 从Tushare获取数据
if self.pro:
try:
df = self.pro.major_news(
src=src,
start_date=start_date,
end_date=end_date,
fields=','.join(fields)
)
if df.empty:
logger.error(f"❌ Tushare API返回空数据: major_news")
return pd.DataFrame()
# 保存到缓存
if use_cache:
self._save_to_cache(cache_key, df)
return df
except Exception as e:
logger.error(f"获取要闻失败: {e}")
return pd.DataFrame()
else:
logger.error("❌ 未初始化Tushare Pro API")
return pd.DataFrame()
def notice_batch(self, ts_codes: List[str], start_date: str = '',
end_date: str = '', max_workers: int = 5) -> pd.DataFrame:
"""
批量获取公告(并行处理)
Args:
ts_codes: 股票代码列表
start_date: 开始日期(格式:20240101)
end_date: 结束日期(格式:20241231)
max_workers: 最大并行工作线程数
Returns:
包含所有公告的DataFrame
"""
all_data = []
def get_single_notice(ts_code):
return self.notice(
ts_code=ts_code,
start_date=start_date,
end_date=end_date
)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(get_single_notice, ts_code): ts_code
for ts_code in ts_codes}
for future in as_completed(futures):
ts_code = futures[future]
try:
df = future.result()
if not df.empty:
all_data.append(df)
except Exception as e:
logger.error(f"获取股票{ts_code}公告失败: {e}")
if all_data:
return pd.concat(all_data, ignore_index=True)
else:
return pd.DataFrame()