基金分析,定时邮件提示

寒假搞基金,写了一个定时提醒的脚本,开学后就不用每天都关注行情了。策略很简单,在定投的基础上,多退少补。涨幅过高赎回,每周四逢低加倍。


执行的效果如图

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
import requests
import pandas as pd
import re
import sys
import math
import json
import smtplib
from email.mime.text import MIMEText
import time
import datetime
import numpy as np

def timeStamp_to_time_13(timeNum):
timeStamp = float(timeNum/1000)
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

def is_trade_day(date):
server_url = "http://www.easybots.cn/api/holiday.php?d="
# 假如今天是周日
date1 = "".join(date.split('-'))
while(1):
req = requests.get(server_url + date1)
vop_data = json.loads(req.text)
if int(vop_data[date1]) == 2:#节假日
return False
elif int(vop_data[date1]) == 1:#周末
return False
else:
return True
time.sleep(3)
# #now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
# sunday = date1.weekday()
# #print(sunday)
# # 如果今天是周日,则返回True
# if sunday == 6 or sunday == 5:
# return False
# else:
# return False
def get_month_year_firstday(error_month = 0):
#获得第一个不是周末的月初和年初日子

for i in range(1,10):

if(error_month == 1):
m_tmp = datetime.datetime.now().strftime('%m')
m_tmp = str(int(m_tmp)-1).rjust(2,"0")
month = datetime.datetime.now().strftime('%Y')+"-"+m_tmp+"-"+str(i).rjust(2,"0")
else:
month = datetime.datetime.now().strftime('%Y-%m')+"-"+str(i).rjust(2,"0")
if is_trade_day(month):
break
for i in range(1,10):
year = datetime.datetime.now().strftime('%Y')+"-01-"+str(i).rjust(2,"0")
if is_trade_day(year):
break

print(month,year)
return month,year
def get_daily_prise(date,fund_code):
"""
:param url: 网页URL
:parma date: 时间日期2020-01-16
:return: 累计净值和日增长率
"""
headers = {"Referer":"http://fundf10.eastmoney.com/jjjz_001811.html","Host":"api.fund.eastmoney.com"}
url = "http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery18305100678071626792_1580736628860&fundCode="+fund_code+"&pageIndex=1&pageSize=20&startDate="+date+"&endDate="+date+"&_=1580736651052"
response = requests.request("GET", url, headers=headers)
tmp = json.loads(response.text[41:-1])['Data']
try:
print("success")
print(tmp['LSJZList'][0]['LJJZ'],tmp['LSJZList'][0]['JZZZL'])
return(tmp['LSJZList'][0]['LJJZ'],tmp['LSJZList'][0]['JZZZL'])
except IndexError:
print("IndexError")
return ("error","error")


def my_mail(message,conf):

msg_from=conf['sender'] #发送方邮箱
passwd=conf['password'] #填入发送方邮箱的授权码
msg_to_list=conf['receiver'] #收件人邮箱

subject="基金邮箱提示"
#print(message)
msg = MIMEText(message,"html")
msg['Subject'] = subject
msg['From'] = msg_from

for i in range(len(msg_to_list)):
msg_to = msg_to_list[i]
msg['To'] = msg_to
try:
s = smtplib.SMTP_SSL("smtp.qq.com",465)
s.login(msg_from, passwd) #登录SMTP服务器
s.sendmail(msg_from, msg_to, msg.as_string())#发邮件 as_string()把MIMEText对象变成str
print ("发送成功")
except s.SMTPException:
print ("发送失败")
finally:
s.quit()

def get_resonse(url):
"""
:param url: 网页URL
:return: 爬取的文本信息
"""
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = 'utf-8'
return r.text
except:
print('Failed to get response to url!')
return ''
def get_realtime_anayls(code):
url = "http://fundgz.1234567.com.cn/js/"+code+".js"
r = get_resonse(url)
text_json = json.loads(r[8:-2])
return text_json

def get_fund_info(code):
failed_list = []
data_list = {}
url = 'http://fund.eastmoney.com/pingzhongdata/'+code+'.js'
response = get_resonse(url)
# 爬取失败等待再次爬取
if response is '':
return ''
else:
strs = re.findall(r'var(.*?);',response)
for i in range(0,len(strs)):
tmp = strs[i].split('=')
var_name = tmp[0].strip()
data_list[var_name] = [tmp[1]]
return data_list

