siat 2.14.2__py3-none-any.whl → 3.0.0__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.
siat/stock.py CHANGED
@@ -20,7 +20,7 @@ from siat.common import *
20
20
  from siat.translate import *
21
21
  from siat.grafix import *
22
22
  from siat.security_prices import *
23
-
23
+ from siat.security_price2 import *
24
24
 
25
25
  #==============================================================================
26
26
  import matplotlib.pyplot as plt
@@ -468,7 +468,7 @@ def stock_price(ticker,fromdate,todate,adj=False, \
468
468
  df=get_price(ticker,fromdate,todate,adj=adj,source=source)
469
469
 
470
470
  if not (df is None):
471
- tickername=codetranslate(ticker)
471
+ tickername=ticker_name(ticker)
472
472
 
473
473
  import datetime; today = datetime.date.today()
474
474
  lang=check_language()
@@ -527,7 +527,7 @@ if __name__ =="__main__":
527
527
  allind=all_calculate(pricedf,"AAPL",'2023-1-1','2023-6-16')
528
528
  list(allind)
529
529
 
530
- def all_calculate(pricedf,ticker1,fromdate,todate):
530
+ def all_calculate(pricedf,ticker1,fromdate,todate,ticker_type='auto'):
531
531
  """
532
532
  功能:单纯计算所有基于证券价格的指标
533
533
 
@@ -546,13 +546,13 @@ def all_calculate(pricedf,ticker1,fromdate,todate):
546
546
 
547
547
  #加入价格波动指标
548
548
  #df1b=price_volatility2(df1a,ticker1,fromdate,todate,graph=False)
549
- df1b=price_volatility2(pricedf,ticker1,fromdate,todate,graph=False)
549
+ df1b=price_volatility2(pricedf,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type)
550
550
 
551
551
  #加入收益率波动指标
552
- df1c=ret_volatility2(pricedf,ticker1,fromdate,todate,graph=False)
552
+ df1c=ret_volatility2(pricedf,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type)
553
553
 
554
554
  #加入收益率下偏标准差指标
555
- df1d=ret_lpsd2(pricedf,ticker1,fromdate,todate,graph=False)
555
+ df1d=ret_lpsd2(pricedf,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type)
556
556
 
557
557
  # 横向拼接合并
558
558
  result=pd.concat([df1a,df1b,df1c,df1d],axis=1,join='outer')
@@ -605,14 +605,16 @@ def security_indicator(ticker,indicator,fromdate,todate, \
605
605
  zeroline=False, \
606
606
  average_value=False, \
607
607
  datatag=False,power=0,graph=True,source='auto',
608
- mark_top=1,mark_bottom=1,mark_end=True):
608
+ mark_top=True,mark_bottom=True,mark_end=True,ticker_type='auto'):
609
609
  """
610
610
  功能:单只证券的全部指标
611
611
  """
612
612
  fromdate1=date_adjust(fromdate,adjust=-365*3)
613
613
 
614
- from siat.security_prices import get_price
615
- pricedf=get_price(ticker,fromdate1,todate,source=source)
614
+ from siat.security_price2 import get_price_1ticker_mixed
615
+ #pricedf=get_prices_all(ticker,fromdate1,todate,source=source,ticker_type=ticker_type)
616
+ pricedf,found=get_price_1ticker_mixed(ticker=ticker,fromdate=fromdate1, \
617
+ todate=todate,source=source,ticker_type=ticker_type)
616
618
  if pricedf is None:
617
619
  print(" #Error(security_indicator): security info not found for",ticker)
618
620
  return None
@@ -625,7 +627,7 @@ def security_indicator(ticker,indicator,fromdate,todate, \
625
627
  fromdate_pd=pd.to_datetime(fromdate)
626
628
  tmp_df=pricedf[pricedf.index >= fromdate_pd]
627
629
  if len(tmp_df)==0:
628
- print(" #Error(security_indicator): no record from",fromdate,"for",ticker)
630
+ print(" #Warning(security_indicator): zero record exists from",fromdate,"for",ticker)
629
631
  return None
630
632
 
631
633
  erdf=all_calculate(pricedf,ticker,fromdate,todate)
@@ -646,18 +648,20 @@ def security_indicator(ticker,indicator,fromdate,todate, \
646
648
  if not graph:
647
649
  return erdf3
648
650
 
649
- #titletxt=texttranslate("证券指标运动趋势:")+codetranslate(ticker)
650
- titletxt=texttranslate("证券趋势分析:")+codetranslate(ticker)
651
- import datetime; today = datetime.date.today()
652
- footnote=texttranslate("数据来源:新浪/东方财富/stooq/雅虎财经,")+str(today)
651
+ #titletxt=texttranslate("证券指标运动趋势:")+ticker_name(ticker)
652
+ titletxt=texttranslate("证券趋势分析:")+ticker_name(ticker,ticker_type=ticker_type)
653
+ import datetime; todaydt = datetime.date.today()
654
+ footnote=texttranslate("数据来源:新浪/东方财富/stooq/雅虎财经,")+str(todaydt)
653
655
  collabel=ectranslate(indicator)
654
656
 
655
657
  ylabeltxt=ectranslate(indicator)
656
- tickersplit=ticker.split('.')
657
- if (len(tickersplit) > 1) and (indicator == 'Close'):
658
- if tickersplit[1].upper() in ['M','B']:
659
- ylabeltxt="stooq_MB" #特殊标志,告知绘图函数不显示某些标记
660
-
658
+ try:
659
+ tickersplit=ticker.split('.')
660
+ if (len(tickersplit) > 1) and (indicator == 'Close'):
661
+ if tickersplit[1].upper() in ['M','B']:
662
+ ylabeltxt="stooq_MB" #特殊标志,告知绘图函数不显示某些标记
663
+ except: pass
664
+
661
665
  if 'Ret%' in indicator:
662
666
  zeroline=True
663
667
 
@@ -669,7 +673,7 @@ def security_indicator(ticker,indicator,fromdate,todate, \
669
673
 
670
674
 
671
675
  def stock_ret(ticker,fromdate,todate,rtype="Daily Ret%", \
672
- datatag=False,power=0,graph=True,source='auto'):
676
+ datatag=False,power=0,graph=True,source='auto',ticker_type='auto'):
673
677
  """
674
678
  功能:绘制证券收益率折线图。
675
679
  输入:证券代码ticker;开始日期fromdate,结束日期todate;收益率类型type;
@@ -681,10 +685,13 @@ def stock_ret(ticker,fromdate,todate,rtype="Daily Ret%", \
681
685
  fromdate1=date_adjust(fromdate, -732)
682
686
 
683
687
  #抓取证券价格
684
- adj=False
685
- if 'Adj' in rtype: adj=True
686
- from siat.security_prices import get_price
687
- pricedf=get_price(ticker,fromdate1,todate,adj=adj,source=source)
688
+ adj=False; adjust=''
689
+ if 'Adj' in rtype: adj=True; adjust='qfq'
690
+ from siat.security_price2 import get_price_1ticker_mixed
691
+ #pricedf=get_price(ticker,fromdate1,todate,adj=adj,source=source)
692
+ pricedf,found=get_price_1ticker_mixed(ticker=ticker,fromdate=fromdate1, \
693
+ todate=todate,adjust=adjust, \
694
+ source=source,ticker_type=ticker_type)
688
695
  if pricedf is None:
689
696
  print(" #Error(stock_ret): failed to find price info for",ticker,fromdate,todate)
690
697
  return None
@@ -715,11 +722,12 @@ def stock_ret(ticker,fromdate,todate,rtype="Daily Ret%", \
715
722
  print(" #Error(stock_ret):only support return types of",colnames)
716
723
  return
717
724
 
718
- titletxt=texttranslate("证券指标运动趋势:")+codetranslate(ticker)
719
- import datetime; today = datetime.date.today()
720
- footnote=texttranslate("数据来源:新浪/东方财富/stooq/雅虎财经,")+str(today)
725
+ import datetime; todaydt = datetime.date.today()
726
+ footnote=texttranslate("数据来源:综合新浪/东方财富/stooq/雅虎财经,")+str(todaydt)
721
727
  collabel=ectranslate(rtype)
722
728
  ylabeltxt=ectranslate(rtype)
729
+ titletxt=texttranslate("证券趋势分析:")+ticker_name(ticker,ticker_type=ticker_type)+",收益率"
730
+
723
731
  pltdf=erdf[erdf.index >= fromdate]
724
732
  plot_line(pltdf,rtype,collabel,ylabeltxt,titletxt,footnote,datatag=datatag, \
725
733
  power=power,zeroline=True)
@@ -758,7 +766,7 @@ def security_mindicators(ticker,measures,fromdate,todate, \
758
766
  date_range=False,date_freq=False, \
759
767
  annotate=False,annotate_value=False, \
760
768
  source='auto', \
761
- mark_top=1,mark_bottom=1):
769
+ mark_top=True,mark_bottom=True,ticker_type='auto'):
762
770
  """
763
771
  功能:单个证券,多个指标对比
764
772
  date_range=False:指定开始结束日期绘图
@@ -781,8 +789,10 @@ def security_mindicators(ticker,measures,fromdate,todate, \
781
789
  measures=[measures]
782
790
 
783
791
  try:
784
- from siat.security_prices import get_price
785
- pricedf=get_price(ticker,fromdate1,todate,source=source)
792
+ from siat.security_price2 import get_price_1ticker_mixed
793
+ #pricedf=get_price(ticker,fromdate1,todate,source=source)
794
+ pricedf,found=get_price_1ticker_mixed(ticker=ticker,fromdate=fromdate1, \
795
+ todate=todate,source=source,ticker_type=ticker_type)
786
796
  except:
787
797
  print(" #Error(security_mindicators): price info not found for",ticker)
788
798
  return None
@@ -793,7 +803,7 @@ def security_mindicators(ticker,measures,fromdate,todate, \
793
803
  print(" #Warning(security_mindicators): price info unavailable for",ticker)
794
804
  return None
795
805
 
796
- df=all_calculate(pricedf,ticker,fromdate,todate)
806
+ df=all_calculate(pricedf,ticker,fromdate,todate,ticker_type=ticker_type)
797
807
 
798
808
  # 检查指标是否存在
799
809
  colList=list(df)
@@ -807,8 +817,8 @@ def security_mindicators(ticker,measures,fromdate,todate, \
807
817
  df1.rename(columns={c:ectranslate(c)},inplace=True)
808
818
 
809
819
  y_label='证券指标'
810
- import datetime; today = datetime.date.today()
811
- x_label="数据来源:综合新浪/东方财富/stooq/雅虎财经,"+str(today)
820
+ import datetime; todaydt = datetime.date.today()
821
+ x_label="数据来源:综合新浪/东方财富/stooq/yahoo,"+str(todaydt)
812
822
 
813
823
  axhline_value=0
814
824
  axhline_label=''
@@ -817,7 +827,7 @@ def security_mindicators(ticker,measures,fromdate,todate, \
817
827
  axhline_value=0
818
828
  axhline_label='指标零线'
819
829
  break
820
- title_txt="证券趋势对比:"+codetranslate(ticker)
830
+ title_txt="证券趋势分析:"+ticker_name(ticker,ticker_type=ticker_type)
821
831
  """
822
832
  draw_lines(df1,y_label,x_label,axhline_value,axhline_label,title_txt, \
823
833
  data_label=False,resample_freq='H',smooth=smooth,loc=loc,annotate=annotate)
@@ -875,7 +885,7 @@ def stock_price_volatility(ticker,fromdate,todate,type="Weekly Price Volatility"
875
885
  print(" #Error(stock_price_volatility):only support price risk types of",colnames)
876
886
  return
877
887
 
878
- titletxt=texttranslate("证券价格波动风险走势图:")+codetranslate(ticker)
888
+ titletxt=texttranslate("证券价格波动风险走势图:")+ticker_name(ticker)
879
889
  import datetime; today = datetime.date.today()
880
890
  footnote=texttranslate("数据来源:新浪/东方财富/stooq,")+str(today)
881
891
  collabel=ectranslate(type)
@@ -898,7 +908,9 @@ if __name__ =="__main__":
898
908
  pv=stock_price_volatility("000002.SZ","2019-1-1","2020-3-16","Annual Exp Price Volatility")
899
909
 
900
910
  #==============================================================================
901
- def price_volatility2(pricedf,ticker,fromdate,todate,type="Weekly Price Volatility",datatag=False,power=4,graph=True):
911
+ def price_volatility2(pricedf,ticker,fromdate,todate, \
912
+ type="Weekly Price Volatility",datatag=False, \
913
+ power=4,graph=True,ticker_type='auto'):
902
914
  """
903
915
  功能:绘制证券价格波动风险折线图。与函数price_volatility的唯一区别是不抓取股价。
904
916
  输入:股价数据集pricedf;证券代码ticker;开始日期fromdate,结束日期todate;期间类型type;
@@ -930,9 +942,9 @@ def price_volatility2(pricedf,ticker,fromdate,todate,type="Weekly Price Volatili
930
942
  print(" #Error(price_volatility2):only support price risk types of",colnames)
931
943
  return
932
944
 
933
- titletxt=texttranslate("证券价格波动风险走势图:")+codetranslate(ticker)
934
- import datetime; today = datetime.date.today()
935
- footnote=texttranslate("数据来源:新浪/东方财富/stooq,")+str(today)
945
+ titletxt=texttranslate("证券趋势分析:")+ticker_name(ticker,ticker_type=ticker_type)+",价格波动风险"
946
+ import datetime; todaydt = datetime.date.today()
947
+ footnote=texttranslate("数据来源:综合新浪/东方财富/stooq/yahoo,")+str(todaydt)
936
948
  collabel=ectranslate(type)
937
949
  ylabeltxt=ectranslate(type)
938
950
  pltdf=erdf[erdf.index >= fromdate]
@@ -989,7 +1001,7 @@ def stock_ret_volatility(ticker,fromdate,todate,type="Weekly Ret Volatility%",da
989
1001
  print(" #Error(stock_ret_volatility),only support return risk types of",colnames)
990
1002
  return
991
1003
 
992
- titletxt=texttranslate("证券收益率波动风险走势图:")+codetranslate(ticker)
1004
+ titletxt=texttranslate("证券收益率波动风险走势图:")+ticker_name(ticker)
993
1005
  import datetime; today = datetime.date.today()
994
1006
  footnote=texttranslate("数据来源:新浪/东方财富/stooq,")+str(today)
995
1007
  collabel=ectranslate(type)
@@ -1013,7 +1025,9 @@ if __name__ =="__main__":
1013
1025
 
1014
1026
 
1015
1027
  #==============================================================================
1016
- def ret_volatility2(retdf,ticker,fromdate,todate,type="Weekly Ret Volatility%",datatag=False,power=4,graph=True):
1028
+ def ret_volatility2(retdf,ticker,fromdate,todate, \
1029
+ type="Weekly Ret Volatility%",datatag=False, \
1030
+ power=4,graph=True,ticker_type='auto'):
1017
1031
  """
1018
1032
  功能:绘制证券收益率波动风险折线图。与函数ret_volatility的唯一区别是不抓取股价。
1019
1033
  输入:股价数据集pricedf;证券代码ticker;开始日期fromdate,结束日期todate;期间类型type;
@@ -1047,9 +1061,9 @@ def ret_volatility2(retdf,ticker,fromdate,todate,type="Weekly Ret Volatility%",d
1047
1061
  print(" #Error(ret_volatility2): only support return risk types of",colnames)
1048
1062
  return
1049
1063
 
1050
- titletxt=texttranslate("证券收益率波动风险走势图:")+codetranslate(ticker)
1051
- import datetime; today = datetime.date.today()
1052
- footnote=texttranslate("数据来源:新浪/东方财富/stooq,")+str(today)
1064
+ titletxt=texttranslate("证券趋势分析:")+ticker_name(ticker,ticker_type=ticker_type)+",收益率波动风险"
1065
+ import datetime; todaydt = datetime.date.today()
1066
+ footnote=texttranslate("数据来源:综合新浪/东方财富/stooq/yahoo,")+str(todaydt)
1053
1067
  collabel=ectranslate(type)
1054
1068
  ylabeltxt=ectranslate(type)
1055
1069
  pltdf=erdf[erdf.index >= fromdate]
@@ -1106,7 +1120,7 @@ def ret_lpsd(ticker,fromdate,todate,type="Weekly Ret Volatility%",datatag=False,
1106
1120
  print(" #Error(ret_lpsd): only support return risk types of",colnames)
1107
1121
  return
1108
1122
 
1109
- titletxt=texttranslate("证券收益率波动损失风险走势图:")+codetranslate(ticker)
1123
+ titletxt=texttranslate("证券收益率波动损失风险走势图:")+ticker_name(ticker)
1110
1124
  import datetime; today = datetime.date.today()
1111
1125
  footnote=texttranslate("数据来源:新浪/东方财富/stooq,")+str(today)
1112
1126
  collabel=ectranslate(type)
@@ -1129,7 +1143,9 @@ if __name__ =="__main__":
1129
1143
  pv=ret_lpsd("000002.SZ","2019-1-1","2020-3-16","Annual Exp Ret Volatility%")
1130
1144
 
1131
1145
  #==============================================================================
1132
- def ret_lpsd2(retdf,ticker,fromdate,todate,rtype="Weekly Ret Volatility%",datatag=False,power=4,graph=True):
1146
+ def ret_lpsd2(retdf,ticker,fromdate,todate, \
1147
+ rtype="Weekly Ret Volatility%",datatag=False, \
1148
+ power=4,graph=True,ticker_type='auto'):
1133
1149
  """
1134
1150
  功能:绘制证券收益率波动损失风险折线图。与函数ret_lpsd的唯一区别是不抓取股价。
1135
1151
  输入:股价数据集pricedf;证券代码ticker;开始日期fromdate,结束日期todate;期间类型type;
@@ -1162,9 +1178,9 @@ def ret_lpsd2(retdf,ticker,fromdate,todate,rtype="Weekly Ret Volatility%",datata
1162
1178
  print(" #Error(ret_lpsd2): only support return risk types of",colnames)
1163
1179
  return
1164
1180
 
1165
- titletxt=texttranslate("证券收益率波动损失风险走势图:")+codetranslate(ticker)
1166
- import datetime; today = datetime.date.today()
1167
- footnote=texttranslate("数据来源:新浪/东方财富/stooq,")+str(today)
1181
+ titletxt=texttranslate("证券趋势分析:")+ticker_name(ticker,ticker_type=ticker_type)+"波动损失风险"
1182
+ import datetime; todaydt = datetime.date.today()
1183
+ footnote=texttranslate("数据来源:综合新浪/东方财富/stooq/yahoo,")+str(todaydt)
1168
1184
  collabel=ectranslate(rtype)
1169
1185
  ylabeltxt=ectranslate(rtype)
1170
1186
  pltdf=erdf[erdf.index >= fromdate]
@@ -1185,7 +1201,9 @@ if __name__ =="__main__":
1185
1201
  pv=price_lpsd2(df,"000002.SZ","2019-1-1","2020-3-16","Annual Price Volatility")
1186
1202
  pv=price_lpsd2(df,"000002.SZ","2019-1-1","2020-3-16","Annual Exp Price Volatility")
1187
1203
  #==============================================================================
1188
- def comp_1security_2measures(df,measure1,measure2,twinx=False,loc1='upper left',loc2='lower left',graph=True):
1204
+ def comp_1security_2measures(df,measure1,measure2,twinx=False, \
1205
+ loc1='upper left',loc2='lower left', \
1206
+ graph=True,ticker_type='auto'):
1189
1207
  """
1190
1208
  功能:对比绘制一只证券两个指标的折线图。
1191
1209
  输入:证券指标数据集df;行情类别measure1/2。
@@ -1220,16 +1238,12 @@ def comp_1security_2measures(df,measure1,measure2,twinx=False,loc1='upper left',
1220
1238
  label2=ectranslate(measure2)
1221
1239
  ylabeltxt=""
1222
1240
 
1223
- lang=check_language()
1224
- if lang == 'English':
1225
- titletxt="Security Trend: "+codetranslate(ticker)
1226
- else:
1227
- titletxt=texttranslate("证券指标走势图:")+codetranslate(ticker)
1228
- import datetime; today = datetime.date.today()
1229
- if lang == 'English':
1230
- footnote="Source: sina/eastmoney/stooq, "+str(today)
1231
- else:
1232
- footnote=texttranslate("数据来源:sina/eastmoney/stooq,")+str(today)
1241
+ tname=ticker_name(ticker,ticker_type=ticker_type)
1242
+ titletxt=text_lang("证券趋势分析:","Security Trend: ")+tname
1243
+
1244
+ import datetime; todaydt = datetime.date.today()
1245
+ footnote1=text_lang("数据来源:综合新浪/东方财富/stooq/yahoo,","Source: integrating sina/eastmoney/stooq/yahoo, ")
1246
+ footnote=footnote1+str(todaydt)
1233
1247
 
1234
1248
  #绘图
1235
1249
  plot_line2(df,ticker,measure1,label1,df,ticker,measure2,label2, \
@@ -1247,7 +1261,9 @@ if __name__ =="__main__":
1247
1261
  df=stock_ret(ticker,fromdate,todate,graph=False)
1248
1262
  comp_1security_2measures(df,measure1,measure2)
1249
1263
  #==============================================================================
1250
- def comp_2securities_1measure(df1,df2,measure,twinx=False,loc1='upper left',loc2='lower left',graph=True):
1264
+ def comp_2securities_1measure(df1,df2,measure,twinx=False,loc1='upper left', \
1265
+ loc2='lower left',graph=True, \
1266
+ ticker_type=['auto','auto']):
1251
1267
  """
1252
1268
  功能:对比绘制两只证券的相同指标折线图。
1253
1269
  输入:指标数据集df1/2;证券代码ticker1/2;指标类别measure。
@@ -1286,17 +1302,15 @@ def comp_2securities_1measure(df1,df2,measure,twinx=False,loc1='upper left',loc2
1286
1302
  label=ectranslate(measure)
1287
1303
  ylabeltxt=ectranslate(measure)
1288
1304
 
1289
- lang=check_language()
1290
- if lang == 'English':
1291
- titletxt="Security Trend: "+codetranslate(ticker1)+" vs "+codetranslate(ticker2)
1292
- else:
1293
- titletxt=texttranslate("证券指标走势对比:")+codetranslate(ticker1)+" vs "+codetranslate(ticker2)
1305
+ tname1=ticker_name(ticker1,ticker_type=ticker_type[0])
1306
+ tname2=ticker_name(ticker2,ticker_type=ticker_type[1])
1307
+
1308
+ titletxt1=text_lang("证券趋势分析:","Security Trend: ")
1309
+ titletxt=titletxt1+tname1+" vs "+tname2
1294
1310
 
1295
- import datetime; today = datetime.date.today()
1296
- if lang == 'English':
1297
- footnote=texttranslate("Source: sina/eastmoney/stooq,")+str(today)
1298
- else:
1299
- footnote=texttranslate("数据来源:sina/eastmoney/stooq,")+str(today)
1311
+ import datetime; todaydt = datetime.date.today()
1312
+ footnote1=text_lang("数据来源:综合/东方财富/stooq/yahoo,","Source: integrating sina/eastmoney/stooq/yahoo,")
1313
+ footnote=footnote1+str(todaydt)+"统计"
1300
1314
 
1301
1315
  plot_line2(df1,ticker1,measure,label,df2,ticker2,measure,label, \
1302
1316
  ylabeltxt,titletxt,footnote,zeroline=zeroline,twinx=twinx, \
@@ -1315,7 +1329,8 @@ if __name__ =="__main__":
1315
1329
  comp_2securities_1measure(df1,df2,measure)
1316
1330
  #==============================================================================
1317
1331
  def compare_security(tickers,measures,fromdate,todate,twinx=False, \
1318
- loc1='best',loc2='lower left',graph=True,source='auto'):
1332
+ loc1='best',loc2='lower left',graph=True,source='auto', \
1333
+ ticker_type='auto'):
1319
1334
  """
1320
1335
  功能:函数克隆compare_stock
1321
1336
  """
@@ -1324,12 +1339,14 @@ def compare_security(tickers,measures,fromdate,todate,twinx=False, \
1324
1339
  tickers=upper_ticker(tickers)
1325
1340
  result=compare_stock(tickers=tickers,measures=measures, \
1326
1341
  fromdate=fromdate,todate=todate,twinx=twinx, \
1327
- loc1=loc1,loc2=loc2,graph=graph,source=source)
1342
+ loc1=loc1,loc2=loc2,graph=graph,source=source, \
1343
+ ticker_type=ticker_type)
1328
1344
  return result
1329
1345
 
1330
1346
  #==============================================================================
1331
1347
  def compare_stock(tickers,measures,fromdate,todate,twinx=False, \
1332
- loc1='best',loc2='lower left',graph=True,source='auto'):
1348
+ loc1='best',loc2='lower left',graph=True,source='auto', \
1349
+ ticker_type='auto'):
1333
1350
  """
1334
1351
  功能:对比绘制折线图:一只证券的两种测度,或两只证券的同一个测度。
1335
1352
  输入:
@@ -1347,7 +1364,7 @@ def compare_stock(tickers,measures,fromdate,todate,twinx=False, \
1347
1364
  #调试开关
1348
1365
  DEBUG=False
1349
1366
  # 应对导入失灵的函数
1350
- from siat.security_prices import upper_ticker
1367
+ from siat.common import upper_ticker
1351
1368
  tickers=upper_ticker(tickers)
1352
1369
 
1353
1370
  #判断证券代码个数
@@ -1383,24 +1400,25 @@ def compare_stock(tickers,measures,fromdate,todate,twinx=False, \
1383
1400
  #是否单一证券代码+两个测度指标
1384
1401
  if (security_num == 1) and (measure_num >= 2):
1385
1402
  #证券ticker1:抓取行情,并计算其各种期间的收益率
1386
- df1a=stock_ret(ticker1,fromdate,todate,graph=False,source=source)
1403
+ df1a=stock_ret(ticker1,fromdate,todate,graph=False,source=source,ticker_type=ticker_type)
1387
1404
  if df1a is None: return None,None
1388
1405
  if DEBUG: print("compare|df1a first date:",df1a.index[0])
1389
1406
  #加入价格波动指标
1390
- df1b=price_volatility2(df1a,ticker1,fromdate,todate,graph=False)
1407
+ df1b=price_volatility2(df1a,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type)
1391
1408
  if DEBUG: print("compare|df1b first date:",df1b.index[0])
1392
1409
  #加入收益率波动指标
1393
- df1c=ret_volatility2(df1b,ticker1,fromdate,todate,graph=False)
1410
+ df1c=ret_volatility2(df1b,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type)
1394
1411
  if DEBUG: print("compare|df1c first date:",df1c.index[0])
1395
1412
  #加入收益率下偏标准差指标
1396
- df1d=ret_lpsd2(df1c,ticker1,fromdate,todate,graph=False)
1413
+ df1d=ret_lpsd2(df1c,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type)
1397
1414
  if DEBUG: print("compare|df1d first date:",df1d.index[0])
1398
1415
 
1399
1416
  #去掉开始日期以前的数据
1400
1417
  pltdf1=df1d[df1d.index >= fromdate]
1401
1418
  #绘制单个证券的双指标对比图
1402
1419
  if graph:
1403
- comp_1security_2measures(pltdf1,measure1,measure2,twinx=twinx,loc1=loc1,loc2=loc2,graph=graph)
1420
+ comp_1security_2measures(pltdf1,measure1,measure2,twinx=twinx, \
1421
+ loc1=loc1,loc2=loc2,graph=graph,ticker_type=ticker_type)
1404
1422
 
1405
1423
  try:
1406
1424
  result1=pltdf1[[measure1]]
@@ -1412,30 +1430,42 @@ def compare_stock(tickers,measures,fromdate,todate,twinx=False, \
1412
1430
  return result1,None
1413
1431
 
1414
1432
  elif (security_num >= 2) and (measure_num >= 1):
1415
- #双证券+单个测度指标
1433
+ #双证券+单个测度指标
1434
+ #解析ticker_type
1435
+ if isinstance(ticker_type,str):
1436
+ ticker_type1=ticker_type2=ticker_type
1437
+ if isinstance(ticker_type,list) and len(ticker_type)==1:
1438
+ ticker_type1=ticker_type2=ticker_type[0]
1439
+ if isinstance(ticker_type,list) and len(ticker_type) > 1:
1440
+ ticker_type1=ticker_type[0]
1441
+ ticker_type2=ticker_type[1]
1442
+ ticker_type_list=[ticker_type1,ticker_type2]
1443
+
1416
1444
  #证券ticker1:抓取行情,并计算其各种期间的收益率
1417
- df1a=stock_ret(ticker1,fromdate,todate,graph=False,source=source)
1445
+ df1a=stock_ret(ticker1,fromdate,todate,graph=False,source=source,ticker_type=ticker_type1)
1418
1446
  if df1a is None: return None,None
1419
1447
  #加入价格波动指标
1420
- df1b=price_volatility2(df1a,ticker1,fromdate,todate,graph=False)
1448
+ df1b=price_volatility2(df1a,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type1)
1421
1449
  #加入收益率波动指标
1422
- df1c=ret_volatility2(df1b,ticker1,fromdate,todate,graph=False)
1450
+ df1c=ret_volatility2(df1b,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type1)
1423
1451
  #加入收益率下偏标准差指标
1424
- df1d=ret_lpsd2(df1c,ticker1,fromdate,todate,graph=False)
1452
+ df1d=ret_lpsd2(df1c,ticker1,fromdate,todate,graph=False,ticker_type=ticker_type1)
1425
1453
  #去掉开始日期以前的数据
1426
1454
  pltdf1=df1d[df1d.index >= fromdate]
1427
1455
 
1428
1456
  #证券ticker2:
1429
- df2a=stock_ret(ticker2,fromdate,todate,graph=False,source=source)
1457
+ df2a=stock_ret(ticker2,fromdate,todate,graph=False,source=source,ticker_type=ticker_type2)
1430
1458
  if df2a is None: return None,None
1431
- df2b=price_volatility2(df2a,ticker2,fromdate,todate,graph=False)
1432
- df2c=ret_volatility2(df2b,ticker2,fromdate,todate,graph=False)
1433
- df2d=ret_lpsd2(df2c,ticker2,fromdate,todate,graph=False)
1459
+ df2b=price_volatility2(df2a,ticker2,fromdate,todate,graph=False,ticker_type=ticker_type2)
1460
+ df2c=ret_volatility2(df2b,ticker2,fromdate,todate,graph=False,ticker_type=ticker_type2)
1461
+ df2d=ret_lpsd2(df2c,ticker2,fromdate,todate,graph=False,ticker_type=ticker_type2)
1434
1462
  pltdf2=df2d[df2d.index >= fromdate]
1435
1463
 
1436
1464
  #绘制双证券单指标对比图
1437
1465
  if graph:
1438
- comp_2securities_1measure(pltdf1,pltdf2,measure1,twinx=twinx,loc1=loc1,loc2=loc2,graph=graph)
1466
+ comp_2securities_1measure(pltdf1,pltdf2,measure1,twinx=twinx, \
1467
+ loc1=loc1,loc2=loc2,graph=graph, \
1468
+ ticker_type=ticker_type_list)
1439
1469
 
1440
1470
  try:
1441
1471
  result1=pltdf1[[measure1]]
@@ -1504,7 +1534,8 @@ def compare_msecurity(tickers,measure,start,end, \
1504
1534
  annotate=False,annotate_value=False, \
1505
1535
  smooth=True, \
1506
1536
  source='auto', \
1507
- mark_top=1,mark_bottom=1,mark_end=False):
1537
+ mark_top=True,mark_bottom=True,mark_end=False, \
1538
+ ticker_type='auto'):
1508
1539
  """
1509
1540
  功能:比较并绘制多条证券指标曲线(多于2条),个数可为双数或单数
1510
1541
  注意:
@@ -1524,7 +1555,7 @@ def compare_msecurity(tickers,measure,start,end, \
1524
1555
 
1525
1556
  """
1526
1557
  # 应对导入失灵的函数
1527
- from siat.security_prices import upper_ticker
1558
+ from siat.common import upper_ticker
1528
1559
  tickers=upper_ticker(tickers)
1529
1560
  # 去掉重复代码:有必要,重复代码将导致后续处理出错KeyError: 0!
1530
1561
  tickers=list(set(tickers))
@@ -1553,11 +1584,22 @@ def compare_msecurity(tickers,measure,start,end, \
1553
1584
  import pandas as pd
1554
1585
  from functools import reduce
1555
1586
 
1587
+ #预处理ticker_type成为列表ticker_type_list
1588
+ if isinstance(ticker_type,str):
1589
+ ticker_type_list=[ticker_type] * len(tickers)
1590
+ if isinstance(ticker_type,list):
1591
+ ticker_type_list=ticker_type
1592
+ if len(ticker_type_list) < len(tickers): #延续最后项的ticker_type
1593
+ ticker_type_list=ticker_type_list+[ticker_type_list[-1]]*(len(tickers)-len(ticker_type_list))
1594
+
1556
1595
  dfs=pd.DataFrame()
1557
1596
  for t in tickers:
1558
1597
  print(" Looking security info for",t,'...')
1598
+ pos=tickers.index(t)
1599
+ tt=ticker_type_list[pos]
1600
+
1559
1601
  with HiddenPrints():
1560
- df_tmp=security_indicator(t,measure,start,end,graph=False,source=source)
1602
+ df_tmp=security_indicator(t,measure,start,end,graph=False,source=source,ticker_type=tt)
1561
1603
  if df_tmp is None:
1562
1604
  print(" #Warning(compare_msecurity): security info not found for",t)
1563
1605
  continue
@@ -1566,7 +1608,7 @@ def compare_msecurity(tickers,measure,start,end, \
1566
1608
  continue
1567
1609
 
1568
1610
  df_tmp1=pd.DataFrame(df_tmp[measure])
1569
- df_tmp1.rename(columns={measure:codetranslate(t)},inplace=True)
1611
+ df_tmp1.rename(columns={measure:ticker_name(t,tt)},inplace=True)
1570
1612
  if len(dfs)==0:
1571
1613
  dfs=df_tmp1
1572
1614
  else:
@@ -1580,87 +1622,6 @@ def compare_msecurity(tickers,measure,start,end, \
1580
1622
  return None
1581
1623
 
1582
1624
  dfs.sort_index(ascending=True,inplace=True)
1583
-
1584
- """
1585
- loopn=int(len(tickers)/2)
1586
- colname=''
1587
- for i in range(0,loopn):
1588
- pair=tickers[i*2:i*2+2]
1589
- #print(i,pair)
1590
- with HiddenPrints():
1591
- dfi=compare_security(pair,measure,start,end,graph=False)
1592
-
1593
- dfi1=dfi[0]
1594
- if dfi1 is None:
1595
- print(" #Warning(compare_msecurity): security info not found for either of",pair)
1596
- continue
1597
-
1598
- if colname == '':
1599
- try:
1600
- colname=list(dfi1)[0]
1601
- except:
1602
- print(" #Warning(compare_msecurity): security prices unavailable for either of",pair)
1603
- continue
1604
-
1605
- try:
1606
- dfi1.rename(columns={colname:codetranslate(tickers[i*2])},inplace=True)
1607
- except:
1608
- print(" #Error(compare_msecurity): info not found for",pair[0])
1609
- return None
1610
-
1611
- dfi2=dfi[1]
1612
- if dfi2 is None:
1613
- print(" #Warning(compare_msecurity): info not found for",pair[1])
1614
-
1615
- try:
1616
- dfi2.rename(columns={colname:codetranslate(tickers[i*2+1])},inplace=True)
1617
- except:
1618
- print(" #Error(compare_msecurity): info not found for",pair[1])
1619
- return None
1620
-
1621
- # 去掉时区信息,避免合并中的日期时区冲突问题
1622
- import pandas as pd
1623
- dfi1.index = pd.to_datetime(dfi1.index)
1624
- dfi1.index = dfi1.index.tz_localize(None)
1625
- dfi2.index = pd.to_datetime(dfi2.index)
1626
- dfi2.index = dfi2.index.tz_localize(None)
1627
-
1628
- if len(dfs) == 0:
1629
- dflist=[dfi1,dfi2]
1630
- else:
1631
- dflist=[dfs,dfi1,dfi2]
1632
- dfs=reduce(lambda left,right:pd.merge(left,right,how='outer',left_index=True,right_index=True),dflist)
1633
-
1634
- #判断是否偶数even
1635
- if (num % 2) == 0:
1636
- even=True
1637
- else:
1638
- even=False
1639
- i=loopn
1640
- if not even: #非偶数
1641
- pair=[tickers[num-1],tickers[num-1]]
1642
- with HiddenPrints():
1643
- dfi=compare_security(pair,measure,start,end,graph=False)
1644
-
1645
- dfi1=dfi[0]
1646
- if dfi1 is None:
1647
- print(" #Warning(compare_msecurity): info not found for",pair[0])
1648
-
1649
- try:
1650
- #dfi1.rename(columns={colname:codetranslate(tickers[i*2])},inplace=True)
1651
- dfi1.rename(columns={colname:codetranslate(tickers[-1])},inplace=True)
1652
- except:
1653
- print(" #Error(compare_msecurity): info not found for",pair[0])
1654
- return None
1655
-
1656
- # 去掉时区信息,避免合并中的日期时区冲突问题
1657
- import pandas as pd
1658
- dfi1.index = pd.to_datetime(dfi1.index)
1659
- dfi1.index = dfi1.index.tz_localize(None)
1660
-
1661
- dflist=[dfs,dfi1]
1662
- dfs=reduce(lambda left,right:pd.merge(left,right,how='outer',left_index=True,right_index=True),dflist)
1663
- """
1664
1625
 
1665
1626
  # 若不绘图则返回原始数据
1666
1627
  if not graph:
@@ -1673,181 +1634,24 @@ def compare_msecurity(tickers,measure,start,end, \
1673
1634
  if tickersplit[1].upper() in ['M','B']:
1674
1635
  #y_label='指标'
1675
1636
  y_label=''
1676
-
1677
- import datetime; today = datetime.date.today()
1678
1637
 
1679
- lang=check_language()
1680
- if lang == 'English':
1681
- x_label="Source: sina/stooq/yahoo, "+str(today)
1682
- title_txt="Trend Analysis"
1683
- else:
1684
- x_label="数据来源: 综合新浪/东方财富/雅虎财经/stooq/FRED/OECD,"+str(today)
1685
- #title_txt="比较多只证券产品的指标走势"
1686
- #title_txt="趋势分析"
1687
- title_txt="证券趋势分析:"+y_label
1688
- if preprocess == 'scaling' and scaling_option == 'change%':
1689
- title_txt="证券涨跌趋势分析:"+y_label
1638
+ x_label1cn="数据来源: 综合新浪/东方财富/stooq/yahoo等,"
1639
+ x_label1en="Source: integrating sina/stooq/yahoo, "
1640
+ x_label1=text_lang(x_label1cn,x_label1en)
1641
+ import datetime; todaydt = datetime.date.today()
1642
+ x_label=x_label1+str(todaydt)
1643
+
1644
+ title_txt1=text_lang("证券趋势分析:","Trend Analysis: ")
1645
+ title_txt=title_txt1+y_label
1646
+ if preprocess == 'scaling' and scaling_option == 'change%':
1647
+ title_txt2=text_lang(",涨跌幅度",", Changes")
1648
+ title_txt=title_txt+title_txt2
1649
+
1690
1650
 
1691
1651
  # 标准化处理
1692
1652
  dfs2,axhline_label,x_label,y_label,plus_sign=df_preprocess(dfs,measure, \
1693
- axhline_label=axhline_label,x_label=x_label,y_label=y_label,lang=lang, \
1653
+ axhline_label=axhline_label,x_label=x_label,y_label=y_label, \
1694
1654
  preprocess=preprocess,scaling_option=scaling_option)
1695
-
1696
- """
1697
- preprocess1=preprocess.lower()
1698
- preplist=['standardize','normalize','logarithm','scaling']
1699
- if preprocess1 in preplist:
1700
- dfs2=dfs.copy(deep=True)
1701
-
1702
- collist=list(dfs2)
1703
- meanlist=[]
1704
- for c in collist:
1705
-
1706
- # 去掉缺失值
1707
- #dfs2[c].dropna(inplace=True)
1708
-
1709
- if preprocess1 == 'standardize':
1710
- cmean=dfs2[c].mean()
1711
- cstd=dfs2[c].std()
1712
- dfs2[c]=dfs2[c].apply(lambda x: (x-cmean)/cstd)
1713
-
1714
- if preprocess1 == 'normalize':
1715
- cmax=dfs2[c].max()
1716
- cmin=dfs2[c].min()
1717
- dfs2[c]=dfs2[c].apply(lambda x: (x-cmin)/(cmax-cmin))
1718
-
1719
- if preprocess1 == 'logarithm':
1720
- import numpy as np
1721
- dfs2[c]=dfs2[c].apply(lambda x: np.log(x) if x>0 else (0 if x==0 else -np.log(-x)))
1722
-
1723
- if preprocess1 == 'scaling':
1724
- scalinglist=['mean','min','start','percentage','change%']
1725
- if not (scaling_option in scalinglist):
1726
- print(" #Error(compare_msecurity): invalid scaling option",scaling_option)
1727
- print(" Valid scaling option:",scalinglist)
1728
- return None
1729
- if scaling_option == 'mean':
1730
- cmean=dfs2[c].mean() #使用均值
1731
- if lang == 'English':
1732
- scalingOptionText='mean value'
1733
- else:
1734
- scalingOptionText='均值'
1735
- if scaling_option == 'min':
1736
- cmean=dfs2[c].min() #使用最小值
1737
- if lang == 'English':
1738
- scalingOptionText='min value'
1739
- else:
1740
- scalingOptionText='最小值'
1741
- #if scaling_option == 'start':
1742
- if scaling_option in ['start','percentage','change%']:
1743
- # 从头寻找第一个非空数值
1744
- import numpy as np
1745
- for n in range(0,len(dfs2)):
1746
- if np.isnan(dfs2[c][n]):
1747
- continue
1748
- else:
1749
- cmean=dfs2[c][n] #使用第一个非空值
1750
- break
1751
-
1752
- if lang == 'English':
1753
- scalingOptionText='starting value'
1754
- else:
1755
- scalingOptionText='起点值'
1756
-
1757
- meanlist=meanlist+[cmean]
1758
-
1759
- #print(cmean,cstd,dfs2[c])
1760
-
1761
- if (preprocess1 == 'scaling') and ('Exp Ret' not in measure):
1762
- # 加上后一个条件是为了防止出现division by zero错误
1763
- if len(meanlist)==0:
1764
- return None
1765
-
1766
- if scaling_option not in ['percentage','change%']:
1767
- meanlistmin=min(meanlist)
1768
- meanlist2= [x / meanlistmin for x in meanlist]
1769
-
1770
- for c in collist:
1771
- pos=collist.index(c)
1772
- cfactor=meanlist2[pos]
1773
- #dfs2[c]=dfs2[c].apply(lambda x: x/cfactor)
1774
- dfs2[c]=dfs2[c].apply(lambda x: x/abs(cfactor))
1775
- elif scaling_option == 'percentage':
1776
- for c in collist:
1777
- pos=collist.index(c)
1778
- cfactor=meanlist[pos]
1779
- #dfs2[c]=dfs2[c].apply(lambda x: round(x/cfactor*100,2))
1780
- dfs2[c]=dfs2[c].apply(lambda x: round(x/abs(cfactor)*100,2))
1781
- elif scaling_option == 'change%':
1782
- plus_sign=True
1783
- for c in collist:
1784
- pos=collist.index(c)
1785
- cfactor=meanlist[pos]
1786
- dfs2[c]=dfs2[c].apply(lambda x: round((x/cfactor-1)*100,2))
1787
-
1788
-
1789
- if lang == 'English':
1790
- if preprocess1 == 'standardize':
1791
- std_notes="Note: for ease of comparison, data are standardized "
1792
- measure_suffix='(standardized)'
1793
- if preprocess1 == 'normalize':
1794
- std_notes="Note: for ease of comparison, data are normalized"
1795
- measure_suffix='(normalized)'
1796
- if preprocess1 == 'logarithm':
1797
- std_notes="Note: for ease of comparison, data are logarithmed"
1798
- measure_suffix='(logarithmed)'
1799
- if preprocess1 == 'scaling':
1800
- if scaling_option == 'mean':
1801
- std_notes="Note: for ease of comparison, data are scaled by mean value"
1802
- measure_suffix='(scaling by mean)'
1803
- elif scaling_option == 'min':
1804
- std_notes="Note: for ease of comparison, data are scaled by min value"
1805
- measure_suffix='(scaling by min)'
1806
- elif scaling_option == 'start':
1807
- std_notes="Note: for ease of comparison, data are scaled by starting value"
1808
- measure_suffix='(scaling by start)'
1809
- elif scaling_option == 'percentage':
1810
- std_notes="Note: for ease of comparison, data are in percentage of starting value"
1811
- measure_suffix='(in prcentage%)'
1812
- elif scaling_option == 'change%':
1813
- std_notes="Note: for ease of comparison, data are in change % of starting value"
1814
- measure_suffix='(change %)'
1815
- else:
1816
- if preprocess1 == 'standardize':
1817
- std_notes="注意:为突出变化趋势,对数据进行了标准化处理"
1818
- measure_suffix='(标准化处理后)'
1819
- if preprocess1 == 'normalize':
1820
- std_notes="注意:为突出变化趋势,对数据进行了归一化处理"
1821
- measure_suffix='(归一化处理后)'
1822
- if preprocess1 == 'logarithm':
1823
- std_notes="注意:为突出变化趋势,对数据进行了对数处理"
1824
- measure_suffix='(对数处理后)'
1825
- if preprocess1 == 'scaling':
1826
- if scaling_option == 'mean':
1827
- std_notes="注意:为突出变化趋势,按均值对原始数据进行了比例缩放"
1828
- measure_suffix='(按均值比例缩放后,非原值)'
1829
- elif scaling_option == 'min':
1830
- std_notes="注意:为突出变化趋势,按最小值对原始数据进行了比例缩放"
1831
- measure_suffix='(按最小值比例缩放后,非原值)'
1832
- elif scaling_option == 'start':
1833
- std_notes="注意:为突出变化趋势,按起点值对原始数据进行了比例缩放"
1834
- measure_suffix='(按起点值比例缩放后,非原值)'
1835
- elif scaling_option == 'percentage':
1836
- std_notes="注释:为突出变化趋势,期间起点数值=100%,其他数值为相对百分比"
1837
- measure_suffix='(相对百分数%)'
1838
- elif scaling_option == 'change%':
1839
- std_notes="注释:为突出变化趋势,图中数值为相对期间起点的增减百分比"
1840
- measure_suffix='(增/减%)'
1841
- axhline_label='零线' #可以在security_trend中使用critical_value选项指定水平线位置,默认0
1842
- #axhline_value=0
1843
-
1844
- if 'Exp Ret' not in measure:
1845
- x_label=std_notes+'\n'+x_label
1846
- y_label=y_label+measure_suffix
1847
-
1848
- else:
1849
- dfs2=dfs
1850
- """
1851
1655
 
1852
1656
  # 填充非交易日的缺失值,使得绘制的曲线连续
1853
1657
  dfs2.fillna(axis=0,method='ffill',inplace=True)
@@ -1863,10 +1667,7 @@ def compare_msecurity(tickers,measure,start,end, \
1863
1667
  for c in colList:
1864
1668
  if 'Exp Ret%' in c:
1865
1669
  dfs2.loc[dfs2[dfs2.index==index1].index.tolist(),c]=0
1866
- """
1867
- # 翻译证券名称
1868
- dfs2.rename(columns={c:codetranslate(c)},inplace=True)
1869
- """
1670
+
1870
1671
  draw_lines(dfs2,y_label,x_label,axhline_value,axhline_label,title_txt, \
1871
1672
  data_label=False,resample_freq='H',smooth=smooth,linewidth=linewidth,loc=loc, \
1872
1673
  annotate=annotate,annotate_value=annotate_value,plus_sign=plus_sign, \
@@ -2006,7 +1807,8 @@ def stock_Kline(ticker,start='default',end='default',volume=True,style='China',m
2006
1807
  return df
2007
1808
 
2008
1809
 
2009
- def candlestick(stkcd,fromdate,todate,volume=True,style='China',mav=[5,10]):
1810
+ def candlestick(stkcd,fromdate,todate,volume=True,style='China',mav=[5,10], \
1811
+ ticker_type='auto'):
2010
1812
  """
2011
1813
  功能:绘制证券价格K线图。
2012
1814
  输入:证券代码ticker;开始日期fromdate,结束日期todate;
@@ -2016,6 +1818,7 @@ def candlestick(stkcd,fromdate,todate,volume=True,style='China',mav=[5,10]):
2016
1818
  输出:绘制证券价格蜡烛图线图
2017
1819
  返回:证券价格数据表
2018
1820
  """
1821
+
2019
1822
  #找出mav的最长天数
2020
1823
  mav_max=0
2021
1824
  for mm in mav:
@@ -2063,53 +1866,39 @@ def candlestick(stkcd,fromdate,todate,volume=True,style='China',mav=[5,10]):
2063
1866
  rc=mpfrc)
2064
1867
 
2065
1868
  #抓取证券价格
2066
- from siat.security_prices import get_price
2067
- daily=get_price(stkcd,fromdate1,todate)
2068
-
1869
+ """
1870
+ from siat.security_prices import get_prices_all
1871
+ daily=get_prices_all(stkcd,fromdate1,todate,ticker_type=ticker_type)
1872
+ """
1873
+ from siat.security_price2 import get_price_mticker_mixed
1874
+ daily,found=get_price_1ticker_mixed(ticker=stkcd,fromdate=fromdate1, \
1875
+ todate=todate,ticker_type=ticker_type)
1876
+ """
2069
1877
  if daily is None:
2070
- print(" #Error(candlestick): failed to get price info of",stkcd,fromdate,todate)
1878
+ print(" #Error(candlestick): failed to get price info of",stkcd)
2071
1879
  return
1880
+ if len(daily) == 0:
1881
+ print(" #Warning(candlestick): zero price info to draw K-line for",stkcd)
1882
+ return
1883
+ """
1884
+ if found == 'None':
1885
+ print(" #Error(candlestick): failed to get price info of",stkcd)
1886
+ return
1887
+ if found == 'Empty':
1888
+ print(" #Warning(candlestick): zero price info to draw K-line for",stkcd)
1889
+ return
2072
1890
 
2073
1891
  #如果抓取到的数据没有Volume字段,创造一个但填充为零
2074
1892
  if 'Volume' not in list(daily):
2075
1893
  daily['Volume']=0
2076
1894
 
2077
1895
  #绘制蜡烛图
2078
- lang=check_language()
2079
- if lang == 'English':
2080
- ylabel_txt='Price'
2081
- ylabel_lower_txt='Volume'
2082
- else:
2083
- ylabel_txt='价格'
2084
- ylabel_lower_txt='成交量'
1896
+ ylabel_txt=text_lang('价格','Price')
1897
+ ylabel_lower_txt=text_lang('成交量','Volume')
2085
1898
 
2086
- titletxt=codetranslate(stkcd)
2087
- """
2088
- if mav > 1:
2089
- mpf.plot(daily,type='candle',
2090
- volume=volume,
2091
- style=s,
2092
- title=titletxt,
2093
- datetime_format='%Y-%m-%d',
2094
- tight_layout=True,
2095
- xrotation=15,
2096
- ylabel=texttranslate(ylabel_txt),
2097
- ylabel_lower=texttranslate(ylabel_lower_txt),
2098
- mav=mav,
2099
- figratio=(12.8,7.2))
2100
- else:
2101
- mpf.plot(daily,type='candle',
2102
- volume=volume,
2103
- style=s,
2104
- title=titletxt,
2105
- datetime_format='%Y-%m-%d',
2106
- tight_layout=True,
2107
- xrotation=15,
2108
- ylabel=texttranslate(ylabel_txt),
2109
- ylabel_lower=texttranslate(ylabel_lower_txt),
2110
- figratio=(12.8,7.2)
2111
- )
2112
- """
1899
+ #titletxt=ticker_name(stkcd)
1900
+ titletxt=ticker_name(stkcd,ticker_type=ticker_type)
1901
+
2113
1902
  fig, axlist = mpf.plot(daily,type='candle',
2114
1903
  volume=volume,
2115
1904
  show_nontrading=False,#自动剔除非交易日空白
@@ -2134,9 +1923,7 @@ def candlestick(stkcd,fromdate,todate,volume=True,style='China',mav=[5,10]):
2134
1923
  #style='italic',
2135
1924
  #fontfamily='fantasy',
2136
1925
  loc='center')
2137
-
2138
1926
  fig.show()
2139
-
2140
1927
  reset_plt()
2141
1928
 
2142
1929
  return daily
@@ -2153,7 +1940,9 @@ if __name__ =="__main__":
2153
1940
  price=candlestick("000002.SZ","2020-2-1","2020-2-29")
2154
1941
 
2155
1942
  #==============================================================================
2156
- def candlestick_pro(stkcd,fromdate,todate,colorup='#00ff00',colordown='#ff00ff',style='nightclouds'):
1943
+ def candlestick_pro(stkcd,fromdate,todate, \
1944
+ colorup='#00ff00',colordown='#ff00ff',style='nightclouds', \
1945
+ ticker_type='auto'):
2157
1946
  """
2158
1947
  功能:绘制证券价格K线图。
2159
1948
  输入:证券代码ticker;开始日期fromdate,结束日期todate;
@@ -2166,12 +1955,13 @@ def candlestick_pro(stkcd,fromdate,todate,colorup='#00ff00',colordown='#ff00ff',
2166
1955
  """
2167
1956
 
2168
1957
  #抓取证券价格
2169
- from siat.security_prices import get_price
2170
- daily=get_price(stkcd,fromdate,todate)
1958
+ from siat.security_price2 import get_price_1ticker_mixed
1959
+ daily,found=get_price_1ticker_mixed(ticker=stkcd,fromdate=fromdate, \
1960
+ todate=todate,ticker_type=ticker_type)
2171
1961
 
2172
- if daily is None:
1962
+ if found in ['None','Empty']:
2173
1963
  print(" #Error(candlestick_pro): failed to get price info of",stkcd,fromdate,todate)
2174
- return
1964
+ return None
2175
1965
 
2176
1966
  #绘制蜡烛图
2177
1967
  #在原有的风格nightclouds基础上定制阳线和阴线柱子的色彩,形成自定义风格s
@@ -2180,8 +1970,10 @@ def candlestick_pro(stkcd,fromdate,todate,colorup='#00ff00',colordown='#ff00ff',
2180
1970
  #kwargs = dict(type='candle',mav=(2,4,6),volume=True,figratio=(10,8),figscale=0.75)
2181
1971
  #kwargs = dict(type='candle',mav=(2,4,6),volume=True,figscale=0.75)
2182
1972
  kwargs = dict(type='candle',mav=5,volume=True)
2183
- #titletxt=str(stkcd)
2184
- titletxt=codetranslate(stkcd)
1973
+
1974
+ #titletxt=ticker_name(stkcd)
1975
+ titletxt=ticker_name(stkcd,ticker_type=ticker_type)
1976
+
2185
1977
  mpf.plot(daily,**kwargs,
2186
1978
  style=s,
2187
1979
  datetime_format='%Y-%m-%d',
@@ -2193,6 +1985,7 @@ def candlestick_pro(stkcd,fromdate,todate,colorup='#00ff00',colordown='#ff00ff',
2193
1985
  figratio=(12.8,7.2)
2194
1986
  )
2195
1987
  reset_plt()
1988
+
2196
1989
  return daily
2197
1990
 
2198
1991
  if __name__ =="__main__":
@@ -2207,7 +2000,8 @@ if __name__ =="__main__":
2207
2000
  price=candlestick_pro("000002.SZ","2020-2-1","2020-2-29")
2208
2001
  #==============================================================================
2209
2002
  def stock_Kline_demo(ticker,start='default',end='default', \
2210
- colorup='red',colordown='green',width=0.5):
2003
+ colorup='red',colordown='green',width=0.5, \
2004
+ ticker_type='auto'):
2211
2005
  """
2212
2006
  套壳函数,为了与stock_Kline保持一致
2213
2007
  """
@@ -2233,7 +2027,8 @@ def stock_Kline_demo(ticker,start='default',end='default', \
2233
2027
  start=date_adjust(todate,adjust=-7)
2234
2028
 
2235
2029
  df=candlestick_demo(stkcd=ticker,fromdate=start,todate=end, \
2236
- colorup=colorup,colordown=colordown,width=width)
2030
+ colorup=colorup,colordown=colordown,width=width, \
2031
+ ticker_type=ticker_type)
2237
2032
 
2238
2033
  return df
2239
2034
 
@@ -2245,7 +2040,9 @@ if __name__ =="__main__":
2245
2040
 
2246
2041
  colorup='red';colordown='green';width=0.7
2247
2042
 
2248
- def candlestick_demo(stkcd,fromdate,todate,colorup='red',colordown='green',width=0.7):
2043
+ def candlestick_demo(stkcd,fromdate,todate, \
2044
+ colorup='red',colordown='green',width=0.7, \
2045
+ ticker_type='auto'):
2249
2046
  """
2250
2047
  功能:绘制证券价格K线图,叠加收盘价。
2251
2048
  输入:证券代码ticker;开始日期fromdate,结束日期todate;
@@ -2253,12 +2050,14 @@ def candlestick_demo(stkcd,fromdate,todate,colorup='red',colordown='green',width
2253
2050
  输出:绘制证券价格蜡烛图线图
2254
2051
  返回:证券价格数据表
2255
2052
  """
2053
+
2256
2054
  #抓取证券价格
2257
- from siat.security_prices import get_price
2258
- p=get_price(stkcd,fromdate,todate)
2259
- if p is None:
2260
- print(" #Error(candlestick_demo): failed to get price info of",stkcd,fromdate,todate)
2261
- return
2055
+ from siat.security_price2 import get_price_1ticker_mixed
2056
+ p,found=get_price_1ticker_mixed(ticker=stkcd,fromdate=fromdate, \
2057
+ todate=todate,ticker_type=ticker_type)
2058
+ if found in ['None','Empty']:
2059
+ print(" #Error(candlestick_demo): failed to get prices for:",stkcd,'\b,',fromdate,'-',todate)
2060
+ return p
2262
2061
 
2263
2062
  p['Date']=p.index
2264
2063
 
@@ -2275,18 +2074,11 @@ def candlestick_demo(stkcd,fromdate,todate,colorup='red',colordown='green',width
2275
2074
  fig,ax=plt.subplots()
2276
2075
 
2277
2076
  #绘制各个价格的折线图
2278
- lang=check_language()
2279
- if lang == 'English':
2280
- open_txt='Open'
2281
- high_txt='High'
2282
- low_txt='Low'
2283
- close_txt='Close'
2284
- else:
2285
- open_txt='开盘价'
2286
- high_txt='最高价'
2287
- low_txt='最低价'
2288
- close_txt='收盘价'
2289
-
2077
+ open_txt=text_lang('开盘价','Open')
2078
+ high_txt=text_lang('最高价','High')
2079
+ low_txt=text_lang('最低价','Low')
2080
+ close_txt=text_lang('收盘价','Close')
2081
+
2290
2082
  plt.plot(p.index,p['Open'],color='green',ls="--",label=open_txt,marker='>',markersize=10,linewidth=2)
2291
2083
  plt.plot(p.index,p['High'],color='cyan',ls="-.",label=high_txt,marker='^',markersize=10,linewidth=2)
2292
2084
  plt.plot(p.index,p['Low'],color='k',ls=":",label=low_txt,marker='v',markersize=10,linewidth=2)
@@ -2308,14 +2100,10 @@ def candlestick_demo(stkcd,fromdate,todate,colorup='red',colordown='green',width
2308
2100
  ax.autoscale_view()
2309
2101
  fig.autofmt_xdate()
2310
2102
 
2311
- if lang == 'English':
2312
- titletxt=texttranslate("Security Price Candlestick Demo: ")+codetranslate(str(stkcd))
2313
- price_txt='Price'
2314
- source_txt="Source: "
2315
- else:
2316
- titletxt=texttranslate("K线图/蜡烛图演示:")+codetranslate(str(stkcd))
2317
- price_txt='价格'
2318
- source_txt="数据来源: "
2103
+ titletxt0=text_lang("K线图/蜡烛图演示:","Security Price Candlestick Demo: ")
2104
+ titletxt=titletxt0 + ticker_name(str(stkcd),ticker_type=ticker_type)
2105
+ price_txt=text_lang('价格','Price')
2106
+ source_txt=text_lang("数据来源: 综合","Data source: integrating ")
2319
2107
 
2320
2108
  plt.title(titletxt,fontsize=title_txt_size,fontweight='bold')
2321
2109
  plt.ylabel(price_txt,fontsize=ylabel_txt_size)
@@ -2409,7 +2197,7 @@ def stock_dividend(ticker,fromdate,todate):
2409
2197
  lang=check_language()
2410
2198
  if lang == 'English':
2411
2199
  print('\n======== '+texttranslate("股票分红历史")+' ========')
2412
- print(texttranslate("股票:"),ticker,'\b,',codetranslate(ticker))
2200
+ print(texttranslate("股票:"),ticker,'\b,',ticker_name(ticker))
2413
2201
  print(texttranslate("历史期间:"),fromdate,"-",todate)
2414
2202
 
2415
2203
  #修改列命为英文
@@ -2418,7 +2206,7 @@ def stock_dividend(ticker,fromdate,todate):
2418
2206
  sourcetxt=texttranslate("数据来源: 雅虎财经,")
2419
2207
  else:
2420
2208
  print('\n======== '+"股票分红历史"+' ========')
2421
- print("股票:",ticker,'\b,',codetranslate(ticker))
2209
+ print("股票:",ticker,'\b,',ticker_name(ticker))
2422
2210
  print("历史期间:",fromdate,"-",todate)
2423
2211
 
2424
2212
  #修改列命为中文
@@ -2516,14 +2304,14 @@ def stock_split(ticker,fromdate,todate):
2516
2304
  lang=check_language()
2517
2305
  if lang == 'English':
2518
2306
  print('\n======== '+texttranslate("股票分拆历史")+' ========')
2519
- print(texttranslate("股票:"),ticker,'\b,',codetranslate(ticker))
2307
+ print(texttranslate("股票:"),ticker,'\b,',ticker_name(ticker))
2520
2308
  print(texttranslate("历史期间:"),fromdate,"-",todate)
2521
2309
  divprt.columns=[texttranslate('序号'),texttranslate('日期'),texttranslate('星期'),texttranslate('分拆比例')]
2522
2310
 
2523
2311
  sourcetxt=texttranslate("数据来源: 雅虎财经,")
2524
2312
  else:
2525
2313
  print('\n======== '+"股票分拆历史"+' ========')
2526
- print("股票:",ticker,'\b,',codetranslate(ticker))
2314
+ print("股票:",ticker,'\b,',ticker_name(ticker))
2527
2315
  print("历史期间:",fromdate,"-",todate)
2528
2316
  divprt.columns=['序号','日期','星期','分拆比例']
2529
2317
 
@@ -3137,14 +2925,14 @@ def get_stock_profile(ticker,info_type='basic',printout=True):
3137
2925
  name2=name1.split(',',1)[0] #仅取第一个符号,以前的字符串
3138
2926
  name3=name2.split('(',1)[0] #仅取第一个符号(以前的字符串
3139
2927
  #name4=name3.split(' ',1)[0] #仅取第一个空格以前的字符串
3140
- #name=codetranslate(name4) #去掉空格有名字错乱风险
2928
+ #name=ticker_name(name4) #去掉空格有名字错乱风险
3141
2929
  name9=name3.strip()
3142
- name=codetranslate(name9) #从短名字翻译
2930
+ name=ticker_name(name9) #从短名字翻译
3143
2931
  """
3144
2932
  if not printout: return info
3145
2933
 
3146
2934
  footnote=''
3147
- name=codetranslate(ticker) #从股票代码直接翻译
2935
+ name=ticker_name(ticker) #从股票代码直接翻译
3148
2936
  if info_type in ['basic']:
3149
2937
  sub_info=stock_basic(info)
3150
2938
  info_text="公司基本信息"
@@ -3605,21 +3393,21 @@ def portfolio_esg2(portfolio):
3605
3393
  esg_ep=esgdf.sort_values(['EPscore'], ascending = True)
3606
3394
  p_ep=esg_ep['EPscore'][-1]
3607
3395
  p_ep_stock=esg_ep.index[-1]
3608
- str_ep=texttranslate(" EP分数(基于")+str(p_ep_stock)+codetranslate(str(p_ep_stock))+")"
3396
+ str_ep=texttranslate(" EP分数(基于")+str(p_ep_stock)+ticker_name(str(p_ep_stock))+")"
3609
3397
  len_ep=hzlen(str_ep)
3610
3398
 
3611
3399
  #木桶短板:CSRScore
3612
3400
  esg_csr=esgdf.sort_values(['CSRscore'], ascending = True)
3613
3401
  p_csr=esg_csr['CSRscore'][-1]
3614
3402
  p_csr_stock=esg_csr.index[-1]
3615
- str_csr=texttranslate(" CSR分数(基于")+str(p_csr_stock)+codetranslate(str(p_csr_stock))+")"
3403
+ str_csr=texttranslate(" CSR分数(基于")+str(p_csr_stock)+ticker_name(str(p_csr_stock))+")"
3616
3404
  len_csr=hzlen(str_csr)
3617
3405
 
3618
3406
  #木桶短板:CGScore
3619
3407
  esg_cg=esgdf.sort_values(['CGscore'], ascending = True)
3620
3408
  p_cg=esg_cg['CGscore'][-1]
3621
3409
  p_cg_stock=esg_cg.index[-1]
3622
- str_cg=texttranslate(" CG分数(基于")+str(p_cg_stock)+codetranslate(str(p_cg_stock))+")"
3410
+ str_cg=texttranslate(" CG分数(基于")+str(p_cg_stock)+ticker_name(str(p_cg_stock))+")"
3623
3411
  len_cg=hzlen(str_cg)
3624
3412
 
3625
3413
  str_esg=texttranslate(" ESG总评分数")
@@ -3736,10 +3524,10 @@ def compare_mmeasure(ticker,measures,fromdate,todate, \
3736
3524
  lang=check_language()
3737
3525
  if lang == 'English':
3738
3526
  x_label="Source: sina/stooq/yahoo, "+str(today)
3739
- title_txt="Compare A Security's Multiple Measurements: "+codetranslate(ticker)
3527
+ title_txt="Compare A Security's Multiple Measurements: "+ticker_name(ticker)
3740
3528
  else:
3741
3529
  x_label="数据来源: 综合新浪/Yahoo/stooq,"+str(today)
3742
- title_txt="证券趋势分析:"+codetranslate(ticker)
3530
+ title_txt="证券趋势分析:"+ticker_name(ticker)
3743
3531
 
3744
3532
  draw_lines(df3,y_label=y_label,x_label=x_label, \
3745
3533
  axhline_value=axhline_value,axhline_label=axhline_label, \