-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathUniversalRotation.py
537 lines (478 loc) · 28.4 KB
/
UniversalRotation.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
import os, random, time, datetime, schedule, webbrowser
import xlwings
import pandas
import requests
import pysnowball
import browser_cookie3
from chinese_calendar import is_workday
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
@xlwings.func
def get_fund_net_asset_value_history(fund_code: str, pz: int = 200) -> pandas.DataFrame:
'''
根据基金代码和要获取的页码抓取基金净值信息
Parameters
----------
fund_code : 6位基金代码
page : 页码 1 为最新页数据
Return
------
DataFrame : 包含基金历史k线数据
'''
# 请求头
EastmoneyFundHeaders = {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
# 'Connection': 'keep-alive',
'Host': 'api.fund.eastmoney.com',
'Referer': 'http://fundf10.eastmoney.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
}
# 请求参数
Eastmoneyparams = {
'fundCode': f'{fund_code}',
'pageIndex': '1',
'pageSize': f'{pz}',
'startDate': '',
'endDate': '',
}
url = 'http://api.fund.eastmoney.com/f10/lsjz'
#设置重连次数
requests.adapters.DEFAULT_RETRIES = 10
session1 = requests.session()
# 设置连接活跃状态为False
session1.keep_alive = False
response1 = session1.get(url, headers=EastmoneyFundHeaders, params=Eastmoneyparams, verify=False, stream=False, timeout=10)
json_response = response1.json()
response1.close()
del(response1)
rows = []
columns = ['日期', '单位净值', '累计净值', '涨跌幅']
if json_response is None:
return pandas.DataFrame(rows, columns=columns)
datas = json_response['Data']['LSJZList']
if len(datas) == 0:
return pandas.DataFrame(rows, columns=columns)
for stock in datas:
rows.append({
'日期': stock['FSRQ'],
'单位净值': stock['DWJZ'],
'累计净值': stock['LJJZ'],
'涨跌幅': stock['JZZZL']
})
df = pandas.DataFrame(rows)
df['日期'] = pandas.to_datetime(df['日期'], errors='coerce')
df['单位净值'] = pandas.to_numeric(df['单位净值'], errors='coerce')
df['累计净值'] = pandas.to_numeric(df['累计净值'], errors='coerce')
df['涨跌幅'] = pandas.to_numeric(df['涨跌幅'], errors='coerce')
return df
@xlwings.func
# 获取基金的市价、溢价率、成交量
def get_fund_premium_rate_and_amount(fund_code: str):
detail = pandas.DataFrame(pysnowball.quote_detail(fund_code))
row1=detail.loc["quote"].iloc[0]
premium_rate1 = row1["premium_rate"]
current_price = row1["current"]
amount1 = row1["amount"]
amount1 = amount1/10000 if amount1 else 0
return current_price, premium_rate1, amount1
@xlwings.func
# 获取xq_a_token
def get_xq_a_token():
str_xq_a_token = ';'
while True:
cj = browser_cookie3.load()
for item in cj:
if item.name == "xq_a_token" :
print('get token, %s = %s' % (item.name, item.value))
str_xq_a_token = 'xq_a_token=' + item.value + ';'
return str_xq_a_token
if str_xq_a_token == ";" :
print('get token, retrying ......')
webbrowser.open("https://xueqiu.com/")
time.sleep(1)
@xlwings.func
# 根据排名计算排名分(精确到小数点后2位)
def get_rank_value(length: int, rank: int):
return round((length-rank)/length*100, 2)
@xlwings.func
def rotate_fund_by_premium_rate_and_20net_asset_value(source_sheets: str, dest_range: str, delay: int):
'''
根据20天净值增长率和溢价率来量化轮动基金
Parameters
----------
source_sheets : Excel里sheet名称
dest_range : 写回Excel的区域
delay : 延时
'''
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller() # wb = xlwings.Book(r'UniversalRotation.xlsm')
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
pysnowball.set_token(get_xq_a_token())
sheet_fund = wb.sheets[source_sheets]
# 数据表范围请参考Excel里的"最新数据"区域
source_range = 'H2:Y' + str(sheet_fund.used_range.last_cell.row)
print('数据表范围:' + source_range)
data_fund = pandas.DataFrame(sheet_fund.range(source_range).value,
columns=['基金代码','基金名称','投资种类','溢价率','5天净值增长率','10天净值增长率',
'20天净值增长率','60天净值增长率','120天净值增长率','250天净值增长率',
'500天净值增长率','750天净值增长率','总排名分','20天净值增长率排名分',
'溢价率排名分','成交额(万元)','Mark','持有周期'])
refresh_time = str(time.strftime("%Y-%m-%d__%H.%M.%S", time.localtime()))
sheet_fund.range('AA6').value = '更新时间:' + refresh_time
log_file = open('log-' + source_sheets + refresh_time + '.txt', 'a+')
for i,fund_code in enumerate(data_fund['基金代码']):
# 延时
if (i % 10 == 0) :
time.sleep(random.randrange(delay))
netAssetValueRaw = get_fund_net_asset_value_history(fund_code[2:8])
# 最新净值以及5个交易日前、10个交易日前、20个交易日前、60个交易日前、120个交易日前、250个交易日前、500个交易日前、750个交易日前的累计净值
netAssetDate1 = str(netAssetValueRaw.loc[0]['日期'])[0:10]
netAssetLJValue1 = netAssetValueRaw.loc[0]['累计净值']
netAssetDate20 = str(netAssetValueRaw.loc[len(netAssetValueRaw)-1]['日期'])[0:10]
netAssetLJValue5 = netAssetLJValue10 = netAssetLJValue20 = netAssetLJValue60 = netAssetLJValue120 \
= netAssetLJValue250 = netAssetLJValue500 \
= netAssetLJValue750 = netAssetValueRaw.loc[len(netAssetValueRaw)-1]['累计净值']
if (len(netAssetValueRaw) > 20) :
netAssetLJValue5 = netAssetValueRaw.loc[5]['累计净值']
netAssetLJValue10 = netAssetValueRaw.loc[10]['累计净值']
netAssetDate20 = str(netAssetValueRaw.loc[20]['日期'])[0:10]
netAssetLJValue20 = netAssetValueRaw.loc[20]['累计净值']
if (len(netAssetValueRaw) > 60) :
netAssetLJValue60 = netAssetValueRaw.loc[60]['累计净值']
if (len(netAssetValueRaw) > 120) :
netAssetLJValue120 = netAssetValueRaw.loc[120]['累计净值']
if (len(netAssetValueRaw) > 250) :
netAssetLJValue250 = netAssetValueRaw.loc[250]['累计净值']
if (len(netAssetValueRaw) > 500) :
netAssetLJValue500 = netAssetValueRaw.loc[500]['累计净值']
if (len(netAssetValueRaw) > 750) :
netAssetLJValue750 = netAssetValueRaw.loc[750]['累计净值']
# 更新5天、10天、20天、60天、120天、250天、500天、750天的累计净值增长率
netAssetLJValue5Rate = round((netAssetLJValue1 - netAssetLJValue5) / netAssetLJValue5, 4)
data_fund.loc[i, '5天净值增长率'] = netAssetLJValue5Rate
netAssetLJValue10Rate = round((netAssetLJValue1 - netAssetLJValue10) / netAssetLJValue10, 4)
data_fund.loc[i, '10天净值增长率'] = netAssetLJValue10Rate
netAssetLJValue20Rate = round((netAssetLJValue1 - netAssetLJValue20) / netAssetLJValue20, 4)
data_fund.loc[i, '20天净值增长率'] = netAssetLJValue20Rate
data_fund.loc[i, '60天净值增长率'] = round((netAssetLJValue1 - netAssetLJValue60) / netAssetLJValue60, 4)
data_fund.loc[i, '120天净值增长率'] = round((netAssetLJValue1 - netAssetLJValue120) / netAssetLJValue120, 4)
data_fund.loc[i, '250天净值增长率'] = round((netAssetLJValue1 - netAssetLJValue250) / netAssetLJValue250, 4)
data_fund.loc[i, '500天净值增长率'] = round((netAssetLJValue1 - netAssetLJValue500) / netAssetLJValue500, 4)
data_fund.loc[i, '750天净值增长率'] = round((netAssetLJValue1 - netAssetLJValue750) / netAssetLJValue750, 4)
# 更新基金的市价、溢价率、成交量
current_price,fundPremiumRateValue,fundAmount = get_fund_premium_rate_and_amount(fund_code)
netAssetDWValue1 = netAssetValueRaw.loc[0]['单位净值']
if (current_price) :
fundPremiumRateValue = round((current_price - netAssetDWValue1) / netAssetDWValue1, 4)
data_fund.loc[i, '溢价率'] = fundPremiumRateValue
data_fund.loc[i, '成交额(万元)'] = fundAmount
log_str = 'No.' + format(str(i), "<6") + fund_code + ':'+ format(data_fund.loc[i, '基金名称'], "<15") \
+ netAssetDate1 + ':净值:' + format(str(netAssetLJValue1), "<10") \
+ netAssetDate20 + ':净值:' + format(str(netAssetLJValue20), "<10") \
+ '二十个交易日净值增长率:' + format(str(netAssetLJValue20Rate), "<10") \
+ '溢价率:'+ format(str(fundPremiumRateValue), "<10")
print(log_str)
print(log_str, file=log_file)
# 更新'溢价率排名分'
data_fund = data_fund.sort_values(by='溢价率', ascending=True)
data_fund.reset_index(drop=True, inplace=True)
for i,fundPremiumRateValueItem in enumerate(data_fund['溢价率']):
data_fund.loc[i, '溢价率排名分'] = get_rank_value(len(data_fund), i)
# 更新'20天净值增长率排名分'
data_fund = data_fund.sort_values(by='20天净值增长率', ascending=False)
data_fund.reset_index(drop=True, inplace=True)
for i,netAssetLJValue20RateItem in enumerate(data_fund['20天净值增长率']):
data_fund.loc[i, '20天净值增长率排名分'] = get_rank_value(len(data_fund), i)
# 计算'总排名分'
for i,sumValue in enumerate(data_fund['总排名分']):
data_fund.loc[i, '总排名分'] = data_fund.loc[i, '溢价率排名分'] + data_fund.loc[i, '20天净值增长率排名分']
data_fund = data_fund.sort_values(by='总排名分', ascending=False)
data_fund.reset_index(drop=True, inplace=True)
# 根据排名更新'总排名分'
for i,fundPremiumRateValue in enumerate(data_fund['总排名分']):
data_fund.loc[i, '总排名分'] = get_rank_value(len(data_fund), i)
# 将数据起始下标从1开始计数
data_fund.index += 1
print(data_fund)
print(data_fund, file=log_file)
log_file.close()
# 更新数据到原Excel
sheet_fund.range(dest_range).value = data_fund
wb.save()
@xlwings.func
# 轮动20天净值增长和溢价率选LOF、ETF和封基
def rotate_LOF_ETF():
print("------------------------20天净值增长率和溢价率轮动LOF、ETF和封基-------------------------------------------------")
rotate_fund_by_premium_rate_and_20net_asset_value('20天净值增长率和溢价率轮动LOF、ETF和封基','G1', 10)
@xlwings.func
# 轮动20天净增和溢价率选债券和境外基金
def rotate_abroad_fund():
print("-----------------------20天净值增长率和溢价率轮动债券和境外基金---------------------------------------------------")
rotate_fund_by_premium_rate_and_20net_asset_value('20天净值增长率和溢价率轮动债券和境外基金', 'G1', 10)
source_range_convertible_bond = 'B8:T'
# 获取可转债实时数据列表上方的多因子策略的阈值上限和权重
def get_convertible_bond_factor(factor:str):
factor = factor.split(',', -1)
return float(factor[0]), float(factor[1])
@xlwings.func
# 更新可转债实时数据:价格、涨跌幅、转股价、转股价值、溢价率、双低值、到期时间、剩余年限、剩余规模、成交金额、换手率、税前收益、振幅等
def refresh_convertible_bond():
print("更新可转债实时数据:价格、涨跌幅、转股价、转股价值、溢价率、双低值、到期时间、剩余年限、剩余规模、成交金额、换手率、税前收益、振幅等")
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller()
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
pysnowball.set_token(get_xq_a_token())
source_sheets = '可转债实时数据'
sheet_fund = wb.sheets[source_sheets]
source_range = source_range_convertible_bond + str(sheet_fund.used_range.last_cell.row)
print('数据表范围:' + source_range)
data_fund = pandas.DataFrame(sheet_fund.range(source_range).value,
columns=['转债代码','转债名称','当前价','涨跌幅','转股价','转股价值','溢价率','双低值',
'到期时间','剩余年限','剩余规模','成交金额','换手率','税前收益','最高价','最低价',
'振幅','多因子1排名','多因子2排名'])
refresh_time = str(time.strftime("%Y-%m-%d__%H.%M.%S", time.localtime()))
sheet_fund.range('W12').value = '更新时间:' + refresh_time
log_file = open('log-' + source_sheets + refresh_time + '.txt', 'a+')
for i,fund_code in enumerate(data_fund['转债代码']):
if str(fund_code).startswith('11') or str(fund_code).startswith('13'):
fund_code_str = ('SH' + str(fund_code))[0:8]
elif str(fund_code).startswith('12'):
fund_code_str = ('SZ' + str(fund_code))[0:8]
detail = pandas.DataFrame(pysnowball.quote_detail(fund_code_str))
row1 = detail.loc["quote"].iloc[0]
data_fund.loc[i, '当前价'] = row1["current"]
data_fund.loc[i, '涨跌幅'] = row1["percent"] / 100 if row1["percent"] != None else '停牌'
data_fund.loc[i, '转股价'] = row1["conversion_price"]
data_fund.loc[i, '转股价值'] = row1["conversion_value"]
data_fund.loc[i, '溢价率'] = row1["premium_rate"] / 100 if row1["premium_rate"] != None else '停牌'
data_fund.loc[i, '双低值'] = row1["current"] + row1["premium_rate"]
data_fund.loc[i, '到期时间'] = str(time.strftime("%Y-%m-%d", time.localtime(row1["maturity_date"]/1000)))
data_fund.loc[i, '剩余年限'] = row1["remain_year"]
data_fund.loc[i, '剩余规模'] = row1["outstanding_amt"] / 100000000 if row1["outstanding_amt"] != None else 1
data_fund.loc[i, '成交金额'] = row1["amount"] / 10000 if row1["amount"] != None else 0
data_fund.loc[i, '换手率'] = (data_fund.loc[i, '成交金额'] / 10000 / row1["current"]) / (data_fund.loc[i, '剩余规模'] / 100)
data_fund.loc[i, '税前收益'] = row1["benefit_before_tax"] / 100 if row1["benefit_before_tax"] != None else '停牌'
data_fund.loc[i, '最高价'] = row1["high"]
data_fund.loc[i, '最低价'] = row1["low"]
if row1["high"] and row1["low"]:
data_fund.loc[i, '振幅'] = (row1["high"] - row1["low"]) / row1["low"]
else:
data_fund.loc[i, '振幅'] = '停牌'
log_str = 'No.' + format(str(i), "<6") + format(str(fund_code_str), "<10") \
+ format(data_fund.loc[i, '转债名称'], "<15") \
+ '当前价:' + format(str(row1["current"]), "<10") \
+ '溢价率:' + format(str(row1["premium_rate"]), "<10") \
+ '涨跌幅:'+ format(str(row1["percent"]), "<10")
print(log_str)
print(log_str, file=log_file)
data_fund = data_fund.sort_values(by='溢价率')
data_fund.reset_index(drop=True, inplace=True)
data_fund.index += 1
print(data_fund)
print(data_fund, file=log_file)
log_file.close()
# 更新原Excel
sheet_fund.range('A7').value = data_fund
wb.save()
@xlwings.func
# 更新低溢价可转债数据
def refresh_premium_rate_convertible_bond():
print("--------------------------------------更新低溢价可转债数据----------------------------------------------------")
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller()
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
sheet_src = wb.sheets['可转债实时数据']
source_range = source_range_convertible_bond + str(sheet_src.used_range.last_cell.row)
data_fund_source = pandas.DataFrame(sheet_src.range(source_range).value,
columns=['转债代码','转债名称','当前价','涨跌幅','转股价','转股价值','溢价率','双低值',
'到期时间','剩余年限','剩余规模','成交金额','换手率','税前收益','最高价','最低价',
'振幅','多因子1排名','多因子2排名'])
data_fund_destination = data_fund_source[['转债代码','转债名称','当前价','溢价率','剩余规模']]
data_fund_destination = data_fund_destination[(data_fund_destination['当前价'] < sheet_src.range('D2').value) &
(data_fund_destination['溢价率'] < sheet_src.range('H2').value) &
(data_fund_destination['剩余规模'] < sheet_src.range('L2').value)]
data_fund_destination = data_fund_destination.sort_values(by='溢价率')
data_fund_destination.reset_index(drop=True, inplace=True)
data_fund_destination.index += 1
print(data_fund_destination)
# 更新低溢价可转债轮动sheet
sheet_dest = wb.sheets['低溢价可转债轮动']
sheet_dest.range('H2').value = data_fund_destination[:50]
wb.save()
@xlwings.func
# 更新双低可转债数据
def refresh_price_and_premium_rate_convertible_bond():
print("----------------------------------------更新双低可转债数据----------------------------------------------------")
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller()
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
sheet_src = wb.sheets['可转债实时数据']
source_range = source_range_convertible_bond + str(sheet_src.used_range.last_cell.row)
data_fund_source = pandas.DataFrame(sheet_src.range(source_range).value,
columns=['转债代码','转债名称','当前价','涨跌幅','转股价','转股价值','溢价率','双低值',
'到期时间','剩余年限','剩余规模','成交金额','换手率','税前收益','最高价','最低价',
'振幅','多因子1排名','多因子2排名'])
data_fund_destination = data_fund_source[['转债代码','转债名称','当前价','溢价率','双低值','剩余规模']]
data_fund_destination = data_fund_destination[(data_fund_destination['当前价'] < sheet_src.range('D3').value) &
(data_fund_destination['溢价率'] < sheet_src.range('H3').value) &
(data_fund_destination['剩余规模'] < sheet_src.range('L3').value)]
data_fund_destination = data_fund_destination.sort_values(by='双低值')
data_fund_destination.reset_index(drop=True, inplace=True)
data_fund_destination.index +=1
print(data_fund_destination)
# 更新双低可转债轮动sheet
sheet_dest = wb.sheets['双低可转债轮动']
sheet_dest.range('H2').value = data_fund_destination[:50]
wb.save()
@xlwings.func
# 更新多因子1可转债数据
def refresh_multifactor1_convertible_bond():
print("--------------------------------------更新多因子1可转债数据----------------------------------------------------")
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller()
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
sheet_src = wb.sheets['可转债实时数据']
source_range = source_range_convertible_bond + str(sheet_src.used_range.last_cell.row)
data_fund_source = pandas.DataFrame(sheet_src.range(source_range).value,
columns=['转债代码','转债名称','当前价','涨跌幅','转股价','转股价值','溢价率','双低值',
'到期时间','剩余年限','剩余规模','成交金额','换手率','税前收益','最高价','最低价',
'振幅','多因子1排名','多因子2排名'])
data_fund_destination = data_fund_source[['转债代码','转债名称','当前价','溢价率','剩余规模']]
threshold_current_price, weight_current_price = get_convertible_bond_factor(sheet_src.range('D5').value)
threshold_premium_rate, weight_premium_rate = get_convertible_bond_factor(sheet_src.range('H5').value)
threshold_outstanding_amt, weight_outstanding_amt = get_convertible_bond_factor(sheet_src.range('L5').value)
# for i, fund_code in enumerate(data_fund_source['转债代码']):
# data_fund_source.loc[i, '多因子1排名'] = data_fund_source.loc[i, '当前价'] * weight_current_price
# + data_fund_source.loc[i, '溢价率'] * weight_premium_rate
# + data_fund_source.loc[i, '剩余规模'] * weight_outstanding_amt
data_fund_destination = data_fund_destination[(data_fund_destination['当前价'] < threshold_current_price) &
(data_fund_destination['溢价率'] < threshold_premium_rate) &
(data_fund_destination['剩余规模'] < threshold_outstanding_amt)]
data_fund_destination = data_fund_destination.sort_values(by='溢价率')
data_fund_destination.reset_index(drop=True, inplace=True)
data_fund_destination.index += 1
print(data_fund_destination)
# 更新低溢价可转债轮动sheet
sheet_dest = wb.sheets['低溢价可转债轮动']
sheet_dest.range('Q2').value = data_fund_destination[:50]
wb.save()
@xlwings.func
# 更新多因子2可转债数据
def refresh_multifactor2_convertible_bond():
print("----------------------------------------更新多因子2可转债数据----------------------------------------------------")
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller()
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
sheet_src = wb.sheets['可转债实时数据']
source_range = source_range_convertible_bond + str(sheet_src.used_range.last_cell.row)
data_fund_source = pandas.DataFrame(sheet_src.range(source_range).value,
columns=['转债代码','转债名称','当前价','涨跌幅','转股价','转股价值','溢价率','双低值',
'到期时间','剩余年限','剩余规模','成交金额','换手率','税前收益','最高价','最低价',
'振幅','多因子1排名','多因子2排名'])
data_fund_destination = data_fund_source[['转债代码','转债名称','当前价','溢价率','剩余规模']]
threshold_current_price, weight_current_price = get_convertible_bond_factor(sheet_src.range('D6').value)
threshold_premium_rate, weight_premium_rate = get_convertible_bond_factor(sheet_src.range('H6').value)
threshold_outstanding_amt, weight_outstanding_amt = get_convertible_bond_factor(sheet_src.range('L6').value)
data_fund_destination = data_fund_destination[(data_fund_destination['当前价'] < threshold_current_price) &
(data_fund_destination['溢价率'] < threshold_premium_rate) &
(data_fund_destination['剩余规模'] < threshold_outstanding_amt)]
data_fund_destination = data_fund_destination.sort_values(by='溢价率')
data_fund_destination.reset_index(drop=True, inplace=True)
data_fund_destination.index += 1
print(data_fund_destination)
# 更新双低可转债轮动sheet
sheet_dest = wb.sheets['双低可转债轮动']
sheet_dest.range('R2').value = data_fund_destination[:50]
wb.save()
@xlwings.func
# 更新股票实时数据:价格、涨跌幅等
def refresh_stock():
print("更新股票实时数据:价格、涨跌幅等")
xlwings.Book("UniversalRotation.xlsm").set_mock_caller()
wb = xlwings.Book.caller()
pandas.options.display.max_columns = None
pandas.options.display.max_rows = None
pysnowball.set_token(get_xq_a_token())
source_sheets = '股票实时数据'
sheet_fund = wb.sheets[source_sheets]
source_range = 'B2:E' + str(sheet_fund.used_range.last_cell.row)
print('数据表范围:' + source_range)
data_fund = pandas.DataFrame(sheet_fund.range(source_range).value,
columns=['股票代码','股票名称','当前价','涨跌幅'])
refresh_time = str(time.strftime("%Y-%m-%d__%H.%M.%S", time.localtime()))
sheet_fund.range('W3').value = '更新时间:' + refresh_time
log_file = open('log-' + source_sheets + refresh_time + '.txt', 'a+')
for i,fund_code in enumerate(data_fund['股票代码']):
detail = pandas.DataFrame(pysnowball.quote_detail(fund_code))
row1 = detail.loc["quote"].iloc[0]
print(str(row1))
# data_fund.loc[i, '当前价'] = row1["current"]
# data_fund.loc[i, '涨跌幅'] = row1["percent"] / 100 if row1["percent"] != None else '停牌'
# data_fund.loc[i, '转股价'] = row1["conversion_price"]
# data_fund.loc[i, '转股价值'] = row1["conversion_value"]
# data_fund.loc[i, '溢价率'] = row1["premium_rate"] / 100 if row1["premium_rate"] != None else '停牌'
# data_fund.loc[i, '双低值'] = row1["current"] + row1["premium_rate"]
# data_fund.loc[i, '到期时间'] = str(time.strftime("%Y-%m-%d", time.localtime(row1["maturity_date"]/1000)))
# data_fund.loc[i, '剩余年限'] = row1["remain_year"]
# data_fund.loc[i, '剩余规模'] = row1["outstanding_amt"] / 100000000 if row1["outstanding_amt"] != None else 1
# data_fund.loc[i, '成交金额'] = row1["amount"] / 10000 if row1["amount"] != None else 0
# data_fund.loc[i, '换手率'] = (data_fund.loc[i, '成交金额'] / 10000 / row1["current"]) / (data_fund.loc[i, '剩余规模'] / 100)
# data_fund.loc[i, '税前收益'] = row1["benefit_before_tax"] / 100 if row1["benefit_before_tax"] != None else '停牌'
# data_fund.loc[i, '最高价'] = row1["high"]
# data_fund.loc[i, '最低价'] = row1["low"]
# if row1["high"] and row1["low"]:
# data_fund.loc[i, '振幅'] = (row1["high"] - row1["low"]) / row1["low"]
# else:
# data_fund.loc[i, '振幅'] = '停牌'
# log_str = 'No.' + format(str(i), "<6") + format(str(fund_code_str), "<10") \
# + format(data_fund.loc[i, '转债名称'], "<15") \
# + '当前价:' + format(str(row1["current"]), "<10") \
# + '溢价率:' + format(str(row1["premium_rate"]), "<10") \
# + '涨跌幅:'+ format(str(row1["percent"]), "<10")
# print(log_str)
# print(log_str, file=log_file)
#
# data_fund = data_fund.sort_values(by='溢价率')
# data_fund.reset_index(drop=True, inplace=True)
# data_fund.index += 1
# print(data_fund)
# print(data_fund, file=log_file)
log_file.close()
# 更新原Excel
sheet_fund.range('A1').value = data_fund
wb.save()
def main_function():
# date = datetime.datetime.now().date()
# if not is_workday(date):
# return
webbrowser.open("https://xueqiu.com/")
#删除旧log
for eachfile in os.listdir('./'):
filename = os.path.join('./', eachfile)
if os.path.isfile(filename) and filename.startswith("./log") :
os.remove(filename)
rotate_LOF_ETF()
webbrowser.open("https://xueqiu.com/")
refresh_convertible_bond()
refresh_premium_rate_convertible_bond()
refresh_price_and_premium_rate_convertible_bond()
refresh_multifactor1_convertible_bond()
refresh_multifactor2_convertible_bond()
rotate_abroad_fund()
# 更新股票实时数据
refresh_stock()
def main():
main_function()
schedule.every().day.at("07:00").do(main_function) # 部署7:00执行更新数据任务
while True:
schedule.run_pending()
if __name__ == "__main__":
main()