-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapi_routes.py
More file actions
2457 lines (2196 loc) · 114 KB
/
Copy pathapi_routes.py
File metadata and controls
2457 lines (2196 loc) · 114 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""API路由模块"""
from flask import jsonify, request
import hashlib
import os
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
import pandas as pd
from datetime import datetime
import json
import re
from data_fetchers import get_realtime_data, get_timeline_data, get_minute_kline, get_daily_kline, get_money_flow, get_money_flow_history, get_money_flow_realtime_kline, get_fundamental_data, get_industry_comparison, get_news_from_stock, get_guba_posts
from technical_indicators import calculate_indicators, get_comprehensive_data, get_comprehensive_data_with_indicators
from data_formatters import format_for_ai, to_json
import requests
from datetime import date, timedelta
from models import get_db, Position, SessionLocal
from db import (
get_watchlist, add_to_watchlist, remove_from_watchlist, update_watchlist_order,
get_config, set_config, get_all_configs,
get_agents, get_agent, create_agent, update_agent, delete_agent,
get_cached_analysis, save_analysis_cache,
create_debate_job, update_debate_job, get_debate_job, list_debate_jobs, cancel_debate_job, delete_debate_job
)
from ai_service import AIService
from four_lights_strategy import scan_four_lights
from overnight_strategy import scan_overnight
from market_context_service import build_market_sentiment_context
from portfolio_service import build_ai_portfolio_context
from strategy_scorer import rank_strong_stocks
from strategy_multi_select import (
build_strategy_decision_prompt,
build_strategy_multi_instruction,
build_strategy_profile,
format_strategy_brief,
)
from strategy_signal_service import (
delete_all_signal_runs,
delete_signal_run,
get_local_capital_flow_map,
list_signal_runs,
save_capital_flow_snapshots,
save_four_lights_run,
save_overnight_run,
validate_pending_signals,
)
from pipeline_feishu import (
execute_strategy_to_multi_debate,
check_pipeline_token,
feishu_webhook_send_text,
parse_feishu_message_text,
feishu_should_trigger,
handle_feishu_event_body,
verify_feishu_event_token,
run_pipeline_in_thread,
)
def register_routes(app):
"""注册所有API路由"""
@app.route('/')
def index():
"""首页 - API文档"""
response = jsonify({
'message': '股票数据API服务(新浪API)',
'version': '3.0.0',
'endpoints': {
'/api/sina/comprehensive/<code>': '获取股票综合数据(实时、分钟K线、分时、日K线)',
'/api/sina/comprehensive_with_indicators/<code>': '获取股票综合数据(包含技术指标:MA/EMA/MACD/RSI/KDJ/BOLL/OBV)',
'/api/sina/realtime/<code>': '获取实时行情数据',
'/api/sina/timeline/<code>': '获取分时数据(每分钟)',
'/api/sina/minute/<code>': '获取分钟K线数据,参数: ?scale=5&datalen=240',
'/api/sina/daily/<code>': '获取日K线数据,参数: ?count=240',
'/api/sina/money_flow/<code>': '获取今日资金流向数据',
'/api/sina/money_flow/history/<code>': '获取历史资金流向数据(日线),参数: ?days=60',
'/api/sina/money_flow/realtime/<code>': '获取实时资金流向分钟线数据,参数: ?klt=1&lmt=0',
'/api/sina/fundamental/<code>': '获取基本面数据',
'/api/sina/industry_comparison/<code>': '获取行业对比数据',
'/api/sina/for_ai/<code>': '获取格式化的股票数据,用于AI分析',
'/api/sina/for_ai_with_indicators/<code>': '获取格式化的股票数据(含技术指标),用于AI分析',
'/api/sentiment/news/<code>': '获取股票相关新闻,参数: ?days=7',
'/api/sentiment/posts/<code>': '获取股吧帖子(最新+热门),参数: ?latest=10&hot=10',
'/api/sentiment/all/<code>': '获取完整舆情数据(新闻+帖子),参数: ?days=7&latest=10&hot=10',
'/api/strategy/strong_stocks': '获取强势股(前两个交易日10:30前涨停,当前未涨停)',
'/api/strategy/four_lights/scan': 'POST 全市场四灯共振扫描并保存信号',
'/api/strategy/four_lights/history': 'GET 四灯信号历史及跨时段验证;DELETE 清空',
'/api/strategy/overnight/scan': 'POST 尾盘隔夜超短扫描并保存信号',
'/api/strategy/overnight/history': 'GET 隔夜信号历史及验证;DELETE 清空',
'/api/watchlist': '自选股管理,GET获取列表,POST添加',
'/api/watchlist/<code>': '自选股管理,DELETE删除',
'/api/config': '配置管理,GET获取所有配置,POST设置配置',
'/api/config/<key>': '配置管理,GET获取单个配置,POST设置配置',
'/api/agents': 'Agent管理,GET获取列表,POST创建',
'/api/agents/<id>': 'Agent管理,PUT更新,DELETE删除',
'/api/ai/analyze/<code>': 'AI分析股票,POST请求,body: {"agent_id": 1}',
'/api/ai/debate/start/<code>': '启动多Agent辩论任务,POST请求',
'/api/ai/debate/start_multi': '启动多选一辩论任务,POST: codes, agent_ids, decision_agent_id, analysis_rounds, debate_rounds',
'/api/portfolio/analyze': 'POST 一键分析账户、市场情绪和全部持仓',
'/api/ai/debate/status/<job_id>': '查询多Agent辩论任务状态',
'/api/ai/debate/jobs': '获取辩论任务列表,参数: ?status=active|completed|failed|canceled',
'/api/ai/debate/stop/<job_id>': '终止辩论任务,POST请求',
'/api/ai/debate/delete/<job_id>': '删除辩论任务,DELETE请求',
'/api/health': '健康检查',
'/api/pipeline/strategy_to_multi_debate': 'POST 强势股筛选→多选一辩论(需 X-Pipeline-Token)',
'/api/feishu/events': 'POST 飞书事件订阅回调(指令触发流水线,需配置 FEISHU_VERIFICATION_TOKEN)',
}
})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
@app.route('/api/health')
def health():
"""健康检查"""
return jsonify({
'status': 'ok',
'timestamp': datetime.now().isoformat(),
'service': '新浪股票API服务'
})
@app.route('/api/sina/comprehensive/<code>')
def get_sina_comprehensive(code):
"""获取股票的综合数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取综合数据,股票代码: {code_str}")
data = get_comprehensive_data(code_str)
result = to_json(data)
response = jsonify(result)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取综合数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/comprehensive_with_indicators/<code>')
def get_sina_comprehensive_with_indicators(code):
"""获取股票的综合数据(包含技术指标)"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取综合数据(含技术指标),股票代码: {code_str}")
data = get_comprehensive_data_with_indicators(code_str)
result = to_json(data)
response = jsonify(result)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取综合数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/realtime/<code>')
def get_sina_realtime(code):
"""获取实时行情数据"""
try:
code_str = str(code).strip()
# 支持sh/sz格式的代码(如sh000001用于上证指数)
if code_str.startswith(('sh', 'sz')):
# 直接使用,不需要验证6位数字
print(f"[API] 获取实时行情,股票代码: {code_str}")
data = get_realtime_data(code_str)
elif not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
else:
print(f"[API] 获取实时行情,股票代码: {code_str}")
data = get_realtime_data(code_str)
if data is None:
return jsonify({'error': '获取数据失败', 'message': '无法获取实时行情数据'}), 500
response = jsonify(data)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取实时行情失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/timeline/<code>')
def get_sina_timeline(code):
"""获取分时数据(每分钟的数据点)"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取分时数据,股票代码: {code_str}")
df = get_timeline_data(code_str)
if df is None or len(df) == 0:
return jsonify({'code': code_str, 'data': [], 'count': 0})
records = df.to_dict('records')
for record in records:
for key, value in record.items():
if pd.isna(value):
record[key] = None
elif isinstance(value, pd.Timestamp):
record[key] = value.strftime('%Y-%m-%d %H:%M:%S')
response = jsonify({'code': code_str, 'data': records, 'count': len(records)})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取分时数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/minute/<code>')
def get_sina_minute(code):
"""获取分钟K线数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
scale = int(request.args.get('scale', 5))
datalen = int(request.args.get('datalen', 240))
if scale not in [5, 15, 30, 60]:
return jsonify({'error': '参数错误', 'message': 'scale参数应为 5, 15, 30, 60 之一'}), 400
print(f"[API] 获取分钟K线,股票代码: {code_str}, scale: {scale}, datalen: {datalen}")
df = get_minute_kline(code_str, scale=scale, datalen=datalen)
if df is None or len(df) == 0:
return jsonify({'code': code_str, 'scale': scale, 'data': [], 'count': 0})
records = df.to_dict('records')
for record in records:
for key, value in record.items():
if pd.isna(value):
record[key] = None
elif isinstance(value, pd.Timestamp):
record[key] = value.strftime('%Y-%m-%d %H:%M:%S')
response = jsonify({'code': code_str, 'scale': scale, 'data': records, 'count': len(records)})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取分钟K线失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/daily/<code>')
def get_sina_daily(code):
"""获取日K线数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
count = int(request.args.get('count', 240))
print(f"[API] 获取日K线,股票代码: {code_str}, count: {count}")
df = get_daily_kline(code_str, count=count)
if df is None or len(df) == 0:
return jsonify({'code': code_str, 'data': [], 'count': 0})
records = df.to_dict('records')
for record in records:
for key, value in record.items():
if pd.isna(value):
record[key] = None
elif isinstance(value, pd.Timestamp):
record[key] = value.strftime('%Y-%m-%d')
response = jsonify({'code': code_str, 'data': records, 'count': len(records)})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取日K线失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/money_flow/<code>')
def get_sina_money_flow(code):
"""获取今日资金流向数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取资金流向,股票代码: {code_str}")
data = get_money_flow(code_str)
response = jsonify(data)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取资金流向失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/money_flow/history/<code>')
def get_sina_money_flow_history(code):
"""获取历史资金流向数据(日线)"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
days = int(request.args.get('days', 60)) # 默认60天
print(f"[API] 获取历史资金流向,股票代码: {code_str}, days: {days}")
data = get_money_flow_history(code_str, days=days)
response = jsonify({
'code': code_str,
'days': days,
'count': len(data),
'data': data
})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取历史资金流向失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/money_flow/realtime/<code>')
def get_sina_money_flow_realtime(code):
"""获取实时资金流向分钟线数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
klt = int(request.args.get('klt', 1)) # 1=1分钟,5=5分钟
lmt = int(request.args.get('lmt', 0)) # 0=获取所有数据
print(f"[API] 获取实时资金流向分钟线,股票代码: {code_str}, klt: {klt}, lmt: {lmt}")
data = get_money_flow_realtime_kline(code_str, klt=klt, lmt=lmt)
response = jsonify({
'code': code_str,
'klt': klt,
'count': len(data),
'data': data
})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取实时资金流向分钟线失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/fundamental/<code>')
def get_sina_fundamental(code):
"""获取股票的基本面数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取基本面数据,股票代码: {code_str}")
data = get_fundamental_data(code_str)
response = jsonify(data)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取基本面数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/industry_comparison/<code>')
def get_sina_industry_comparison(code):
"""获取股票的行业对比数据"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取行业对比数据,股票代码: {code_str}")
data = get_industry_comparison(code_str)
response = jsonify(data)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取行业对比数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/for_ai/<code>')
def get_sina_for_ai(code):
"""获取格式化的股票数据,用于AI分析"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取AI分析数据,股票代码: {code_str}")
data = get_comprehensive_data(code_str)
formatted = format_for_ai(data)
raw_data = {
'realtime': data['realtime'],
'timeline_count': len(data['timeline']) if data['timeline'] is not None else 0,
'minute_5_count': len(data['minute_5']) if data['minute_5'] is not None else 0,
'minute_15_count': len(data['minute_15']) if data['minute_15'] is not None else 0,
'minute_30_count': len(data['minute_30']) if data['minute_30'] is not None else 0,
'daily_count': len(data['daily']) if data['daily'] is not None else 0,
'sector_info': data.get('sector_info', []),
'money_flow': data.get('money_flow', {}),
'fundamental': data.get('fundamental', {}),
'industry_comparison': data.get('industry_comparison', {}),
}
response = jsonify({'code': code_str, 'formatted_text': formatted, 'raw_data': raw_data})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取AI分析数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
@app.route('/api/sina/for_ai_with_indicators/<code>')
def get_sina_for_ai_with_indicators(code):
"""获取格式化的股票数据(包含技术指标),用于AI分析"""
try:
code_str = str(code).strip()
if not code_str.isdigit() or len(code_str) != 6:
return jsonify({'error': '股票代码格式错误', 'message': '股票代码应为6位数字,如 000001'}), 400
print(f"[API] 获取AI分析数据(含技术指标),股票代码: {code_str}")
data = get_comprehensive_data_with_indicators(code_str)
formatted = format_for_ai(data)
raw_data = {
'realtime': data['realtime'],
'timeline_count': len(data['timeline']) if data['timeline'] is not None else 0,
'minute_5_count': len(data['minute_5']) if data['minute_5'] is not None else 0,
'minute_15_count': len(data['minute_15']) if data['minute_15'] is not None else 0,
'minute_30_count': len(data['minute_30']) if data['minute_30'] is not None else 0,
'daily_count': len(data['daily']) if data['daily'] is not None else 0,
'sector_info': data.get('sector_info', []),
'money_flow': data.get('money_flow', {}),
'fundamental': data.get('fundamental', {}),
'industry_comparison': data.get('industry_comparison', {}),
}
# 添加技术指标摘要
if data['daily'] is not None and len(data['daily']) > 0:
latest = data['daily'].iloc[-1]
indicators_summary = {}
ma_cols = [col for col in data['daily'].columns if col.startswith('MA') and not col.startswith('MACD')]
if ma_cols:
indicators_summary['MA'] = {col: float(latest[col]) for col in ma_cols if pd.notna(latest[col])}
if 'MACD_DIF' in data['daily'].columns and pd.notna(latest['MACD_DIF']):
indicators_summary['MACD'] = {
'DIF': float(latest['MACD_DIF']),
'DEA': float(latest.get('MACD_DEA', 0)) if pd.notna(latest.get('MACD_DEA')) else 0,
'MACD': float(latest.get('MACD', 0)) if pd.notna(latest.get('MACD')) else 0
}
if 'RSI14' in data['daily'].columns and pd.notna(latest['RSI14']):
indicators_summary['RSI'] = float(latest['RSI14'])
if 'KDJ_K' in data['daily'].columns and pd.notna(latest['KDJ_K']):
indicators_summary['KDJ'] = {
'K': float(latest['KDJ_K']),
'D': float(latest.get('KDJ_D', 0)) if pd.notna(latest.get('KDJ_D')) else 0,
'J': float(latest.get('KDJ_J', 0)) if pd.notna(latest.get('KDJ_J')) else 0
}
if 'BOLL_UPPER' in data['daily'].columns and pd.notna(latest['BOLL_UPPER']):
indicators_summary['BOLL'] = {
'upper': float(latest['BOLL_UPPER']),
'mid': float(latest.get('BOLL_MID', 0)) if pd.notna(latest.get('BOLL_MID')) else 0,
'lower': float(latest.get('BOLL_LOWER', 0)) if pd.notna(latest.get('BOLL_LOWER')) else 0
}
raw_data['indicators'] = indicators_summary
response = jsonify({'code': code_str, 'formatted_text': formatted, 'raw_data': raw_data})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取AI分析数据失败: {error_msg}")
return jsonify({'error': '获取数据失败', 'message': error_msg}), 500
# ==================== 舆情数据API ====================
@app.route('/api/sentiment/news/<code>')
def get_sentiment_news(code):
"""获取股票相关新闻"""
try:
code_str = str(code).strip()
days = int(request.args.get('days', 7))
news_list = get_news_from_stock(code_str, days=days)
response = jsonify({
'code': code_str,
'days': days,
'count': len(news_list),
'news': news_list
})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取新闻失败: {error_msg}")
return jsonify({'error': '获取新闻失败', 'message': error_msg}), 500
@app.route('/api/sentiment/posts/<code>')
def get_sentiment_posts(code):
"""获取股吧帖子(最新+热门)"""
try:
code_str = str(code).strip()
latest_count = int(request.args.get('latest', 10))
hot_count = int(request.args.get('hot', 10))
posts_list = get_guba_posts(code_str, latest_count=latest_count, hot_count=hot_count)
# 按类型分组
latest_posts = [p for p in posts_list if p.get('sort_type') == 'latest']
hot_posts = [p for p in posts_list if p.get('sort_type') == 'hot']
response = jsonify({
'code': code_str,
'latest_count': len(latest_posts),
'hot_count': len(hot_posts),
'total_count': len(posts_list),
'latest_posts': latest_posts,
'hot_posts': hot_posts,
'all_posts': posts_list
})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取股吧帖子失败: {error_msg}")
return jsonify({'error': '获取股吧帖子失败', 'message': error_msg}), 500
@app.route('/api/sentiment/all/<code>')
def get_sentiment_all(code):
"""获取完整舆情数据(新闻+帖子)"""
try:
code_str = str(code).strip()
days = int(request.args.get('days', 7))
latest_count = int(request.args.get('latest', 10))
hot_count = int(request.args.get('hot', 10))
# 获取新闻
news_list = get_news_from_stock(code_str, days=days)
# 获取帖子
posts_list = get_guba_posts(code_str, latest_count=latest_count, hot_count=hot_count)
# 按类型分组
latest_posts = [p for p in posts_list if p.get('sort_type') == 'latest']
hot_posts = [p for p in posts_list if p.get('sort_type') == 'hot']
response = jsonify({
'code': code_str,
'news': {
'count': len(news_list),
'days': days,
'list': news_list
},
'posts': {
'latest_count': len(latest_posts),
'hot_count': len(hot_posts),
'total_count': len(posts_list),
'latest_posts': latest_posts,
'hot_posts': hot_posts,
'all_posts': posts_list
}
})
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
except Exception as e:
error_msg = str(e)
print(f"[API] 获取舆情数据失败: {error_msg}")
return jsonify({'error': '获取舆情数据失败', 'message': error_msg}), 500
# ==================== 自选股API ====================
@app.route('/api/watchlist', methods=['GET'])
def get_watchlist_api():
"""获取自选股列表"""
db = next(get_db())
try:
items = get_watchlist(db)
return jsonify({
'success': True,
'data': [{'id': item.id, 'code': item.code, 'name': item.name, 'sort_order': item.sort_order} for item in items]
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/watchlist', methods=['POST'])
def add_watchlist_api():
"""添加自选股"""
db = next(get_db())
try:
data = request.json
code = data.get('code', '').strip()
if not code or len(code) != 6:
return jsonify({'success': False, 'error': '股票代码格式错误'}), 400
name = data.get('name', '')
item = add_to_watchlist(db, code, name)
return jsonify({
'success': True,
'data': {'id': item.id, 'code': item.code, 'name': item.name}
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/watchlist/<code>', methods=['DELETE'])
def remove_watchlist_api(code):
"""移除自选股"""
db = next(get_db())
try:
success = remove_from_watchlist(db, code)
return jsonify({'success': success})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/watchlist/order', methods=['POST'])
def update_watchlist_order_api():
"""更新自选股排序"""
db = next(get_db())
try:
data = request.json
orders = data.get('orders', []) # [{'code': '000001', 'sort_order': 0}, ...]
update_watchlist_order(db, [(item['code'], item['sort_order']) for item in orders])
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
# ==================== 配置API ====================
@app.route('/api/config', methods=['GET'])
def get_config_api():
"""获取所有配置"""
db = next(get_db())
try:
configs = get_all_configs(db)
return jsonify({'success': True, 'data': configs})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/config/<key>', methods=['GET'])
def get_config_key_api(key):
"""获取单个配置"""
db = next(get_db())
try:
value = get_config(db, key)
return jsonify({'success': True, 'data': {key: value}})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/config/<key>', methods=['POST'])
def set_config_api(key):
"""设置配置"""
db = next(get_db())
try:
data = request.json
value = data.get('value', '')
set_config(db, key, value)
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
# ==================== Agent API ====================
@app.route('/api/agents', methods=['GET'])
def get_agents_api():
"""获取所有Agent"""
db = next(get_db())
try:
enabled_only = request.args.get('enabled_only', 'false').lower() == 'true'
agents = get_agents(db, enabled_only)
return jsonify({
'success': True,
'data': [{
'id': a.id,
'name': a.name,
'type': a.type,
'prompt': a.prompt,
'enabled': a.enabled,
'ai_provider': a.ai_provider,
'model': a.model,
'sort_order': a.sort_order
} for a in agents]
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/agents', methods=['POST'])
def create_agent_api():
"""创建Agent"""
db = next(get_db())
try:
data = request.json
agent = create_agent(
db,
name=data.get('name'),
type=data.get('type'),
prompt=data.get('prompt'),
ai_provider=data.get('ai_provider'),
model=data.get('model'),
enabled=data.get('enabled', True),
sort_order=data.get('sort_order', 0)
)
return jsonify({'success': True, 'data': {'id': agent.id}})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/agents/<int:agent_id>', methods=['PUT'])
def update_agent_api(agent_id):
"""更新Agent"""
db = next(get_db())
try:
data = request.json
agent = update_agent(db, agent_id, **data)
return jsonify({'success': agent is not None, 'data': {'id': agent.id} if agent else None})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
@app.route('/api/agents/<int:agent_id>', methods=['DELETE'])
def delete_agent_api(agent_id):
"""删除Agent"""
db = next(get_db())
try:
success = delete_agent(db, agent_id)
return jsonify({'success': success})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
finally:
db.close()
# ==================== AI服务工具API ====================
@app.route('/api/ai/models', methods=['GET'])
def get_ai_models():
"""获取指定AI提供商的可用模型列表"""
try:
provider = request.args.get('provider')
api_key = request.args.get('api_key')
if not provider:
return jsonify({'success': False, 'error': '缺少provider参数'}), 400
if not api_key:
# 尝试从数据库获取
db = next(get_db())
try:
api_key_key = f'{provider}_api_key'
api_key = get_config(db, api_key_key)
finally:
db.close()
if not api_key:
return jsonify({'success': False, 'error': '未配置API Key'}), 400
models = AIService.get_models(provider, api_key)
return jsonify({
'success': True,
'data': models
})
except Exception as e:
error_msg = str(e)
print(f"[API] 获取模型列表失败: {error_msg}")
return jsonify({'success': False, 'error': error_msg}), 500
@app.route('/api/ai/test', methods=['POST'])
def test_ai_connection():
"""测试AI服务连接"""
try:
data = request.json
provider = data.get('provider')
api_key = data.get('api_key')
model = data.get('model')
if not provider or not api_key:
return jsonify({'success': False, 'error': '缺少provider或api_key参数'}), 400
result = AIService.test_connection(provider, api_key, model)
return jsonify(result)
except Exception as e:
error_msg = str(e)
print(f"[API] 测试连接失败: {error_msg}")
return jsonify({'success': False, 'error': error_msg}), 500
def _serialize_job(job):
agent_info = {}
try:
agent_info = json.loads(job.agent_ids) if job.agent_ids else {}
except Exception:
agent_info = {}
steps = []
try:
steps = json.loads(job.steps) if job.steps else []
except Exception:
steps = []
return {
'job_id': job.job_id,
'code': job.code,
'name': job.name,
'agent_ids': agent_info.get('agent_ids', []),
'analysis_rounds': agent_info.get('analysis_rounds', 3),
'debate_rounds': agent_info.get('debate_rounds', 3),
'meta': agent_info.get('meta', {}),
'status': job.status,
'progress': job.progress,
'steps': steps,
'report_md': job.report_md or '',
'error': job.error,
'created_at': job.created_at.isoformat() if job.created_at else None,
'updated_at': job.updated_at.isoformat() if job.updated_at else None,
}
def _update_debate_job(db: SessionLocal, job_id, **kwargs):
if 'steps' in kwargs and isinstance(kwargs['steps'], list):
kwargs['steps'] = json.dumps(kwargs['steps'], ensure_ascii=False)
update_debate_job(db, job_id, **kwargs)
def _is_job_canceled(db, job_id):
job = get_debate_job(db, job_id)
return True if (job and job.canceled) else False
def _run_debate_job(job_id, code_str, agent_ids, analysis_rounds, debate_rounds, override_api_key=None):
db = SessionLocal()
try:
_update_debate_job(db, job_id, status='running', progress=5)
agents = []
for agent_id in agent_ids:
agent = get_agent(db, agent_id)
if not agent or not agent.enabled:
raise ValueError(f'Agent不存在或未启用: {agent_id}')
agents.append(agent)
# 获取股票数据
print(f"[API] 获取股票数据(辩论): {code_str}")
stock_data = get_comprehensive_data_with_indicators(code_str)
formatted_data = format_for_ai(stock_data)
portfolio_context = build_ai_portfolio_context(db, code_str)
# 获取舆情数据(新闻+帖子)
try:
news_list = get_news_from_stock(code_str, days=7)[:5]
posts_list = get_guba_posts(code_str, latest_count=5, hot_count=5)
sentiment_text = "News:\n" + "\n".join([f"- {n.get('title','')}" for n in news_list]) + "\n\nPosts:\n" + "\n".join([f"- {p.get('title','')}" for p in posts_list[:10]])
except Exception as e:
sentiment_text = f"Sentiment data unavailable: {str(e)}"
default_model_map = {
'openai': 'gpt-3.5-turbo',
'deepseek': 'deepseek-chat',
'qwen': 'qwen-turbo',
'gemini': 'gemini-pro',
'siliconflow': 'Qwen/Qwen2.5-7B-Instruct',
'grok': 'grok-4-0709'
}
def resolve_agent_config(agent):
provider = agent.ai_provider or get_config(db, 'default_ai_provider', 'openai')
# 移动端可以通过override_api_key传入专属Key,优先使用;否则退回到服务器配置
api_key = override_api_key or get_config(db, f'{provider}_api_key')
if not api_key:
raise ValueError(f'未配置{provider} API Key')
model = agent.model or get_config(db, f'{provider}_model', default_model_map.get(provider, 'gpt-3.5-turbo'))
return provider, api_key, model
steps = []
analysis_memory = {agent.id: [] for agent in agents}
# 多轮分析(同一轮并行)
for round_idx in range(1, analysis_rounds + 1):
if _is_job_canceled(db, job_id):
_update_debate_job(db, job_id, status='canceled')
return
# 获取当前时间(每轮分析都更新)
current_time = datetime.now()
current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
current_time_info = f"Current Time: {current_time_str} (Weekday: {current_time.strftime('%A')})"
prompts = []
for agent in agents:
prev_analysis = "\n\n".join(analysis_memory[agent.id][-2:]) if analysis_memory[agent.id] else "None"
prompts.append((
agent,
f"{agent.prompt}\n\n"
f"{current_time_info}\n\n"
f"Stock Data:\n{formatted_data}\n\n"
f"{portfolio_context}\n\n"
f"Sentiment Data:\n{sentiment_text}\n\n"
f"Round {round_idx} Analysis:\n"
f"Build on your previous analysis and provide new insights without repetition.\n\n"
f"Previous Analysis (if any):\n{prev_analysis}\n\n"
f"Please provide your analysis in Chinese."
))
with ThreadPoolExecutor(max_workers=min(6, len(prompts))) as executor:
futures = {
executor.submit(
AIService.call_agent,
*resolve_agent_config(agent),
prompt
): agent
for agent, prompt in prompts
}
for future in as_completed(futures):
agent = futures[future]
try:
result = future.result()
except Exception as e:
result = f"[ERROR] {agent.name} analysis failed: {str(e)}"
analysis_memory[agent.id].append(result)
steps.append({
'phase': 'analysis',
'round': round_idx,
'agent_id': agent.id,
'agent_name': agent.name,
'content': result,
'timestamp': datetime.now().isoformat()
})
progress = 20 + round_idx * 10
_update_debate_job(db, job_id, steps=steps, progress=progress)
# 多轮辩论(同一轮并行)
debate_history = []
for round_idx in range(1, debate_rounds + 1):
if _is_job_canceled(db, job_id):
_update_debate_job(db, job_id, status='canceled')
return
# 获取当前时间(每轮辩论都更新)
current_time = datetime.now()
current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
current_time_info = f"Current Time: {current_time_str} (Weekday: {current_time.strftime('%A')})"
prompts = []
other_latest = "\n\n".join([
f"{a.name}:\n{analysis_memory[a.id][-1]}"
for a in agents if analysis_memory[a.id]
])
recent_debate = "\n\n".join([
f"Round {item['round']} - {item['agent_name']}:\n{item['content']}"
for item in debate_history[-min(len(debate_history), len(agents) * 2):]
]) if debate_history else "None"
for agent in agents:
prompts.append((
agent,
f"{agent.prompt}\n\n"
f"{current_time_info}\n\n"
"You are participating in a multi-agent debate.\n\n"
f"Current Stock Data:\n{formatted_data}\n\n"
f"{portfolio_context}\n\n"
f"Sentiment Data:\n{sentiment_text}\n\n"
f"Debate Round {round_idx}:\n"
"Respond with counterarguments, supporting evidence, and actionable insights.\n"
"Focus on your unique perspective and address opposing viewpoints.\n\n"
f"Other agents' latest analyses:\n{other_latest}\n\n"
f"Recent Debate History:\n{recent_debate}\n\n"
"Please provide your debate response in Chinese."
))