从小白出发带你领略Python爬虫之美,关注微信公众号:机智出品(jizhjchupin),免费获取源代码及实战教程
一、系统环境:
Windows7+Python3.6
二、结果展示:
对于没时间去看自己关注股票或者基金的,可以个性化定制内容,将这个小脚本放在电脑上配合定期运行,就可以收到邮件提醒。这个程序通过tushare获取股票行情数据,matplotlib对走势数据绘图并保存,email将需要订阅的提醒发送至指定邮箱。
提醒邮件.png
三、代码解释:
step1:需要的库
import requestsimport tushare as tsimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.pyplot as savefigimport numpy as npfrom datetime import datetimeimport matplotlib.dates as mdatesimport smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.image import MIMEImagefrom datetime import timedelta, datefrom bs4 import BeautifulSoup
step2:tushare获取股票行情
TuShare是一个免费、开源的python财经数据接口包。关于怎么用可以去tushare网站看看。
#获取所有股票代码,用于判断代码是基金还是股票def get_allcode(): allcode=[] stock_info=ts.get_stock_basics() for i in stock_info.index: allcode.append(i) return allcode#获取股票行情def stock(code): df = ts.get_realtime_quotes(code) temp=df[['code','name','open','price','high','low','date','time']] temp=np.array(temp) lists=temp.tolist() stock_now=lists[0] return stock_now#获取股票历史行情def history_stock(code): start_date=str(date.today()-timedelta(days=15)) end_date=str(date.today()) df=ts.get_k_data(code,start=start_date, end=end_date) temp=df[['date','open','high','low','close','volume']] temp=np.array(temp) stock_info=temp.tolist() #print(stock_info) return stock_info
step3:matplotlib绘制行情走势折线图
这里就是绘制了一个简单的股价走势折线图,需要更深入分析的可以看matplotlib教程画K线图。
#matplotlib绘制股价走势图def picture(code): time=[] value=[] stock_info=history_stock(code)#历史行情 for i in range(len(stock_info)): time.append(stock_info[i][0]) value.append(stock_info[i][4]) plt.figure(figsize=(10,3)) xs = [datetime.strptime(d, '%Y-%m-%d').date() for d in time] plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.plot(xs,value,color="b",linewidth=1,marker='o',markerfacecolor='red',markersize=4) #在当前绘图对象绘图(X轴,Y轴,蓝色虚线,线宽度) plt.gcf().autofmt_xdate()#时间旋转 plt.xlabel("Time") #X轴标签 plt.ylabel("Price") #Y轴标签 plt.title(code) #图标题 plt.grid()#框线 plt.savefig(code+".jpg") #保存图 #plt.show() #显示图
step4:邮件内容发送邮件
SMTP发邮件可以在廖雪峰老师网站学习
#邮件内容def content(stock_now): code=stock_now[0] name=stock_now[1] openprice=stock_now[2] price=stock_now[3] high=stock_now[4] low=stock_now[5] date=stock_now[6] time=stock_now[7] changepercent=(float(price)-float(openprice))/float(openprice) changepercent='%.2f%%' % (changepercent * 100) if round(float(price)-float(openprice),3)>0: color='red'#涨用红色 else: color='green'#跌用绿色 con='<html><body><b>%s[%s]</b><p><font>%s %s</font></p><p><font size="3" color="%s">%s--%s(%s)</font></p><p>最高价:%s 最低价%s</p><p>![](cid:0)</p></body></html>'%(name,code,date,time,color,price,round(float(price)-float(openprice),3),changepercent,high,low) return con#发送邮件def sendemail(code,con,stock_now): mail_host = '服务器' mail_user = '用户名' mail_pass = '密码' sender = '邮箱地址' receivers = ['对方邮箱地址'] end_date=str(date.today()) name=stock_now[1] title = end_date+name+'['+code+']' message = MIMEMultipart() message['From'] = sender message['To'] = receivers[0] message['Subject'] = title part1 = MIMEText(con,'html','utf-8') with open(code+'.jpg','rb')as fp: picture = MIMEImage(fp.read()) picture['Content-Type'] = 'application/octet-stream' picture['Content-Disposition'] = 'attachment;filename="%s.jpg"'%(code) picture['Content-ID'] = '<0>' picture['X-Attachment-Id'] = '0' message.attach(part1) message.attach(picture) try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host,25) smtpObj.login(mail_user,mail_pass) print('邮箱登录成功') smtpObj.sendmail( sender,receivers,message.as_string()) print('邮件发送成功') smtpObj.quit() except Exception as e: print('error',e)
step5:主程序
在同一个文件夹内放一个code.txt文件,分行写入需要关注的股票和基金代码。上面只展示了股票,关于基金部分可以在文章底部链接下载本脚本。读取后放入列表循环发送邮件。matplotlib要正常显示中文和负数需要加两句:
plt.rcParams['font.sans-serif']=['SimHei']#显示中文
plt.rcParams['axes.unicode_minus'] = False #负数
def main(): codes=[] with open('code.txt','r') as f: for line in f.readlines(): codes.append(line.strip()) allcode=get_allcode() i=0 for code in codes: i=i+1 if code in allcode: print('---------%s-----------股票:%s------------'%(i,code)) stock_now=stock(code) con=content(stock_now) picture(code) sendemail(code,con,stock_now) else: print('---------%s-----------基金:%s------------'%(i,code)) getFundNav(code) fund_info=fund_now(code) con=fund_content(fund_info) sendemail(code,con,fund_info) plt.rcParams['font.sans-serif']=['SimHei']#显示中文plt.rcParams['axes.unicode_minus'] = False #负数if __name__ == "__main__": main()
作者:机智出品
链接:https://www.jianshu.com/p/95cb7d5d72f8
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