forked from oficcejo/aiagents-stock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_source_manager.py
More file actions
379 lines (316 loc) · 13.6 KB
/
data_source_manager.py
File metadata and controls
379 lines (316 loc) · 13.6 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""
数据源管理器
实现akshare和tushare的自动切换机制
"""
import os
import pandas as pd
from datetime import datetime, timedelta
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
class DataSourceManager:
"""数据源管理器 - 实现akshare与tushare自动切换"""
def __init__(self):
self.tushare_token = os.getenv('TUSHARE_TOKEN', '')
self.tushare_available = False
self.tushare_api = None
# 初始化tushare
if self.tushare_token:
try:
import tushare as ts
ts.set_token(self.tushare_token)
self.tushare_api = ts.pro_api()
self.tushare_available = True
print("✅ Tushare数据源初始化成功")
except Exception as e:
print(f"⚠️ Tushare数据源初始化失败: {e}")
self.tushare_available = False
else:
print("ℹ️ 未配置Tushare Token,将仅使用Akshare数据源")
def get_stock_hist_data(self, symbol, start_date=None, end_date=None, adjust='qfq'):
"""
获取股票历史数据(优先akshare,失败时使用tushare)
Args:
symbol: 股票代码(6位数字)
start_date: 开始日期(格式:'20240101'或'2024-01-01')
end_date: 结束日期
adjust: 复权类型('qfq'前复权, 'hfq'后复权, ''不复权)
Returns:
DataFrame: 包含日期、开盘、收盘、最高、最低、成交量等列
"""
# 标准化日期格式
if start_date:
start_date = start_date.replace('-', '')
if end_date:
end_date = end_date.replace('-', '')
else:
end_date = datetime.now().strftime('%Y%m%d')
# 优先使用akshare
try:
import akshare as ak
print(f"[Akshare] 正在获取 {symbol} 的历史数据...")
df = ak.stock_zh_a_hist(
symbol=symbol,
period="daily",
start_date=start_date,
end_date=end_date,
adjust=adjust
)
if df is not None and not df.empty:
# 标准化列名
df = df.rename(columns={
'日期': 'date',
'开盘': 'open',
'收盘': 'close',
'最高': 'high',
'最低': 'low',
'成交量': 'volume',
'成交额': 'amount',
'振幅': 'amplitude',
'涨跌幅': 'pct_change',
'涨跌额': 'change',
'换手率': 'turnover'
})
df['date'] = pd.to_datetime(df['date'])
print(f"[Akshare] ✅ 成功获取 {len(df)} 条数据")
return df
except Exception as e:
print(f"[Akshare] ❌ 获取失败: {e}")
# akshare失败,尝试tushare
if self.tushare_available:
try:
print(f"[Tushare] 正在获取 {symbol} 的历史数据(备用数据源)...")
# 转换股票代码格式(添加市场后缀)
ts_code = self._convert_to_ts_code(symbol)
# 转换复权类型
adj_dict = {'qfq': 'qfq', 'hfq': 'hfq', '': None}
adj = adj_dict.get(adjust, 'qfq')
# 格式化日期
start = f"{start_date[:4]}-{start_date[4:6]}-{start_date[6:]}" if start_date else None
end = f"{end_date[:4]}-{end_date[4:6]}-{end_date[6:]}" if end_date else None
# 获取数据
df = self.tushare_api.daily(
ts_code=ts_code,
start_date=start_date,
end_date=end_date,
adj=adj
)
if df is not None and not df.empty:
# 标准化列名和数据格式
df = df.rename(columns={
'trade_date': 'date',
'vol': 'volume',
'amount': 'amount'
})
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values('date')
# 转换成交量单位(tushare单位是手,转换为股)
df['volume'] = df['volume'] * 100
# 转换成交额单位(tushare单位是千元,转换为元)
df['amount'] = df['amount'] * 1000
print(f"[Tushare] ✅ 成功获取 {len(df)} 条数据")
return df
except Exception as e:
print(f"[Tushare] ❌ 获取失败: {e}")
# 两个数据源都失败
print("❌ 所有数据源均获取失败")
return None
def get_stock_basic_info(self, symbol):
"""
获取股票基本信息(优先akshare,失败时使用tushare)
Args:
symbol: 股票代码
Returns:
dict: 股票基本信息
"""
info = {
"symbol": symbol,
"name": "未知",
"industry": "未知",
"market": "未知"
}
# 优先使用akshare
try:
import akshare as ak
print(f"[Akshare] 正在获取 {symbol} 的基本信息...")
stock_info = ak.stock_individual_info_em(symbol=symbol)
if stock_info is not None and not stock_info.empty:
for _, row in stock_info.iterrows():
key = row['item']
value = row['value']
if key == '股票简称':
info['name'] = value
elif key == '所处行业':
info['industry'] = value
elif key == '上市时间':
info['list_date'] = value
elif key == '总市值':
info['market_cap'] = value
elif key == '流通市值':
info['circulating_market_cap'] = value
print(f"[Akshare] ✅ 成功获取基本信息")
return info
except Exception as e:
print(f"[Akshare] ❌ 获取失败: {e}")
# akshare失败,尝试tushare
if self.tushare_available:
try:
print(f"[Tushare] 正在获取 {symbol} 的基本信息(备用数据源)...")
ts_code = self._convert_to_ts_code(symbol)
df = self.tushare_api.stock_basic(
ts_code=ts_code,
fields='ts_code,name,area,industry,market,list_date'
)
if df is not None and not df.empty:
info['name'] = df.iloc[0]['name']
info['industry'] = df.iloc[0]['industry']
info['market'] = df.iloc[0]['market']
info['list_date'] = df.iloc[0]['list_date']
print(f"[Tushare] ✅ 成功获取基本信息")
return info
except Exception as e:
print(f"[Tushare] ❌ 获取失败: {e}")
return info
def get_realtime_quotes(self, symbol):
"""
获取实时行情数据(优先akshare,失败时使用tushare)
Args:
symbol: 股票代码
Returns:
dict: 实时行情数据
"""
quotes = {}
# 优先使用akshare
try:
import akshare as ak
print(f"[Akshare] 正在获取 {symbol} 的实时行情...")
df = ak.stock_zh_a_spot_em()
stock_df = df[df['代码'] == symbol]
if not stock_df.empty:
row = stock_df.iloc[0]
quotes = {
'symbol': symbol,
'name': row['名称'],
'price': row['最新价'],
'change_percent': row['涨跌幅'],
'change': row['涨跌额'],
'volume': row['成交量'],
'amount': row['成交额'],
'high': row['最高'],
'low': row['最低'],
'open': row['今开'],
'pre_close': row['昨收']
}
print(f"[Akshare] ✅ 成功获取实时行情")
return quotes
except Exception as e:
print(f"[Akshare] ❌ 获取失败: {e}")
# akshare失败,尝试tushare
if self.tushare_available:
try:
print(f"[Tushare] 正在获取 {symbol} 的实时行情(备用数据源)...")
ts_code = self._convert_to_ts_code(symbol)
df = self.tushare_api.daily(
ts_code=ts_code,
start_date=datetime.now().strftime('%Y%m%d'),
end_date=datetime.now().strftime('%Y%m%d')
)
if df is not None and not df.empty:
row = df.iloc[0]
quotes = {
'symbol': symbol,
'price': row['close'],
'change_percent': row['pct_chg'],
'volume': row['vol'] * 100,
'amount': row['amount'] * 1000,
'high': row['high'],
'low': row['low'],
'open': row['open'],
'pre_close': row['pre_close']
}
print(f"[Tushare] ✅ 成功获取实时行情")
return quotes
except Exception as e:
print(f"[Tushare] ❌ 获取失败: {e}")
return quotes
def get_financial_data(self, symbol, report_type='income'):
"""
获取财务数据(优先akshare,失败时使用tushare)
Args:
symbol: 股票代码
report_type: 报表类型('income'利润表, 'balance'资产负债表, 'cashflow'现金流量表)
Returns:
DataFrame: 财务数据
"""
# 优先使用akshare
try:
import akshare as ak
print(f"[Akshare] 正在获取 {symbol} 的财务数据...")
if report_type == 'income':
df = ak.stock_financial_report_sina(stock=symbol, symbol="利润表")
elif report_type == 'balance':
df = ak.stock_financial_report_sina(stock=symbol, symbol="资产负债表")
elif report_type == 'cashflow':
df = ak.stock_financial_report_sina(stock=symbol, symbol="现金流量表")
else:
df = None
if df is not None and not df.empty:
print(f"[Akshare] ✅ 成功获取财务数据")
return df
except Exception as e:
print(f"[Akshare] ❌ 获取失败: {e}")
# akshare失败,尝试tushare
if self.tushare_available:
try:
print(f"[Tushare] 正在获取 {symbol} 的财务数据(备用数据源)...")
ts_code = self._convert_to_ts_code(symbol)
if report_type == 'income':
df = self.tushare_api.income(ts_code=ts_code)
elif report_type == 'balance':
df = self.tushare_api.balancesheet(ts_code=ts_code)
elif report_type == 'cashflow':
df = self.tushare_api.cashflow(ts_code=ts_code)
else:
df = None
if df is not None and not df.empty:
print(f"[Tushare] ✅ 成功获取财务数据")
return df
except Exception as e:
print(f"[Tushare] ❌ 获取失败: {e}")
return None
def _convert_to_ts_code(self, symbol):
"""
将6位股票代码转换为tushare格式(带市场后缀)
Args:
symbol: 6位股票代码
Returns:
str: tushare格式代码(如:000001.SZ)
"""
if not symbol or len(symbol) != 6:
return symbol
# 根据代码判断市场
if symbol.startswith('6'):
# 上海主板
return f"{symbol}.SH"
elif symbol.startswith('0') or symbol.startswith('3'):
# 深圳主板和创业板
return f"{symbol}.SZ"
elif symbol.startswith('8') or symbol.startswith('4'):
# 北交所
return f"{symbol}.BJ"
else:
# 默认深圳
return f"{symbol}.SZ"
def _convert_from_ts_code(self, ts_code):
"""
将tushare格式代码转换为6位代码
Args:
ts_code: tushare格式代码(如:000001.SZ)
Returns:
str: 6位股票代码
"""
if '.' in ts_code:
return ts_code.split('.')[0]
return ts_code
# 全局数据源管理器实例
data_source_manager = DataSourceManager()