def getYesterday(today=datetime.date.today()):

for i in range(1,100):
oneday=datetime.timedelta(days=i)
yesterday=today-oneday
print(yesterday)
if(is_trade_day(yesterday.strftime('%Y-%m-%d'))):
return yesterday

def make_csv():
fund_list = read_fund_list()
#print(fund_list)
yesterday_time = getYesterday()
print(yesterday_time)
now_date = yesterday_time.strftime('%Y-%m-%d')
final = []
final.append(['基金名称','今日累计净值','今日净增长'+now_date,'年初增长率','月初增长率','28号加倍','周四加倍','是否赎回'])
for i in range(1,len(fund_list)):
stock_json_str = get_fund_info(fund_list[i])
#stock_json = json.loads(stock_json_str)
tmp = []
tmp.append(stock_json_str['fS_name'][0].split('"')[1])
a,b = get_daily_prise(now_date,fund_list[i])
tmp.append(a)
tmp.append(b+'%')

print("年初和月初")
month,year = get_month_year_firstday()
#print( month,year)
month_price,rub = get_daily_prise(month,fund_list[i])
if month_price == "error":
month,year = get_month_year_firstday(error_month = 1)
month_price,rub = get_daily_prise(month,fund_list[i])
year_price,rub = get_daily_prise(year,fund_list[i])
print(year_price,month_price)
tmp.append(str((float(a)/float(year_price) - 1) * 100).ljust(5,"0")+"%")
tmp.append(str((float(a)/float(month_price) - 1) * 100).ljust(5,"0")+"%")
if((float(a)/float(year_price) - 1)<-0.05):
tmp.append("定投加三倍")
elif((float(a)/float(year_price) - 1)<-0.03):
tmp.append("定投加两倍")
elif((float(a)/float(year_price) - 1)<0.1):
tmp.append("不变")
else:
tmp.append("停止投入")


if((float(a)/float(month_price) - 1)<-0.05):
tmp.append("定投加三倍")
elif((float(a)/float(month_price) - 1)<-0.03):
tmp.append("定投加两倍")
elif((float(a)/float(month_price) - 1)<0.1):
tmp.append("不变")
else:
tmp.append("停止投入")


if((float(a)/float(month_price) - 1)>0.2):
tmp.append("赎回"+str((float(a)/float(month_price) - 1)-0.1))
elif((float(a)/float(month_price) - 1)>0.5):
tmp.append("赎回"+str((float(a)/float(month_price) - 1)-0.1))
else:
tmp.append("不必")
final.append(tmp)
df = pd.DataFrame(final,index=fund_list, columns=['基金名称','今日累计净值','今日净增长'+now_date,'年初增长率','月初增长率','28号加倍','周四加倍','是否赎回'])#生成6行4列位置
outputpath='fund.csv'
df.to_csv(outputpath,sep=',',index=False,header=False,encoding='utf_8_sig')
return(df)

def read_fund_list():
#read txt method one
f = open("fund_list.txt")
ans = []
ans.append("/")
line = f.readline()
ans.append(line.replace("\n",""))
while line:
line = f.readline()
ans.append(line.replace("\n",""))
f.close()
return list(filter(None, ans))

if __name__ == '__main__':
stock_json_str = get_fund_info("001811")
#stock_json = json.loads(stock_json_str)
# for i in stock_json_str.keys():
# print(i+":")
# print(stock_json_str[i])
# print("---------------------------------------------------------------------\n")

# text = get_realtime_anayls("001811")
#
# print(text_json)
# w782 comm lsjz


# timeStamp_to_time_13(1580728885284)
# is_week_lastday("2020-01-08")
df = make_csv()
conf = {'sender': 'qqnumber@qq.com', 'sender_name':'guo',
'receiver':['qqnumber@qq.com','qqnumber@qq.com'], 'password':'*********',
'server':'smtp.qq.com','port':465, 'receiver_name':['me','guest']}
df=pd.read_csv("fund.csv")
df.sort_values('月初增长率',inplace = False)
my_mail(df.to_html(),conf)
#print(get_realtime_anayls("001811"))

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2015-2024 galaxy
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信