-
Notifications
You must be signed in to change notification settings - Fork 7
/
pdSql_common.py
1500 lines (1420 loc) · 68.3 KB
/
pdSql_common.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
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
import pymysql
import pandas as pd
import numpy as np
import datetime,time,os
import tushare as ts
from file_config import YH_SOURCE_DATA_DIR,TDX_LAST_STRING
"""
try:
from pandas.lib import Timestamp
except:
pass
"""
from pandas._libs.lib import Timestamp
import easytrader,easyhistory
import time,os
#ROOT_DIR='E:/work/stockAnalyze'
#ROOT_DIR="C:/中国银河证券海王星/T0002"
#ROOT_DIR="C:\work\stockAnalyze"
#RAW_HIST_DIR=YH_SOURCE_DATA_DIR#"C:/中国银河证券海王星/T0002/export/"
#TDX_LAST_STRING = '数据来源:通达信'
#HIST_DIR=ROOT_DIR+'/update/'
#"""
import tradeTime as tt
import sendEmail as sm
import qq_quotation as qq
"""
from . import tradeTime as tt
from . import sendEmail as sm
from . import qq_quotation as qq
"""
def form_sql(table_name,oper_type='query',select_field=None,where_condition=None,insert_field=None,update_field=None,update_value=None):
"""
:param table_name: string type, db_name.table_name
:param select_field: string type, like 'id,type,value'
:param where_condition: string type, like 'field_value>50'
:param insert_field: string type, like '(date_time,measurement_id,value)'
:param update_field: string type, like 'value' or '(measurement_id,value)'
:param update_value: value or string type, like '1000' or "'normal_type'"
:return: sql string
:use example:
:query: sql_q=form_sql(table_name='stock.account',oper_type='query',select_field='acc_name,initial',where_condition="acc_name='36005'")
:insert: sql_insert=form_sql(table_name='stock.account',oper_type='insert',insert_field='(acc_name,initial,comm)')
:update: sql_update=form_sql(table_name='stock.account',oper_type='update',update_field='initial',where_condition='initial=2900019000',set_value_str='29000')
:delete: sql_delete=form_sql(table_name='stock.account',oper_type='delete',where_condition="initial=14200.0")
"""
sql=''
if table_name=='' or not table_name:
return sql
if oper_type=='query':
field='*'
if select_field:
field=select_field
condition=''
if where_condition:
condition=' where %s' % where_condition
sql='select %s from %s'%(field,table_name) + condition +';'
elif oper_type=='insert' and insert_field:
num=len(insert_field.split(','))
value_tail='%s,'*num
value_tail='('+value_tail[:-1]+')'
sql='insert into %s '% table_name +insert_field +' values'+ value_tail + ';'
elif oper_type=='update' and where_condition and update_field:
"""
update_value_str=str(update_value)
if isinstance(update_value, str):
update_value_str="'%s'"%update_value
"""
sql='update %s set %s='%(table_name,update_field)+ update_value + ' where '+ where_condition + ';'
"""
sql=''
num=len(update_field.split(','))
if num==1:
sql='update %s set %s='%(table_name,update_field)+ update_value + ' where '+ where_condition + ';'
elif num>1:
value_tail='%s,'*num
value_tail='('+value_tail[:-1]+')'
update_sql="update test set " + update_field +value_tail + ':'
else:
pass
"""
elif oper_type=='delete':
condition=''
if where_condition:
condition=' where %s' % where_condition
sql='delete from %s'%table_name + condition + ';'
else:
pass
# print('%s_sql=%s'%(oper_type,sql))
return sql
def format_code(code):
"""
股票代码规整
"""
if not code:
return ''
else:
if isinstance(code,int) or isinstance(code,str):
code_str = '%s'%code
if len(code_str)>=6:
code = code_str
else:
code = '0'*(6-len(code_str))+ '%s'%code_str
else:
pass
return code
def format_name_by_code(code,dict):
if dict:
try:
return dict[code]
except:
return '其他指数'
else:
return 'None'
def get_data_columns(dest_dir,remove_value='Unnamed: 0'):
"""
获取某一目录下相同类型文件的列值,返回list
"""
all_files = os.listdir(dest_dir)
if not all_files:
return list()
file_name = dest_dir + all_files[0]
columns = pd.read_csv(file_name,usecols=None).tail(1).columns.values.tolist()
try:
columns.remove(remove_value)
except:
pass
return columns
def get_raw_hist_df(code_str,latest_count=None):
file_type='csv'
file_name='C:/hist/day/data/'+code_str+'.'+file_type
#print('file_name=',file_name)
raw_column_list=['date','open','high','low','close','volume','rmb','factor']
#print('file_name=',file_name)
df_0=pd.DataFrame({},columns=raw_column_list)
try:
#print('code_str=%s'%code_str)
#df=pd.read_csv(file_name,names=raw_column_list, header=0,encoding='gb2312' #='gb18030')#'utf-8') #for python3
hist_df = pd.read_csv(file_name)
hist_df['rmb'] = hist_df['amount']
#del hist_df['amount']
#del hist_df['MA1']
#print(hist_df)
#print('pd.read_csv=',df)
if hist_df.empty:
#print('code_str=',code_str)
return df_0
return hist_df
except OSError as e:
#print('OSError:',e)
return df_0
def append_to_csv(value,column_name='code',file_name='C:/work/temp/stop_stocks.csv',empty_first=False):
"""
追加单列的CSV文件
"""
stop_codes = []
if empty_first:
pd.DataFrame({column_name:[]}).to_csv(file_name,encoding='utf-8')
try:
stop_trade_df = df=pd.read_csv(file_name)
stop_codes = stop_trade_df[column_name].values.tolist()
except:
pd.DataFrame({column_name:[]}).to_csv(file_name,encoding='utf-8')
stop_codes.append(value)
new_df = pd.DataFrame({column_name:stop_codes})
new_df.to_csv(file_name,encoding='utf-8')
return new_df
#append_to_csv('000562')
def get_yh_raw_hist_df(code_str,latest_count=None,target_last_date_str='',is_updated_raw_export_date=False):
file_type='csv'
#RAW_HIST_DIR="C:/中国银河证券海王星/T0002/export/"
file_name=YH_SOURCE_DATA_DIR+code_str+'.'+file_type
raw_column_list=['date','open','high','low','close','volume','amount']
#print('file_name=',file_name)
df_0=pd.DataFrame({},columns=raw_column_list)
has_tdx_last_string = False
try:
#if True:
#print('code_str=%s'%code_str)
df=pd.read_csv(file_name,names=raw_column_list, header=0,encoding='gb2312')#'utf-8') #for python3
#print('pd.read_csv=',df)
if df.empty:
#print('code_str=',code_str)
df_0.to_csv(file_name,encoding='utf-8')
return df_0,has_tdx_last_string
#else:
# return
last_date=df.tail(1).iloc[0].date
if last_date==TDX_LAST_STRING:
df=df[:-1]
#print('数据来源:通达信')
#print(df.tail(1).iloc[0].date)
if df.empty:
df_0.to_csv(file_name,encoding='utf-8')
return df_0,has_tdx_last_string
#else:
# return
last_volume=df.tail(1).iloc[0].volume
last_trade_date_str = df.tail(1).iloc[0].date
if target_last_date_str and is_updated_raw_export_date:
if last_trade_date_str>=target_last_date_str:
pass
else:
"""个股停牌,代码写入txt文件"""
pass
"""
stop_stocks_csv_name = 'C:/stop_stocks.csv'
stop_trade_df = df=pd.read_csv(stop_stocks_csv_name)
new_stock_df = pd.DataFrame({'code':[code_str]})
stop_trade_df.append(new_stock_df)
"""
if int(last_volume)==0:
df=df[:-1]
df['date'].astype(Timestamp)
df_to_write = df.set_index('date')
df_to_write.to_csv(file_name,encoding='utf-8')
has_tdx_last_string = True
else:
pass
return df,has_tdx_last_string
except OSError as e:
#print('OSError:',e)
df_0.to_csv(file_name,encoding='utf-8')
return df_0,has_tdx_last_string
def get_easyhistory_df(code_str,source='easyhistory'): #ta_lib
data_path = 'C:/hist/day/data/'
if source=='YH' or source=='yh':
data_path = YH_SOURCE_DATA_DIR
his = easyhistory.History(dtype='D', path=data_path,type='csv',codes=[code_str])
#if his.empty:
# return his
res = his.get_hist_indicator(code_str)
return res
def update_one_hist(code_str,stock_sql_obj,histdata_last_df,update_db=True):
"""
:param code_str: string type, code string_name
:param stock_sql_obj: StockSQL type,
:param histdata_last_df: dataframe type, df from table histdata
:return:
"""
df=get_raw_hist_df(code_str)
if df.empty:
return 0
code_list=[code_str]*len(df)
df['code']=pd.Series(code_list,index=df.index)
p=df.pop('code')
df.insert(0,'code',p)
#print("update_one_hist1")
last_db_date=stock_sql_obj.get_last_db_date(code_str,histdata_last_df)
#print("update_one_hist2")
last_db_date_str=''
#print('last_db_date',last_db_date,type(last_db_date))
#print('last_db_date_str',last_db_date_str)
#criteria0=df.volume>0
#df=df[df.volume>0]
if last_db_date:
last_db_date_str='%s' % last_db_date
last_db_date_str=last_db_date_str[:10]
#criteria1=df.date>last_db_date_str
df=df[df.date>last_db_date_str]
#print('sub df', df)
if df.empty:
#print('History data up-to-date for %s, no need update' % code_str)
return 0
if update_db:
stock_sql_obj.insert_table(df, 'histdata')
#print(df.tail(1))
#print(df.tail(1).iloc[0])
update_date=df.tail(1).iloc[0].date
#last_date=histdata_last_df.loc[date[-1],'date']
#update_date= 2015-11-20 <class 'str'>
#print('update_date=',update_date,type(update_date))
stock_sql_obj.update_last_db_date(code_str,last_db_date_str,update_date)
return len(df)
def get_file_timestamp(file_name):
#get last modify time of given file
file_mt_str=''
try:
file_mt= time.localtime(os.stat(file_name).st_mtime)
file_mt_str=time.strftime("%Y-%m-%d %X",file_mt)
except:
#file do not exist
pass
return file_mt_str
#get the all file source data in certain DIR
def get_dir_latest_modify_time(hist_dir,codes={}):
"""
:param hist_dir: string type, DIR of export data
:return: list type, code string list
"""
all_code=[]
latest_time = '1970-01-01 00:00:00'
if codes:
for code in codes:
full_file_name = hist_dir + '%s.csv' % code
file_mt_str = get_file_timestamp(full_file_name)
if file_mt_str > latest_time:
latest_time = file_mt_str
all_code = codes
else:
for filename in os.listdir(hist_dir):#(r'ROOT_DIR+/export'):
code=filename[:-4]
if len(code)==6:
all_code.append(code)
full_file_name = hist_dir + filename
file_mt_str = get_file_timestamp(full_file_name)
if file_mt_str > latest_time:
latest_time = file_mt_str
return all_code,latest_time
#get the all file source data in certain DIR
def get_all_code(hist_dir):
"""
:param hist_dir: string type, DIR of export data
:return: list type, code string list
"""
all_code=[]
for filename in os.listdir(hist_dir):#(r'ROOT_DIR+/export'):
code=filename[:-4]
if len(code)==6:
all_code.append(code)
return all_code
def get_all_quotation(his_dir=YH_SOURCE_DATA_DIR):
#hist_dir = 'C:/中国银河证券海王星/T0002/export/'
all_codes = get_all_code(hist_dir)
quotation_data = qq.get_qq_quotations_df(all_codes)
print('quotation_data:',quotation_data)
return quotation_data
#get_all_quotation()
def get_different_symbols(hist_dir='C:/hist/day/data/'):
indexs= ['cyb', 'zxb', 'sz', 'sh', 'sz300', 'zx300', 'hs300']#, 'sh50']
all_codes = get_all_code(hist_dir)
funds =[]
b_stock = []
for code in all_codes:
if code.startswith('1') or code.startswith('5'):
funds.append(code)
elif code.startswith('9'):
b_stock.append(code)
except_codes = ['000029']
all_stocks = list(set(all_codes).difference(set(funds+indexs+except_codes)))
return indexs,funds,b_stock,all_stocks
def update_all_hist_data(codes,update_db=True):
"""
:param codes: list type, code string list
:return:
"""
starttime=datetime.datetime.now()
stock_sql_obj=StockSQL()
print('histdata_last_df1',datetime.datetime.now())
histdata_last_df=stock_sql_obj.query_data(table='histdata_last')
print('histdata_last_df2',datetime.datetime.now())
for code_str in codes:
update_one_hist(code_str, stock_sql_obj,histdata_last_df,update_db)
deltatime=datetime.datetime.now()-starttime
print('update duration=',deltatime.days*24*3600+deltatime.seconds)
print('update completed')
def get_position(broker='yh',user_file='yh.json'):
user = easytrader.use(broker)
user.prepare(user_file)
holding_stocks_df = user.position#['证券代码'] #['code']
user_balance = user.balance#['证券代码'] #['code']
account = '36005'
if user_file== 'yh1.json':
account = '38736'
holding_stocks_df['account'] = account
this_day=datetime.datetime.now()
date_format='%Y/%m/%d'
time_format = date_format + ' %X'
time_str=this_day.strftime(time_format)
holding_stocks_df['update'] = time_str
#holding_stocks_df['valid'] = 1
"""
当前持仓 股份可用 参考市值 参考市价 股份余额 参考盈亏 交易市场 参考成本价 盈亏比例(%) 股东代码 \
0 6300 6300 24885.0 3.95 6300 343.00 深A 3.896 1.39% 0130010635
1 400 400 9900.0 24.75 400 163.00 深A 24.343 1.67% 0130010635
2 600 600 15060.0 25.10 600 115.00 深A 24.908 0.77% 0130010635
3 1260 0 13041.0 10.35 1260 906.06 沪A 9.631 7.47% A732980330
证券代码 证券名称 买入冻结 卖出冻结
0 000932 华菱钢铁 0 0
1 000977 浪潮信息 0 0
2 300326 凯利泰 0 0
3 601009 南京银行 0 0
"""
#print(holding_stocks_df)
return holding_stocks_df,user_balance
def update_one_stock(symbol,realtime_update=False,dest_dir=YH_SOURCE_DATA_DIR, force_update_from_YH=False):
"""
运行之前先下载及导出YH历史数据
"""
"""
:param symbol: string type, stock code
:param realtime_update: bool type, True for K data force update during trade time
:param dest_dir: string type, like csv dir
:param force_update_from_YH: bool type, force update K data from YH
:return: Dataframe, history K data for stock
"""
index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
qq_index_symbol_maps = {'sh':'000001','sz':'399001','zxb':'399005','cyb':'399006',
'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
FIX_FACTOR = 1.0
d_format='%Y/%m/%d'
last_date_str = tt.get_last_trade_date(date_format=d_format)
latest_date_str = tt.get_latest_trade_date(date_format=d_format)
#print('last_date_str=',last_date_str)
#print('latest_date_str=',latest_date_str)
next_date_str = tt.get_next_trade_date(date_format=d_format)
#print(next_date_str)
dest_file_name = dest_dir+ '%s.csv' % symbol
dest_df = get_raw_hist_df(code_str=symbol)
file_type='csv'
#RAW_HIST_DIR = YH_SOURCE_DATA_DIR#"C:/中国银河证券海王星/T0002/export/"
yh_file_name =YH_SOURCE_DATA_DIR+symbol+'.'+file_type
if symbol in index_symbol_maps.keys():
symbol = index_symbol_maps[symbol]
dest_file_name = dest_dir+ '%s.csv' % symbol
#print('dest_file_name=',dest_file_name)
if dest_df.empty:
if symbol in index_symbol_maps.keys():
symbol = index_symbol_maps[symbol]
yh_file_name = YH_SOURCE_DATA_DIR+symbol+'.'+file_type
#yh_index_df = get_yh_raw_hist_df(code_str=symbol)
#print('yh_file_namev=',yh_file_name)
yh_index_df = pd.read_csv(yh_file_name)
#yh_index_df['factor'] = 1.0
yh_df = yh_index_df.set_index('date')
yh_df.to_csv(dest_file_name ,encoding='utf-8')
dest_df = yh_index_df
#del dest_df['rmb']
return yh_df
#print(dest_df)
dest_df_last_date = dest_df.tail(1).iloc[0]['date']
#print('dest_df_last_date=',dest_df_last_date)
quotation_datetime = datetime.datetime.now()
if dest_df_last_date<latest_date_str:
quotation_date = ''
try:
quotation_index_df = qq.get_qq_quotations_df([symbol], ['code','date','open','high','low','close','volume','amount'])
quotation_date = quotation_index_df.iloc[0]['date']
#quotation_date = quotation_index_df.iloc[0]['date']
#quotation_datetime = quotation_index_df.iloc[0]['datetime']
#del quotation_index_df['datetime']
if dest_df_last_date==quotation_date:
return dest_df
#quotation_index_df = ts.get_index()
except:
time.sleep(3)
quotation_index_df = qq.get_qq_quotations_df([symbol], ['code','date','open','high','low','close','volume','amount'])
print(quotation_index_df)
quotation_date = quotation_index_df.iloc[0]['date']
#quotation_datetime = quotation_index_df.iloc[0]['datetime']
#del quotation_index_df['datetime']
if dest_df_last_date==quotation_date:
return dest_df
#print('quotation_date=',quotation_date)
#print(quotation_index_df)
#quotation_index_df['factor'] = 1.0
quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount']]#,'factor']]
#quotation_index_df.iloc[0]['volume'] = 0
#quotation_index_df.iloc[0]['amount'] = 0
#print(quotation_index_df)
#print(quotation_index_df)
need_to_send_mail = []
sub = ''
index_name = symbol
#table_update_times = self.get_table_update_time()
if quotation_date:
yh_symbol = symbol
if symbol in index_symbol_maps.keys():
yh_symbol = index_symbol_maps[index_name]
yh_file_name = YH_SOURCE_DATA_DIR+yh_symbol+'.'+file_type
#yh_index_df = get_yh_raw_hist_df(code_str=symbol)
yh_index_df = pd.read_csv(yh_file_name,encoding='GBK')
#yh_index_df['factor'] = FIX_FACTOR
yh_last_date = yh_index_df.tail(1).iloc[0]['date']
#print('yh_last_date=',yh_last_date)
#print( yh_index_df)#.head(len(yh_index_df)-1))
if yh_last_date>dest_df_last_date: #dest_df_last_date<latest_date_str
#date_data = self.query_data(table=index_name,fields='date',condition="date>='%s'" % last_date_str)
#data_len = len(date_data)
#this_table_update_time = table_update_times[index_name]
#print('this_table_update_time=', this_table_update_time)
if yh_last_date<last_date_str: #no update more than two day
"""需要手动下载银河客户端数据"""
print('Need to manual update %s index from YH APP! Please make suere you have sync up YH data' % index_name)
need_to_send_mail.append(index_name)
sub = '多于两天没有更新指数数据库'
content = '%s 数据表更新可能异常' % need_to_send_mail
sm.send_mail(sub,content,mail_to_list=None)
elif yh_last_date==last_date_str: # update by last date
"""只需要更新当天数据"""
realtime_update = tt.is_trade_time_now()
if realtime_update:
if yh_last_date<latest_date_str:
print(' force update %s index' % symbol)
yh_index_df = yh_index_df.append(quotation_index_df, ignore_index=True)
#elif yh_last_date==latest_date_str:
# print(' delete last update, then force update %s index' % symbol)
# yh_index_df=yh_index_df[:-1]
# yh_index_df = yh_index_df.append(quotation_index_df, ignore_index=True)
else:
pass
#print(yh_index_df)
else:
pass
else:# yh_last_date>latest_date_str: #update to latest date
"""YH已经更新到今天,要更新盘中获取的当天数据"""
print(' %s index updated to %s; not need to update' % (index_name,latest_date_str))
"""
if force_update:
print(' force update %s index' % index_name)
yh_index_df0 = yh_index_df.head(len(yh_index_df)-1)
print(yh_index_df0)
yh_index_df = yh_index_df0.append(quotation_index_df, ignore_index=True)
print(yh_index_df)
else:
pass
"""
yh_index_df = yh_index_df.set_index('date')
"""
try:
os.remove(file_name)
print('Delete and update the csv file')
except:
pass
"""
yh_index_df.to_csv(dest_file_name ,encoding='utf-8')
else:
if force_update_from_YH and yh_last_date==dest_df_last_date:
yh_index_df = yh_index_df.set_index('date')
yh_index_df.to_csv(dest_file_name ,encoding='utf-8')
pass
elif dest_df_last_date==latest_date_str:
print('No need to update data')
realtime_update = tt.is_trade_time_now()
if realtime_update:
quotation_index_df = qq.get_qq_quotations([symbol], ['code','date','open','high','low','close','volume','amount'])
#quotation_index_df['factor'] = 1.0
quotation_index_df = quotation_index_df[['date','open','high','low','close','volume','amount']]#'factor']]
#print(quotation_index_df)
print(' force update %s index' % symbol)
dest_df0 = dest_df
if dest_df_last_date==latest_date_str:
dest_df0 = dest_df.head(len(dest_df)-1)
#dest_df0 = dest_df0[:-1]
#print(dest_df0)
dest_df = dest_df0.append(quotation_index_df, ignore_index=True)
#print(dest_df)
if quotation_index_df.empty:
pass
else:
yh_index_df = yh_index_df.set_index('date')
dest_df.to_csv(dest_file_name ,encoding='utf-8')
else:
pass
else:
pass
return dest_df
#df = update_one_stock(symbol='399006',dest_dir="C:/中国银河证券海王星/T0002/export/", force_update_from_YH=False)
#print(df)
def update_realtime_k(hist_dir=YH_SOURCE_DATA_DIR):
update_one_stock(symbol, realtime_update, hist_dir, force_update_from_YH)
return
def update_codes_from_YH(codes, realtime_update=False, dest_dir='C:/hist/day/data/', force_update_from_YH=False):
#index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
# 'sh50':'000016','sz300':'399007','zx300':'399008','hs300':'000300'}
#print(list(index_symbol_maps.keys()))
#通常为指数和基金从银河的更新
for symbol in codes: # #list(index_symbol_maps.keys()):
print(symbol)
update_one_stock(symbol, realtime_update, dest_dir, force_update_from_YH)
return
def get_exit_data(symbol,dest_df,last_date_str):
df=pd.read_csv('C:/hist/day/temp/%s.csv' % symbol)
dest_df = get_raw_hist_df(code_str=symbol)
if dest_df.empty:
pass
else:
dest_df_last_date = dest_df.tail(1).iloc[0]['date']
if dest_df_last_date==last_date_str:
exit_price = dest_df.tail(3)
return
def get_exit_comnfirm_rate(sql=None):
"""
Get from SQL
"""
confirm_rate=0.0026#卖出交易费
if sql:
setting_dict = stock_sql_obj.get_exit_setting_data()
if setting_dict and 'exit_confirm_rate' in list(setting_dict.keys()):
confirm_rate = setting_dict['exit_confirm_rate']
return confirm_rate
def get_exit_setting_rate(exit_setting_dict={}):
"""
Get from SQL
"""
confirm_rate=0.0026
tolerate_dropdown_rate = -0.05
delay_minutes = 60
if exit_setting_dict:
if 'valid' in list(exit_setting_dict.keys()):
if exit_setting_dict['valid']:
if 'tolerate_loss' in list(exit_setting_dict.keys()):
tolerate_dropdown_rate = exit_setting_dict['tolerate_loss']
if 'exit_confirm_rate' in list(exit_setting_dict.keys()):
confirm_rate = exit_setting_dict['exit_confirm_rate']
if 'delay_minutes' in list(exit_setting_dict.keys()):
delay_minutes = exit_setting_dict['delay_minutes']
else:
return 0,0,0
else:
pass
return confirm_rate,tolerate_dropdown_rate,delay_minutes
def get_stock_exit_price(hold_codes=['300162'],exit_setting_dict={},data_path=YH_SOURCE_DATA_DIR):#'C:/中国银河证券海王星/T0002/export/'):#, has_update_history=False):
"""获取包括股票的止损数据"""
"""
confirm_rate:超过止损价后再次下跌的幅度,以确认止损
"""
confirm_rate,tolerate_dropdown_rate,delay_minutes = get_exit_setting_rate(exit_setting_dict)
#exit_dict={'300162': {'exit_half':22.5, 'exit_all': 19.0},'002696': {'exit_half':17.10, 'exit_all': 15.60}}
has_update_history = True
"""
if not has_update_history:
easyhistory.init('D', export='csv', path="C:/hist",stock_codes=hold_codes)
easyhistory.update(path="C:/hist",stock_codes=hold_codes)
#has_update_history = True
"""
#his = easyhistory.History(dtype='D', path='C:/hist',codes=hold_codes)
#data_path = 'C:/hist/day/data/'
#data_path = 'C:/中国银河证券海王星/T0002/export/'
exit_dict = dict()
his = easyhistory.History(dtype='D', path=data_path, type='csv',codes=hold_codes)
d_format='%Y/%m/%d'
last_date_str = tt.get_last_trade_date(date_format=d_format)
latest_date_str = tt.get_latest_trade_date(date_format=d_format)
for code in hold_codes:
#code_hist_df = hist[code].MA(1).tail(3).describe()
if code=='sh000001' or code=='sh':
code = '999999'
if code=='cyb':
code = '399006'
exit_data = dict()
hist_df =his[code].ROC(1)
hist_last_date = hist_df.tail(1).iloc[0].date
last_close = hist_df.tail(1).iloc[0].close
#print('hist_last_date=',hist_last_date)
great_drop_rate = 0.0
geat_increase_rate = 0.0
min_close = 0.0
min_low =0.0
if hist_last_date<last_date_str:
hist_df['l_change'] = ((hist_df['low']-hist_df['close'].shift(1))/hist_df['close'].shift(1)).round(3)
hist_df['h_change'] = ((hist_df['high']-hist_df['close'].shift(1))/hist_df['close'].shift(1)).round(3)
hist_low_describe = hist_df.tail(60).describe()
#print(hist_low_describe)
great_drop_rate = round(hist_low_describe.loc['25%'].l_change,4)#表征下跌时,异常大的下跌幅度
geat_increase_rate = round(hist_low_describe.loc['75%'].h_change,4)#表征上涨时,较大的上涨幅度
if tolerate_dropdown_rate<0: #如果有给定容许回撤
great_drop_rate = max(great_drop_rate,tolerate_dropdown_rate)
#print('hist_low_change=',hist_low_change)
#if hist_low_change< great_drop_rate:
#great_drop_rate = hist_low_change
#print('great_drop_rate=',great_drop_rate)
else:
hist_df['l_change'] = ((hist_df['low']-hist_df['close'].shift(1))/hist_df['close'].shift(1)).round(3)
hist_df['h_change'] = ((hist_df['high']-hist_df['close'].shift(1))/hist_df['close'].shift(1)).round(3)
hist_low_describe = hist_df.tail(60).describe()
great_drop_rate = round(hist_low_describe.loc['25%'].l_change,4)
geat_increase_rate = round(hist_low_describe.loc['75%'].h_change,4)
#great_drop_rate = hist_low_change
#print('great_drop_rate=',great_drop_rate)
hist_df = hist_df[hist_df.date<=last_date_str]
describe_df = his[code].MA(1).tail(3).describe()
min_low =round(describe_df.loc['min'].low, 2) #撒内最低价的最小值
min_close = round(round(describe_df.loc['min'].close,2),2)
max_close = round(describe_df.loc['max'].close,2)
max_high = round(describe_df.loc['max'].high,2)#三日最高价的最大值
if tolerate_dropdown_rate<0: #如果有给定容许回撤
min_low = max(min_low,round(last_close*(1.0+tolerate_dropdown_rate),2))
exit_half_price = min_close * (1.0 - confirm_rate)
exit_all_price = min_low * (1.0 - confirm_rate)
"""
if min_low<=5:
pass
elif min_low<=10:
exit_half_price = exit_half_price - 0.01
exit_all_price = exit_all_price - 0.01
elif min_low<=30:
exit_half_price = exit_half_price - 0.02
exit_all_price = exit_all_price - 0.02
elif min_low<=50:
exit_half_price = exit_half_price - 0.05
exit_all_price = exit_all_price - 0.05
elif min_low<=100:
exit_half_price = exit_half_price - 0.1
exit_all_price = exit_all_price - 0.1
else:
exit_half_price = exit_half_price - 0.2
exit_all_price = exit_all_price - 0.2
"""
exit_data['exit_half'] = exit_half_price
exit_data['exit_all'] = exit_all_price
exit_data['exit_rate'] = great_drop_rate
exit_data['t_rate'] = geat_increase_rate
exit_dict[code] = exit_data
#print('exit_dict=%s' % exit_dict)
return exit_dict
def send_exit_mail(exit_code='002290',exit_state=1.0,exit_data={},exit_time=datetime.datetime.now(),
mail_to_list=None,count=0,clear=0,to_sql=None,period_count=20):
"""发送止损退出email告警"""
exit_type = ""
if exit_state==1:
exit_type = "清仓 "
elif exit_state==0.5:
exit_type = "半仓 "
else:
pass
stock_type = "个股风险"
if exit_code in ['sh','cyb','999999','399006'] :
stock_type = "系统风险"
sub = '[%s] %s触发<%s>止损,累计触发count=%s, 时间: %s' % (stock_type,exit_code,exit_type,count, exit_time)
content = '请确认已经止损!止损数据: \n %s' % exit_data
if clear:
sub = '[解除' + sub[1:]
content = '当日止损后重返止损之上!止损数据: \n %s' % exit_data
else:
pass
if count==1 or count%period_count==0:
sm.send_mail(sub,content,mail_to_list)
if to_sql:
#type,symbol,subject,save_time
data = [[stock_type,exit_type,exit_code,sub,exit_time]]
to_sql.maillogs(data)
else:
pass
else:
pass
return
def get_exit_price(symbols=['sh','cyb'],exit_setting={},yh_index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
'sh50':'000016','sz300':'399007','zx300':'399008'}):#['sh','sz','zxb','cyb','sz300','sh50']):
"""获取包括指数在内的止损数据"""
yh_index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
'sh50':'000016','sz300':'399007','zx300':'399008'}#'hs300':'000300'}
hold_codes = []
for symbol in symbols:
actual_code = symbol
if symbol in list(yh_index_symbol_maps.keys()):
actual_code = yh_index_symbol_maps[symbol]
else:#stock
pass
hold_codes.append(actual_code)
exit_data = get_stock_exit_price(hold_codes,exit_setting_dict=exit_setting)
return exit_data
def is_risk_to_exit(symbols=['sh','cyb'],init_exit_data={},
yh_index_symbol_maps = {'sh':'999999','sz':'399001','zxb':'399005','cyb':'399006',
'sh50':'000016','sz300':'399007','zx300':'399008'},mail_count={},
demon_sql=None,mail2sql=None,mail_period=20,mailto_list=None,
stopped=[], operation_tdx=None,exit_setting_dict={}):
"""风险监测和emai告警"""
#index_exit_data=get_exit_price(['sh','cyb']
confirm_rate,tolerate_dropdown_rate,delay_minutes = get_exit_setting_rate(exit_setting_dict)
exit_data = init_exit_data
if not exit_data:
exit_data = get_exit_price(symbols)
else:
pass
if not mail_count:
for symbol in symbols:
mail_count[symbol] = 0
else:
pass
symbol_quot = qq.get_qq_quotations(codes=symbols)
#overlap_symbol = list(set(list(exit_data.keys())) & set(list(symbol_quot.keys())))
if not exit_data or not symbol_quot:
return {}
risk_data = {}
symbols = list(set(symbols).difference(set(stopped)))
for symbol in symbols:
this_risk = {}
exit_p = 100000.0
symbol_now_p = symbol_quot[symbol]['now']
symbol_now_v = symbol_quot[symbol]['volume']
if symbol_now_v>=0: #update stop stocks
pass
else:
if symbol not in stopped:
stopped.append(symbol)
else:
pass
if symbol=='300431' and demon_sql and False: #for test
symbol_now_p = demon_sql.get_demon_value()
code = symbol
if code in list(yh_index_symbol_maps.keys()):
code = yh_index_symbol_maps[symbol]
index_exit_half = exit_data[code]['exit_half']
index_exit_all = exit_data[code]['exit_all']
#index_exit_all = 52.52
#index_exit_all = 3098.89
index_exit_rate = exit_data[code]['exit_rate']
risk_state = 0
if index_exit_all==0:
last_close = symbol_quot[symbol]['close']
index_exit_all = (1+2*index_exit_rate) * last_close
index_exit_half = (1+index_exit_rate) * last_close
else:
pass
#print('symbol=',symbol)
#print('symbol_now_p=',symbol_now_p)
#print('index_exit_all',index_exit_all)
if symbol_now_p<=index_exit_all*(1+confirm_rate):
risk_state = 1.0
exit_p = index_exit_all
elif symbol_now_p<=index_exit_half*(1+confirm_rate):
risk_state = 0.5
exit_p = index_exit_half
else:
pass
if risk_state>0:
if mail_count[symbol]>=0: #email to exit
mail_count[symbol] = mail_count[symbol] + 1
this_risk['risk_code'] = symbol
this_risk['risk_now'] = symbol_now_p
this_risk['risk_state'] = risk_state
this_risk['risk_time'] = datetime.datetime.now()
"""
if operation_tdx:
pre_position = operation_tdx.get_my_position()
available_to_sell = pre_position[symbol]['可用余额'] * risk_state
operation_tdx.order(code=symbol, direction='S', quantity=available_to_sell, actual_price=symbol_now_p)
post_position = operation_tdx.get_my_position()
print('post_position=',post_position)
pos_chg = operation_tdx.getPostionChange(pre_position,post_position)
"""
send_exit_mail(exit_code=symbol,exit_state=risk_state,exit_data=exit_data[code],
exit_time=datetime.datetime.now(),mail_to_list=mailto_list,count=mail_count[symbol],
to_sql=mail2sql,period_count=mail_period)
risk_data[symbol] = this_risk
else:
print('Have sent email before')
elif risk_state==0:# not exit or recover
if mail_count[symbol]==0:
pass
elif mail_count[symbol]>=1:
if mail_count[symbol]==1:
send_exit_mail(exit_code=symbol,exit_state=risk_state,exit_data=exit_data[code],
exit_time=datetime.datetime.now(),mail_to_list=mailto_list,count=mail_count[symbol],
clear=1,to_sql=mail2sql,period_count=mail_period)
this_risk['risk_code'] = symbol
this_risk['risk_now'] = symbol_now_p
this_risk['risk_state'] = risk_state
this_risk['risk_time'] = datetime.datetime.now()
risk_data[symbol] = this_risk
else:# still not descrease to 0
pass
mail_count[symbol] = mail_count[symbol] - 1
else:#不存在的情况
pass
else:
#不存在的情况
pass
if stopped:
stopped=list(set(stopped))
return risk_data,mail_count,stopped
def sell_risk_stock(risk_data,position,alv_sell_stocks,symbol_quot,operation_tdx,demon_sql=None,half_sell=False):
#position,alv_sell_stocks = op_tdx.get_all_position()
risk_stocks = list(risk_data.keys())
current_acc_id,current_box_id = operation_tdx.get_acc_combobox_id()
this_acc_position = operation_tdx.get_my_position()
acc_list = list(alv_sell_stocks.keys())
if current_acc_id in acc_list:
this_acc_avl_sell = alv_sell_stocks[current_acc_id]
if this_acc_avl_sell:
this_acc_exit_stocks = list(set(risk_stocks) & set(this_acc_avl_sell))
for symbol in this_acc_exit_stocks:
risk_state = risk_data[symbol]['risk_state']
if (risk_state==0.5 and not half_sell) or risk_state==0:
continue
this_acc_num_to_sell = this_acc_position[symbol]['可用余额'] * risk_state
"""
set_columns= ['ask1', 'bid1_volume', 'code', 'price_volume_amount', 'ask5_volume', 'ask5',
'PE', 'now', 'bid2_volume', 'bid5', 'recent_trade', 'wave', 'high', 'close',
'circulation', 'bid2', 'bid3', 'ask1_volume', 'increase', 'name', 'low',
'bid3_volume', 'ask3', 'high_2', 'bid_volume', 'bid5_volume', 'ask3_volume', 'quot_time',
'datetime', 'open', 'total_market', 'low_2', 'topest', 'ask2_volume', 'turnover',
'ask_volume', 'bid1', 'amount', 'increase_rate', 'PB', 'ask2', 'lowest',
'ask4_volume', 'date', 'bid4_volume', 'ask4', 'volume', 'unknown', 'bid4']
"""
symbol_bid1_p = symbol_quot[symbol]['bid1']
symbol_bid5_p = symbol_quot[symbol]['bid5']
symbol_ask1_p = symbol_quot[symbol]['ask1']
symbol_ask5_p = symbol_quot[symbol]['ask5']
symbol_now_p = symbol_quot[symbol]['now']
symbol_now_v = symbol_quot[symbol]['volume']
symbol_topest = symbol_quot[symbol]['topest']
symbol_lowest = symbol_quot[symbol]['lowest']
if symbol_now_v<=0 or symbol_now_p<=0:#stop trade
continue
limit_p = [symbol_topest,symbol_lowest]
if symbol=='300432' and demon_sql: #for test
symbol_now_p = demon_sql.get_demon_value()
#operation_tdx.order(code=symbol, direction='S', quantity=this_acc_num_to_sell, actual_price=symbol_now_p,limit_price=None)
operation_tdx.order(code=symbol, direction='S', quantity=this_acc_num_to_sell, actual_price=symbol_now_p,limit_price=None,post_confirm_interval=0,check_valid_time=True)
else:
pass
if len(acc_list)==2:
exchange_id = operation_tdx.change_account(current_acc_id, current_box_id)
second_acc_id,second_box_id = operation_tdx.get_acc_combobox_id()
second_acc_position = operation_tdx.get_my_position()
if second_acc_id in acc_list:
second_acc_avl_sell = alv_sell_stocks[second_acc_id]
if second_acc_avl_sell:
this_acc_exit_stocks = list(set(risk_stocks) & set(second_acc_avl_sell))
for symbol in this_acc_exit_stocks:
risk_state = risk_data[symbol]['risk_state']
print('second_acc_position[symbol]=',second_acc_position[symbol])
if (risk_state==0.5 and not half_sell) or risk_state==0: #and '可用余额 ' not in list(risk_data[symbol].keys()):
continue
second_acc_num_to_sell = second_acc_position[symbol]['可用余额 '] * risk_state
symbol_bid1_p = symbol_quot[symbol]['bid1']
symbol_bid5_p = symbol_quot[symbol]['bid5']
symbol_ask1_p = symbol_quot[symbol]['ask1']
symbol_ask5_p = symbol_quot[symbol]['ask5']
symbol_now_p = symbol_quot[symbol]['now']
symbol_now_v = symbol_quot[symbol]['volume']
if symbol_now_v<=0 or symbol_now_p<=0:#stop trade
continue
symbol_topest = symbol_quot[symbol]['topest']
symbol_lowest = symbol_quot[symbol]['lowest']
limit_p = [symbol_topest,symbol_lowest]
if symbol=='300432' and demon_sql: #for test
symbol_now_p = demon_sql.get_demon_value()
#operation_tdx.order(code=symbol, direction='S', quantity=second_acc_num_to_sell, actual_price=symbol_now_p,limit_price=None)
operation_tdx.order(code=symbol, direction='S', quantity=second_acc_num_to_sell, actual_price=symbol_now_p,limit_price=None,post_confirm_interval=0,check_valid_time=True)
else:
pass
return
def get_potential_stocks(stock_sql,strategy=33):
potential_stocks = []
table = 'potential'
potential_stock_df = stock_sql.get_table_df(table,columns=None)
if potential_stock_df.empty:
pass
else:
potential_stocks = potential_stock_df['code'].tolist()
print('potential_stocks=',potential_stocks)
return potential_stocks
def get_realtime_price(stocks=[]):
symbol_quot = qq.get_qq_quotations(codes=stocks)
"""
symbol_bid1_p = symbol_quot[symbol]['bid1']
symbol_bid5_p = symbol_quot[symbol]['bid5']
symbol_ask1_p = symbol_quot[symbol]['ask1']
symbol_ask5_p = symbol_quot[symbol]['ask5']
symbol_now_p = symbol_quot[symbol]['now']