-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathtool.py
1930 lines (1584 loc) · 76.8 KB
/
tool.py
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
import tushare as ts
import matplotlib.pyplot as plt
import pandas as pd
import os
import random
from matplotlib.ticker import MaxNLocator
#from prettytable import PrettyTable
#from blessed import Terminal
import time
from datetime import datetime, timedelta
import numpy as np
import mplfinance as mpf
from typing import Optional
import matplotlib.font_manager as fm
from matplotlib.lines import Line2D
from typing import Union, Any
from sklearn.linear_model import LinearRegression
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# plt.rcParams['axes.unicode_minus'] = False
font_path = './fonts/SimHei.ttf'
font_prop = fm.FontProperties(fname=font_path)
tushare_token = os.getenv('TUSHARE_TOKEN')
pro = ts.pro_api(tushare_token)
# def last_month_end(date_str:str=''):
# date_obj = datetime.strptime(date_str, '%Y%m%d')
# current_month = date_obj.month
# current_year = date_obj.year
#
# if current_month == 1:
# last_month = 12
# last_year = current_year - 1
# else:
# last_month = current_month - 1
# last_year = current_year
#
# if date_obj.month != (date_obj + timedelta(days=1)).month:
# last_month_end_date = date_obj
# else:
# last_day_of_last_month = (date_obj.replace(day=1) - timedelta(days=1)).day
# last_month_end_date = datetime(last_year, last_month, last_day_of_last_month)
#
# return last_month_end_date.strftime('%Y%m%d')
def get_last_year_date(date_str: str = '') -> str:
"""
This function takes a date string in the format YYYYMMDD and returns the date string one year prior to the input date.
Args:
- date_str: string, the input date in the format YYYYMMDD
Returns:
- string, the date one year prior to the input date in the format YYYYMMDD
"""
dt = datetime.strptime(date_str, '%Y%m%d')
# To calculate the date one year ago
one_year_ago = dt - timedelta(days=365)
# To format the date as a string
one_year_ago_str = one_year_ago.strftime('%Y%m%d')
return one_year_ago_str
def get_adj_factor(stock_code: str = '', start_date: str = '', end_date: str = '') -> pd.DataFrame:
# Get stock price adjustment factors. Retrieve the stock price adjustment factors for a single stock's entire historical data or for all stocks on a single trading day.
# The input includes the stock code, start date, end date, and trading date, all in string format with the date in the YYYYMMDD format
# The return value is a dataframe containing the stock code, trading date, and adjustment factor
# ts_code str 股票代码
# adj_factor float 复权因子
"""
This function retrieves the adjusted stock prices for a given stock code and date range.
Args:
- stock_code: string, the stock code to retrieve data for
- start_date: string, the start date in the format YYYYMMDD
- end_date: string, the end date in the format YYYYMMDD
Returns:
- dataframe, a dataframe containing the stock code, trade date, and adjusted factor
This will retrieve the adjusted stock prices for the stock with code '000001.SZ' between the dates '20220101' and '20220501'.
"""
df = pro.adj_factor(**{
"ts_code": stock_code,
"trade_date": "",
"start_date": start_date,
"end_date": end_date,
"limit": "",
"offset": ""
}, fields=[
"ts_code",
"trade_date",
"adj_factor"
])
return df
def get_stock_code(stock_name: str) -> str:
# Retrieve the stock code of a given stock name. If we call get_stock_code('贵州茅台'), it will return '600519.SH'.
df = pd.read_csv('tushare_stock_basic_20230421210721.csv')
try:
code = df.loc[df.name==stock_name].ts_code.iloc[0]
return code
except:
return None
def get_stock_name_from_code(stock_code: str) -> str:
"""
Reads a local file to retrieve the stock name from a given stock code.
Args:
- stock_code (str): The code of the stock.
Returns:
- str: The stock name of the given stock code.
"""
# For example,if we call get_stock_name_from_code('600519.SH'), it will return '贵州茅台'.
df = pd.read_csv('tushare_stock_basic_20230421210721.csv')
name = df.loc[df.ts_code == stock_code].name.iloc[0]
return name
def get_stock_prices_data(stock_name: str='', start_date: str='', end_date: str='', freq:str='daily') -> pd.DataFrame:
"""
Retrieves the daily/weekly/monthly price data for a given stock code during a specific time period. get_stock_prices_data('贵州茅台','20200120','20220222','daily')
Args:
- stock_name (str)
- start_date (str): The start date in the format 'YYYYMMDD'.
- end_date (str): The end date in 'YYYYMMDD'.
- freq (str): The frequency of the price data, can be 'daily', 'weekly', or 'monthly'.
Returns:
- pd.DataFrame: A dataframe that contains the daily/weekly/monthly data. The output columns contain stock_code, trade_date, open, high, low, close, pre_close(昨天收盘价), change(涨跌额), pct_chg(涨跌幅),vol(成交量),amount(成交额)
"""
stock_code = get_stock_code(stock_name)
if freq == 'daily':
stock_data = pro.daily(**{
"ts_code": stock_code,
"trade_date": '',
"start_date": start_date,
"end_date": end_date,
"offset": "",
"limit": ""
}, fields=[
"ts_code",
"trade_date",
"open",
"high",
"low",
"close",
"pre_close",
"change",
"pct_chg",
"vol",
"amount"
])
elif freq == 'weekly':
stock_data = pro.weekly(**{
"ts_code": stock_code,
"trade_date": '',
"start_date": start_date,
"end_date": end_date,
"limit": "",
"offset": ""
}, fields=[
"ts_code",
"trade_date",
"close",
"open",
"high",
"low",
"pre_close",
"change",
"pct_chg",
"vol",
"amount"
])
elif freq == 'monthly':
stock_data = pro.monthly(**{
"ts_code": stock_code,
"trade_date": '',
"start_date": start_date,
"end_date": end_date,
"limit": "",
"offset": ""
}, fields=[
"ts_code",
"trade_date",
"close",
"open",
"high",
"low",
"pre_close",
"change",
"pct_chg",
"vol",
"amount"
])
adj_f = get_adj_factor(stock_code, start_date, end_date)
stock_data = pd.merge(stock_data, adj_f, on=['ts_code', 'trade_date'])
# Multiply the values of open, high, low, and close by their corresponding adjustment factors.
# To obtain the adjusted close price
stock_data[['open', 'high', 'low', 'close']] *= stock_data['adj_factor'].values.reshape(-1, 1)
#stock_data.rename(columns={'vol': 'volume'}, inplace=True)
df = pd.read_csv('tushare_stock_basic_20230421210721.csv')
stock_data_merged = pd.merge(stock_data, df, on='ts_code')
stock_data_merged.rename(columns={'ts_code': 'stock_code'}, inplace=True)
stock_data_merged.rename(columns={'name': 'stock_name'}, inplace=True)
stock_data_merged = stock_data_merged.sort_values(by='trade_date', ascending=True) # To sort the DataFrame by date in ascending order
return stock_data_merged
def get_stock_technical_data(stock_name: str, start_date: str, end_date: str) -> pd.DataFrame:
"""
Retrieves the daily technical data of a stock including macd turnover rate, volume, PE ratio, etc. Those technical indicators are usually plotted as subplots in a k-line chart.
Args:
stock_name (str):
start_date (str): Start date "YYYYMMDD"
end_date (str): End date "YYYYMMDD"
Returns:
pd.DataFrame: A DataFrame containing the technical data of the stock,
including various indicators such as ts_code, trade_date, close, macd_dif, macd_dea, macd, kdj_k, kdj_d, kdj_j, rsi_6, rsi_12, boll_upper, boll_mid, boll_lower, cci, turnover_rate, turnover_rate_f, volume_ratio, pe_ttm(市盈率), pb(市净率), ps_ttm, dv_ttm, total_share, float_share, free_share, total_mv, circ_mv
"""
# Technical factors
stock_code = get_stock_code(stock_name)
stock_data1 = pro.stk_factor(**{
"ts_code": stock_code,
"start_date": start_date,
"end_date": end_date,
"trade_date": '',
"limit": "",
"offset": ""
}, fields=[
"ts_code",
"trade_date",
"close",
"macd_dif",
"macd_dea",
"macd",
"kdj_k",
"kdj_d",
"kdj_j",
"rsi_6",
"rsi_12",
"rsi_24",
"boll_upper",
"boll_mid",
"boll_lower",
"cci"
])
# Trading factors
stock_data2 = pro.daily_basic(**{
"ts_code": stock_code,
"trade_date": '',
"start_date": start_date,
"end_date": end_date,
"limit": "",
"offset": ""
}, fields=[
"ts_code", #
"trade_date",
"turnover_rate",
"turnover_rate_f",
"volume_ratio",
"pe_ttm",
"pb",
"ps_ttm",
"dv_ttm",
"total_share",
"float_share",
"free_share",
"total_mv",
"circ_mv"
])
#
stock_data = pd.merge(stock_data1, stock_data2, on=['ts_code', 'trade_date'])
df = pd.read_csv('tushare_stock_basic_20230421210721.csv')
stock_data_merged = pd.merge(stock_data, df, on='ts_code')
stock_data_merged = stock_data_merged.sort_values(by='trade_date', ascending=True)
stock_data_merged.drop(['symbol'], axis=1, inplace=True)
stock_data_merged.rename(columns={'ts_code': 'stock_code'}, inplace=True)
stock_data_merged.rename(columns={'name': 'stock_name'}, inplace=True)
return stock_data_merged
def plot_stock_data(stock_data: pd.DataFrame, ax: Optional[plt.Axes] = None, figure_type: str = 'line', title_name: str ='') -> plt.Axes:
"""
This function plots stock data.
Args:
- stock_data: pandas DataFrame, the stock data to plot. The DataFrame should contain three columns:
- Column 1: trade date in 'YYYYMMDD'
- Column 2: Stock name or code (string format)
- Column 3: Index value (numeric format)
The DataFrame can be time series data or cross-sectional data. If it is time-series data, the first column represents different trade time, the second column represents the same name. For cross-sectional data, the first column is the same, the second column contains different stocks.
- ax: matplotlib Axes object, the axes to plot the data on
- figure_type: the type of figure (either 'line' or 'bar')
- title_name
Returns:
- matplotlib Axes object, the axes containing the plot
"""
index_name = stock_data.columns[2]
name_list = stock_data.iloc[:,1]
date_list = stock_data.iloc[:,0]
if name_list.nunique() == 1 and date_list.nunique() != 1:
# Time Series Data
unchanged_var = name_list.iloc[0] # stock name
x_dim = date_list # tradingdate
x_name = stock_data.columns[0]
elif name_list.nunique() != 1 and date_list.nunique() == 1:
# Cross-sectional Data
unchanged_var = date_list.iloc[0] # tradingdate
x_dim = name_list # stock name
x_name = stock_data.columns[1]
data_size = x_dim.shape[0]
start_x_dim, end_x_dim = x_dim.iloc[0], x_dim.iloc[-1]
start_y = stock_data.iloc[0, 2]
end_y = stock_data.iloc[-1, 2]
def generate_random_color():
r = random.randint(0, 255)/ 255.0
g = random.randint(0, 100)/ 255.0
b = random.randint(0, 255)/ 255.0
return (r, g, b)
color = generate_random_color()
if ax is None:
_, ax = plt.subplots()
if figure_type =='line':
#
ax.plot(x_dim, stock_data.iloc[:, 2], label = unchanged_var+'_' + index_name, color=color,linewidth=3)
#
plt.scatter(x_dim, stock_data.iloc[:, 2], color=color,s=3) # Add markers to the data points
#
#ax.scatter(x_dim, stock_data.iloc[:, 2],label = unchanged_var+'_' + index_name, color=color, s=3)
#
ax.annotate(unchanged_var + ':' + str(round(start_y, 2)) + ' @' + start_x_dim, xy=(start_x_dim, start_y),
xytext=(start_x_dim, start_y),
textcoords='data', fontsize=14,color=color, horizontalalignment='right',fontproperties=font_prop)
ax.annotate(unchanged_var + ':' + str(round(end_y, 2)) +' @' + end_x_dim, xy=(end_x_dim, end_y),
xytext=(end_x_dim, end_y),
textcoords='data', fontsize=14, color=color, horizontalalignment='left',fontproperties=font_prop)
elif figure_type == 'bar':
ax.bar(x_dim, stock_data.iloc[:, 2], label = unchanged_var + '_' + index_name, width=0.3, color=color)
ax.annotate(unchanged_var + ':' + str(round(start_y, 2)) + ' @' + start_x_dim, xy=(start_x_dim, start_y),
xytext=(start_x_dim, start_y),
textcoords='data', fontsize=14, color=color, horizontalalignment='right',fontproperties=font_prop)
ax.annotate(unchanged_var + ':' + str(round(end_y, 2)) + ' @' + end_x_dim, xy=(end_x_dim, end_y),
xytext=(end_x_dim, end_y),
textcoords='data', fontsize=14, color=color, horizontalalignment='left',fontproperties=font_prop)
plt.xticks(x_dim,rotation=45) #
ax.xaxis.set_major_locator(MaxNLocator( integer=True, prune=None, nbins=100)) #
plt.xlabel(x_name, fontproperties=font_prop,fontsize=18)
plt.ylabel(f'{index_name}', fontproperties=font_prop,fontsize=16)
ax.set_title(title_name , fontproperties=font_prop,fontsize=16)
plt.legend(prop=font_prop) # 显示图例
fig = plt.gcf()
fig.set_size_inches(18, 12)
return ax
def query_fund_Manager(Manager_name: str) -> pd.DataFrame:
# 代码fund_code,公告日期ann_date,基金经理名字name,性别gender,出生年份birth_year,学历edu,国籍nationality,开始管理日期begin_date,结束日期end_date,简历resume
"""
Retrieves information about a fund manager.
Args:
Manager_name (str): The name of the fund manager.
Returns:
df (DataFrame): A DataFrame containing the fund manager's information, including the fund codes, announcement dates,
manager's name, gender, birth year, education, nationality, start and end dates of managing funds,
and the manager's resume.
"""
df = pro.fund_manager(**{
"ts_code": "",
"ann_date": "",
"name": Manager_name,
"offset": "",
"limit": ""
}, fields=[
"ts_code",
"ann_date",
"name",
"gender",
"birth_year",
"edu",
"nationality",
"begin_date",
"end_date",
"resume"
])
#
df.rename(columns={'ts_code': 'fund_code'}, inplace=True)
# To query the fund name based on the fund code and store it in a new column called fund_name, while removing the rows where the fund name is not found
df['fund_name'] = df['fund_code'].apply(lambda x: query_fund_name_or_code('', x))
df.dropna(subset=['fund_name'], inplace=True)
df.rename(columns={'name': 'manager_name'}, inplace=True)
#
df_out = df[['fund_name','fund_code','ann_date','manager_name','begin_date','end_date']]
return df_out
# def save_stock_prices_to_csv(stock_prices: pd.DataFrame, stock_name: str, file_path: str) -> None:
#
# """
# Saves the price data of a specific stock symbol during a specific time period to a local CSV file.
#
# Args:
# - stock_prices (pd.DataFrame): A pandas dataframe that contains the daily price data for the given stock symbol during the specified time period.
# - stock_name (str): The name of the stock.
# - file_path (str): The file path where the CSV file will be saved.
#
# Returns:
# - None: The function only saves the CSV file to the specified file path.
# """
# # The function checks if the directory to save the CSV file exists and creates it if it does not exist.
# # The function then saves the price data of the specified stock symbol during the specified time period to a local CSV file with the name {stock_name}_price_data.csv in the specified file path.
#
#
# if not os.path.exists(file_path):
# os.makedirs(file_path)
#
#
# file_path = f"{file_path}{stock_name}_stock_prices.csv"
# stock_prices.to_csv(file_path, index_label='Date')
# print(f"Stock prices for {stock_name} saved to {file_path}")
def calculate_stock_index(stock_data: pd.DataFrame, index:str='close') -> pd.DataFrame:
"""
Calculate a specific index of a stock based on its price information.
Args:
stock_data (pd.DataFrame): DataFrame containing the stock's price information.
index (str, optional): The index to calculate. The available options depend on the column names in the
input stock price data. Additionally, there are two special indices: 'candle_K' and 'Cumulative_Earnings_Rate'.
Returns:
DataFrame containing the corresponding index data of the stock. In general, it includes three columns: 'trade_date', 'name', and the corresponding index value.
Besides, if index is 'candle_K', the function returns the DataFrame containing 'trade_date', 'Open', 'High', 'Low', 'Close', 'Volume','name' column.
If index is a technical index such as 'macd' or a trading index likes 'pe_ttm', the function returns the DataFrame with corresponding columns.
"""
if 'stock_name' not in stock_data.columns and 'index_name' in stock_data.columns:
stock_data.rename(columns={'index_name': 'stock_name'}, inplace=True)
#
index = index.lower()
if index=='Cumulative_Earnings_Rate' or index =='Cumulative_Earnings_Rate'.lower() :
stock_data[index] = (1 + stock_data['pct_chg'] / 100.).cumprod() - 1.
stock_data[index] = stock_data[index] * 100.
if 'stock_name' in stock_data.columns :
selected_index = stock_data[['trade_date', 'stock_name', index]].copy()
#
if 'fund_name' in stock_data.columns:
selected_index = stock_data[['trade_date', 'fund_name', index]].copy()
return selected_index
elif index == 'candle_K' or index == 'candle_K'.lower():
#tech_df = tech_df.drop(['name', 'symbol', 'industry', 'area','market','list_date','ts_code','close'], axis=1)
# Merge two DataFrames based on the 'trade_date' column.
stock_data = stock_data.rename(
columns={'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close',
'vol': 'Volume'})
selected_index = stock_data[['trade_date', 'Open', 'High', 'Low', 'Close', 'Volume','stock_name']].copy()
return selected_index
elif index =='macd':
selected_index = stock_data[['trade_date','macd','macd_dea','macd_dif']].copy()
return selected_index
elif index =='rsi':
selected_index = stock_data[['trade_date','rsi_6','rsi_12']].copy()
return selected_index
elif index =='boll':
selected_index = stock_data[['trade_date', 'boll_upper', 'boll_lower','boll_mid']].copy()
return selected_index
elif index =='kdj':
selected_index = stock_data[['trade_date', 'kdj_k', 'kdj_d','kdj_j']].copy()
return selected_index
elif index =='cci':
selected_index = stock_data[['trade_date', 'cci']].copy()
return selected_index
elif index == '换手率':
selected_index = stock_data[['trade_date', 'turnover_rate','turnover_rate_f']].copy()
return selected_index
elif index == '市值':
selected_index = stock_data[['trade_date', 'total_mv','circ_mv']].copy()
return selected_index
elif index in stock_data.columns:
stock_data = stock_data
if 'stock_name' in stock_data.columns :
selected_index = stock_data[['trade_date', 'stock_name', index]].copy()
if 'fund_name' in stock_data.columns:
selected_index = stock_data[['trade_date', 'fund_name', index]].copy()
# Except for candlestick chart and technical indicators, the remaining outputs consist of three columns: date, name, and indicator.
return selected_index
def rank_index_cross_section(stock_data: pd.DataFrame, Top_k: int = -1, ascending: bool = False) -> pd.DataFrame:
"""
Sort the cross-sectional data based on the given index.
Args:
stock_data : DataFrame containing the cross-sectional data. It should have three columns, and the last column represents the variable to be sorted.
Top_k : The number of data points to retain after sorting. (Default: -1, which retains all data points)
ascending: Whether to sort the data in ascending order or not. (Default: False)
Returns:
stock_data_selected : DataFrame containing the sorted data. It has the same structure as the input DataFrame.
"""
index = stock_data.columns[-1]
stock_data = stock_data.sort_values(by=index, ascending=ascending)
#stock_data_selected = stock_data[['trade_date','stock_name', index]].copy()
stock_data_selected = stock_data[:Top_k]
stock_data_selected = stock_data_selected.drop_duplicates(subset=['stock_name'], keep='first')
return stock_data_selected
def get_company_info(stock_name: str='') -> pd.DataFrame:
# ts_code: str 股票代码, exchange:str 交易所代码SSE上交所 SZSE深交所, chairman:str 法人代表, manager:str 总经理, secretary:str 董秘 # reg_capital:float 注册资本, setup_date:str 注册日期, province:str 所在省份 ,city:str 所在城市
# introduction:str 公司介绍, website:str 公司主页 , email:str 电子邮件, office:str 办公室 # ann_date: str 公告日期, business_scope:str 经营范围, employees:int 员工人数, main_business:str 主要业务及产品
"""
This function retrieves company information including stock code, exchange, chairman, manager, secretary,
registered capital, setup date, province, city, website, email, employees, business scope, main business,
introduction, office, and announcement date.
Args:
- stock_name (str): The name of the stock.
Returns:
- pd.DataFrame: A DataFrame that contains the company information.
"""
stock_code = get_stock_code(stock_name)
df = pro.stock_company(**{
"ts_code": stock_code,"exchange": "","status": "", "limit": "","offset": ""
}, fields=[
"ts_code","exchange","chairman", "manager","secretary", "reg_capital","setup_date", "province","city",
"website", "email","employees","business_scope","main_business","introduction","office", "ann_date"
])
en_to_cn = {
'ts_code': '股票代码',
'exchange': '交易所代码',
'chairman': '法人代表',
'manager': '总经理',
'secretary': '董秘',
'reg_capital': '注册资本',
'setup_date': '注册日期',
'province': '所在省份',
'city': '所在城市',
'introduction': '公司介绍',
'website': '公司主页',
'email': '电子邮件',
'office': '办公室',
'ann_date': '公告日期',
'business_scope': '经营范围',
'employees': '员工人数',
'main_business': '主要业务及产品'
}
df.rename(columns=en_to_cn, inplace=True)
df.insert(0, '股票名称', stock_name)
# for column in df.columns:
# print(f"[{column}]: {df[column].values[0]}")
return df
# def get_Financial_data(stock_code: str, report_date: str, financial_index: str = '' ) -> pd.DataFrame:
# # report_date的格式为"YYYYMMDD",包括"yyyy0331"为一季报,"yyyy0630"为半年报,"yyyy0930"为三季报,"yyyy1231"为年报
# # index包含: # current_ratio 流动比率 # quick_ratio 速动比率 # netprofit_margin 销售净利率 # grossprofit_margin 销售毛利率 # roe 净资产收益率 # roe_dt 净资产收益率(扣除非经常损益)
# # roa 总资产报酬率 # debt_to_assets 资产负债率 # roa_yearly 年化总资产净利率 # q_dtprofit 扣除非经常损益后的单季度净利润 # q_eps 每股收益(单季度)
# # q_netprofit_margin 销售净利率(单季度) # q_gsprofit_margin 销售毛利率(单季度) # basic_eps_yoy 基本每股收益同比增长率(%) # netprofit_yoy 归属母公司股东的净利润同比增长率(%) # q_netprofit_yoy 归属母公司股东的净利润同比增长率(%)(单季度) # q_netprofit_qoq 归属母公司股东的净利润环比增长率(%)(单季度) # equity_yoy 净资产同比增长率
# """
# Retrieves financial data for a specific stock within a given date range.
#
# Args:
# stock_code (str): The stock code or symbol of the company for which financial data is requested.
# report_date (str): The report date in the format "YYYYMMDD" .
# financial_index (str, optional): The financial indicator to be queried. If not specified, all available financial
# indicators will be included.
#
# Returns:
# pd.DataFrame: A DataFrame containing the financial data for the specified stock and date range. The DataFrame
# consists of the following columns: "stock_name",
# "trade_date" (reporting period), and the requested financial indicator(s).
#
# """
# stock_data = pro.fina_indicator(**{
# "ts_code": stock_code,
# "ann_date": "",
# "start_date": '',
# "end_date": '',
# "period": report_date,
# "update_flag": "1",
# "limit": "",
# "offset": ""
# }, fields=["ts_code","end_date", financial_index])
#
# stock_name = get_stock_name_from_code(stock_code)
# stock_data['stock_name'] = stock_name
# stock_data = stock_data.sort_values(by='end_date', ascending=True) # 按照日期升序排列
# # 把end_data列改名为trade_date
# stock_data.rename(columns={'end_date': 'trade_date'}, inplace=True)
# stock_financial_data = stock_data[['stock_name', 'trade_date', financial_index]]
# return stock_financial_data
def get_Financial_data_from_time_range(stock_name:str, start_date:str, end_date:str, financial_index:str='') -> pd.DataFrame:
# start_date='20190101',end_date='20221231',financial_index='roe', The returned data consists of the ROE values for the entire three-year period from 2019 to 2022.
# To query quarterly or annual financial report data for a specific moment, "yyyy0331"为一季报,"yyyy0630"为半年报,"yyyy0930"为三季报,"yyyy1231"为年报,例如get_Financial_data_from_time_range("600519.SH", "20190331", "20190331", "roe") means to query the return on equity (ROE) data from the first quarter of 2019,
# # current_ratio 流动比率 # quick_ratio 速动比率 # netprofit_margin 销售净利率 # grossprofit_margin 销售毛利率 # roe 净资产收益率 # roe_dt 净资产收益率(扣除非经常损益)
# roa 总资产报酬率 # debt_to_assets 资产负债率 # roa_yearly 年化总资产净利率 # q_dtprofit 扣除非经常损益后的单季度净利润 # q_eps 每股收益(单季度)
# q_netprofit_margin 销售净利率(单季度) # q_gsprofit_margin 销售毛利率(单季度) # basic_eps_yoy 基本每股收益同比增长率(%) # netprofit_yoy 归属母公司股东的净利润同比增长率(%) # q_netprofit_yoy 归属母公司股东的净利润同比增长率(%)(单季度) # q_netprofit_qoq 归属母公司股东的净利润环比增长率(%)(单季度) # equity_yoy 净资产同比增长率
"""
Retrieves the financial data for a given stock within a specified date range.
Args:
stock_name (str): The stock code.
start_date (str): The start date of the data range in the format "YYYYMMDD".
end_date (str): The end date of the data range in the format "YYYYMMDD".
financial_index (str, optional): The financial indicator to be queried.
Returns:
pd.DataFrame: A DataFrame containin financial data for the specified stock and date range.
"""
stock_code = get_stock_code(stock_name)
stock_data = pro.fina_indicator(**{
"ts_code": stock_code,
"ann_date": "",
"start_date": start_date,
"end_date": end_date,
"period": '',
"update_flag": "1",
"limit": "",
"offset": ""
}, fields=["ts_code", "end_date", financial_index])
#stock_name = get_stock_name_from_code(stock_code)
stock_data['stock_name'] = stock_name
stock_data = stock_data.sort_values(by='end_date', ascending=True) # 按照日期升序排列
# 把end_data列改名为trade_date
stock_data.rename(columns={'end_date': 'trade_date'}, inplace=True)
stock_financial_data = stock_data[['stock_name', 'trade_date', financial_index]]
return stock_financial_data
def get_GDP_data(start_quarter:str='', end_quarter:str='', index:str='gdp_yoy') -> pd.DataFrame:
# The available indicators for query include the following 9 categories: # gdp GDP累计值(亿元)# gdp_yoy 当季同比增速(%)# pi 第一产业累计值(亿元)# pi_yoy 第一产业同比增速(%)# si 第二产业累计值(亿元)# si_yoy 第二产业同比增速(%)# ti 第三产业累计值(亿元) # ti_yoy 第三产业同比增速(%)
"""
Retrieves GDP data for the chosen index and specified time period.
Args:
- start_quarter (str): The start quarter of the query, in YYYYMMDD format.
- end_quarter (str): The end quarter, in YYYYMMDD format.
- index (str): The specific GDP index to retrieve. Default is `gdp_yoy`.
Returns:
- pd.DataFrame: A pandas DataFrame with three columns: `quarter`, `country`, and the selected `index`.
"""
# The output is a DataFrame with three columns:
# the first column represents the quarter (quarter), the second column represents the country (country), and the third column represents the index (index).
df = pro.cn_gdp(**{
"q":'',
"start_q": start_quarter,
"end_q": end_quarter,
"limit": "",
"offset": ""
}, fields=[
"quarter",
"gdp",
"gdp_yoy",
"pi",
"pi_yoy",
"si",
"si_yoy",
"ti",
"ti_yoy"
])
df = df.sort_values(by='quarter', ascending=True) #
df['country'] = 'China'
df = df[['quarter', 'country', index]].copy()
return df
def get_cpi_ppi_currency_supply_data(start_month: str = '', end_month: str = '', type: str = 'cpi', index: str = '') -> pd.DataFrame:
# The query types (type) include three categories: CPI, PPI, and currency supply. Each type corresponds to different indices.
# Specifically, CPI has 12 indices, PPI has 30 indices, and currency supply has 9 indices.
# The output is a DataFrame table with three columns: the first column represents the month (month), the second column represents the country (country), and the third column represents the index (index).
# type='cpi',monthly CPI data include the following 12 categories:
# nt_val 全国当月值 # nt_yoy 全国同比(%)# nt_mom 全国环比(%)# nt_accu 全国累计值# town_val 城市当月值# town_yoy 城市同比(%)# town_mom 城市环比(%)# town_accu 城市累计值# cnt_val 农村当月值# cnt_yoy 农村同比(%)# cnt_mom 农村环比(%)# cnt_accu 农村累计值
# type = 'ppi', monthly PPI data include the following 30 categories:
# ppi_yoy PPI:全部工业品:当月同比
# ppi_mp_yoy PPI:生产资料:当月同比
# ppi_mp_qm_yoy PPI:生产资料:采掘业:当月同比
# ppi_mp_rm_yoy PPI:生产资料:原料业:当月同比
# ppi_mp_p_yoy PPI:生产资料:加工业:当月同比
# ppi_cg_yoy PPI:生活资料:当月同比
# ppi_cg_f_yoy PPI:生活资料:食品类:当月同比
# ppi_cg_c_yoy PPI:生活资料:衣着类:当月同比
# ppi_cg_adu_yoy PPI:生活资料:一般日用品类:当月同比
# ppi_cg_dcg_yoy PPI:生活资料:耐用消费品类:当月同比
# ppi_mom PPI:全部工业品:环比
# ppi_mp_mom PPI:生产资料:环比
# ppi_mp_qm_mom PPI:生产资料:采掘业:环比
# ppi_mp_rm_mom PPI:生产资料:原料业:环比
# ppi_mp_p_mom PPI:生产资料:加工业:环比
# ppi_cg_mom PPI:生活资料:环比
# ppi_cg_f_mom PPI:生活资料:食品类:环比
# ppi_cg_c_mom PPI:生活资料:衣着类:环比
# ppi_cg_adu_mom PPI:生活资料:一般日用品类:环比
# ppi_cg_dcg_mom PPI:生活资料:耐用消费品类:环比
# ppi_accu PPI:全部工业品:累计同比
# ppi_mp_accu PPI:生产资料:累计同比
# ppi_mp_qm_accu PPI:生产资料:采掘业:累计同比
# ppi_mp_rm_accu PPI:生产资料:原料业:累计同比
# ppi_mp_p_accu PPI:生产资料:加工业:累计同比
# ppi_cg_accu PPI:生活资料:累计同比
# ppi_cg_f_accu PPI:生活资料:食品类:累计同比
# ppi_cg_c_accu PPI:生活资料:衣着类:累计同比
# ppi_cg_adu_accu PPI:生活资料:一般日用品类:累计同比
# ppi_cg_dcg_accu PPI:生活资料:耐用消费品类:累计同比
# type = 'currency_supply', monthly currency supply data include the following 9 categories:
# m0 M0(亿元)# m0_yoy M0同比(%)# m0_mom M0环比(%)# m1 M1(亿元)# m1_yoy M1同比(%)# m1_mom M1环比(%)# m2 M2(亿元)# m2_yoy M2同比(%)# m2_mom M2环比(%)
"""
This function is used to retrieve China's monthly CPI (Consumer Price Index), PPI (Producer Price Index),
and monetary supply data published by the National Bureau of Statistics,
and return a DataFrame table containing month, country, and index values.
The function parameters include start month, end month, query type, and query index.
For query indexes that are not within the query range, the default index for the corresponding type is returned.
Args:
- start_month (str): start month of the query, in the format of YYYYMMDD.
- end_month (str):end month in YYYYMMDD
- type (str): required parameter, query type, including three types: cpi, ppi, and currency_supply.
- index (str): optional parameter, query index, the specific index depends on the query type.
If the query index is not within the range, the default index for the corresponding type is returned.
Returns:
- pd.DataFrame: DataFrame type, including three columns: month, country, and index value.
"""
if type == 'cpi':
df = pro.cn_cpi(**{
"m": '',
"start_m": start_month,
"end_m": end_month,
"limit": "",
"offset": ""
}, fields=[
"month", "nt_val","nt_yoy", "nt_mom","nt_accu", "town_val", "town_yoy", "town_mom",
"town_accu", "cnt_val", "cnt_yoy", "cnt_mom", "cnt_accu"])
# If the index is not within the aforementioned range, the index is set as "nt_yoy".
if index not in df.columns:
index = 'nt_yoy'
elif type == 'ppi':
df = pro.cn_ppi(**{
"m": '',
"start_m": start_month,
"end_m": end_month,
"limit": "",
"offset": ""
}, fields=[
"month", "ppi_yoy", "ppi_mp_yoy", "ppi_mp_qm_yoy", "ppi_mp_rm_yoy", "ppi_mp_p_yoy", "ppi_cg_yoy",
"ppi_cg_f_yoy", "ppi_cg_c_yoy", "ppi_cg_adu_yoy", "ppi_cg_dcg_yoy",
"ppi_mom", "ppi_mp_mom", "ppi_mp_qm_mom", "ppi_mp_rm_mom", "ppi_mp_p_mom", "ppi_cg_mom", "ppi_cg_f_mom",
"ppi_cg_c_mom", "ppi_cg_adu_mom", "ppi_cg_dcg_mom",
"ppi_accu", "ppi_mp_accu", "ppi_mp_qm_accu", "ppi_mp_rm_accu", "ppi_mp_p_accu", "ppi_cg_accu",
"ppi_cg_f_accu", "ppi_cg_c_accu", "ppi_cg_adu_accu", "ppi_cg_dcg_accu"
])
if index not in df.columns:
index = 'ppi_yoy'
elif type == 'currency_supply':
df = pro.cn_m(**{
"m": '',
"start_m": start_month,
"end_m": end_month,
"limit": "",
"offset": ""
}, fields=[
"month", "m0", "m0_yoy","m0_mom", "m1",
"m1_yoy", "m1_mom", "m2", "m2_yoy", "m2_mom"])
if index not in df.columns:
index = 'm2_yoy'
df = df.sort_values(by='month', ascending=True) #
df['country'] = 'China'
df = df[['month', 'country', index]].copy()
return df
def predict_next_value(df: pd.DataFrame, pred_index: str = 'nt_yoy', pred_num:int = 1. ) -> pd.DataFrame:
"""
Predict the next n values of a specific column in the DataFrame using linear regression.
Parameters:
df (pandas.DataFrame): The input DataFrame.
pred_index (str): The name of the column to predict.
pred_num (int): The number of future values to predict.
Returns:
pandas.DataFrame: The DataFrame with the predicted values appended to the specified column
and other columns filled as pred+index.
"""
input_array = df[pred_index].values
# Convert the input array into the desired format.
x = np.array(range(len(input_array))).reshape(-1, 1)
y = input_array.reshape(-1, 1)
# Train a linear regression model.
model = LinearRegression()
model.fit(x, y)
# Predict the future n values.
next_indices = np.array(range(len(input_array), len(input_array) + pred_num)).reshape(-1, 1)
predicted_values = model.predict(next_indices).flatten()
for i, value in enumerate(predicted_values, 1):
row_data = {pred_index: value}
for other_col in df.columns:
if other_col != pred_index:
row_data[other_col] = 'pred' + str(i)
df = df.append(row_data, ignore_index=True)
# Return the updated DataFrame
return df
def get_latest_new_from_web(src: str = 'sina') -> pd.DataFrame:
# 新浪财经 sina 获取新浪财经实时资讯
# 同花顺 10jqka 同花顺财经新闻
# 东方财富 eastmoney 东方财富财经新闻
# 云财经 yuncaijing 云财经新闻
"""
Retrieves the latest news data from major news websites, including Sina Finance, 10jqka, Eastmoney, and Yuncaijing.
Args:
src (str): The name of the news website. Default is 'sina'. Optional parameters include: 'sina' for Sina Finance,
'10jqka' for 10jqka, 'eastmoney' for Eastmoney, and 'yuncaijing' for Yuncaijing.
Returns:
pd.DataFrame: A DataFrame containing the news data, including two columns for date/time and content.
"""
df = pro.news(**{
"start_date": '',
"end_date": '',
"src": src,
"limit": "",
"offset": ""
}, fields=[
"datetime",
"content",
])
df = df.apply(lambda x: '[' + x.name + ']' + ': ' + x.astype(str))
return df
# def show_dynamic_table(df: pd.DataFrame) -> None:
# '''
# This function displays a dynamic table in the terminal window, where each row of the input DataFrame is shown one by one.
# Arguments:
# df: A Pandas DataFrame containing the data to be displayed in the dynamic table.
#
# Returns: None. This function does not return anything.
#
# '''
#
# return df
# # table = PrettyTable(df.columns.tolist(),align='l')
#
# # 将 DataFrame 的数据添加到表格中
# # for row in df.itertuples(index=False):
# # table.add_row(row)
#
# # 初始化终端
# # term = Terminal()
# #
# # # 在终端窗口中滚动显示表格
# # with term.fullscreen():
# # with term.cbreak():
# # print(term.clear())
# # with term.location(0, 0):
# # # 将表格分解为多行,并遍历每一行
# # lines = str(table).split('\n')
# # for i, line in enumerate(lines):
# # with term.location(0, i):
# # print(line)
# # time.sleep(1)
# #
# # while True:
# # # 读取输入
# # key = term.inkey(timeout=0.1)
# #
# # # 如果收到q键,则退出
# # if key.lower() == 'q':
# # break
def get_index_constituent(index_name: str = '', start_date:str ='', end_date:str ='') -> pd.DataFrame:
"""
Query the constituent stocks of basic index (中证500) or a specified SW (申万) industry index
args:
index_name: the name of the index.