起初需求是这样的,新手买卖股票,容易犯的一个错误就是频繁看盘,于是我就把买卖股票的软件卸载了,可是我又想知道自己的总盈亏,该怎么办呢?
我想有没有办法通过脚本获取特定几支股票的最新收盘价,并根据自己买入的成本计算收益,然后每天定时的发邮件给自己。比如每个工作日的下午3点半。下面这个脚本就是用来干这个事情的。邮件正文是自己买入几支股票的最新收盘价,最新涨跌,以及最新盈亏。同时附件内容为最近n天内的总盈亏,可通过绘制直方图查看盈亏的趋势。
import pandas as pdimport tushare as tsdef income(cost, price, num):return round((price - cost) * num, 3)def get_stock_detail(days, code, desc, cost, num):df = ts.get_hist_data(code)# 收盘价 涨跌幅df = df[['close', 'p_change']][:days]df['income'] = df['close'].apply(lambda s: income(cost, s, num))a = [[desc] * 3, ['close', 'p_change', 'income']]index = pd.MultiIndex.from_arrays(a, names=['股票名称', '行情'])df.columns = indexreturn dfdays = 10code = ['000651', '002230', '002415', '002236']desc = ['格力电器', '科大讯飞', '海康威视', '大华股份']cost = [64.89, 31.056, 33.077, 19.47]num = [200, 300, 300, 500]# 将查询结果进行横向拼接res = pd.DataFrame()for i in range(len(code)):df = get_stock_detail(days, code[i], desc[i], cost[i], num[i])res = pd.concat([res, df], axis=1)# 计算总收益res['total_income'] = 0for i in range(len(code)):res['total_income'] += res[(desc[i], 'income')]res['total_income'] = round(res['total_income'], 3)# 写入文件file_name = "最近" + str(days) + "日盈亏汇总.txt"res['total_income'].to_csv(file_name, sep="\t", index=True, encoding='utf-8', header=True)# 通过直方图的形式直观查看# res['total_income'].sort_index().plot.bar()#---------------------------获取当天日期-----------------------------from datetime import datetimedt = datetime.now()y = dt.yearm = dt.monthd = dt.daydef format(n):return str(0) + str(n) if n < 10 else str(n)curDay = str(y) + '-' + format(m) + '-' + format(d)#---------------------------发送邮件---------------------------------import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartfrom email.mime.application import MIMEApplication# 第三方 SMTP 服务mail_host="smtp.qq.com" #设置服务器mail_user="jinfeng.wang60@qq.com" #用户名mail_pass="xxxxxx" #密码authentication_pass="xxxxxx" # 授权码sender = 'jinfeng.wang60@qq.com'# 多个收件人,用列表组装receivers = "jinfeng.wang60@qq.com"# 正文内容priceDesc = '\n格力最新收盘价:' + str(res.iloc[0][(desc[0], 'close')])priceDesc += '\n格力最新涨跌幅:' + str(res.iloc[0][(desc[0], 'p_change')])priceDesc += '\n格力盈亏:' + str(res.iloc[0][(desc[0], 'income')])priceDesc += '\n'priceDesc += '\n科大最新收盘价:' + str(res.iloc[0][(desc[1], 'close')])priceDesc += '\n科大最新涨跌幅:' + str(res.iloc[0][(desc[1], 'p_change')])priceDesc += '\n科大盈亏:' + str(res.iloc[0][(desc[1], 'income')])priceDesc += '\n'priceDesc += '\n海康最新收盘价:' + str(res.iloc[0][(desc[2], 'close')])priceDesc += '\n海康最新涨跌幅:' + str(res.iloc[0][(desc[2], 'p_change')])priceDesc += '\n海康盈亏:' + str(res.iloc[0][(desc[2], 'income')])priceDesc += '\n'priceDesc += '\n大华最新收盘价:' + str(res.iloc[0][(desc[3], 'close')])priceDesc += '\n大华最新涨跌幅:' + str(res.iloc[0][(desc[3], 'p_change')])priceDesc += '\n大华盈亏:' + str(res.iloc[0][(desc[3], 'income')])priceDesc += '\n'# 附件txtPart = MIMEApplication(open(file_name, 'rb').read())txtPart.add_header('Content-Disposition', 'attachment', filename=file_name)m = MIMEMultipart()textApart = MIMEText(priceDesc, 'plain', 'utf-8')m.attach(txtPart)m.attach(textApart)m['From'] = senderm['to'] = receivers#邮件主题subject = ' ' + curDay + ' 累计总盈亏: ' + str(res['total_income'][0])m['Subject'] = subjecttry:smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号smtpObj.login(mail_user,authentication_pass)smtpObj.sendmail(sender, receivers, m.as_string())print (curDay + " 邮件发送成功\n")except smtplib.SMTPException as e:print ("Error: 无法发送邮件")print(e)
要想让这个脚本完整的跑起来,有几个条件需要满足一下:
- 电脑要有python的环境,可以跑python脚本
- 安装pandas,tushare,lxml库 (如果报错说缺少什么库,直接使用pip install 命令进行安装即可)
- 替换脚本中的用户名,密码,授权码,收件人邮箱,发件人邮箱为自己的。
这样就可以跑起来了,甚至可以根据自己的实际需求用起来。要想做价值投资者,股价没必要天天看,如果是好公司的股票,那好好拿着就是,多分析下公司本身,行业大趋势,经济政策这些,同时增加自己的投资知识储备。要记住:投资靠的是国运和时间的复利;同时投资和生活中的一切都息息相关。
我是通过crontab来跑定时任务的,简单记住两个常见的命令
crontab -l # 列出本地电脑上所有的crontab定时任务
crontab -e # 编辑本地电脑上的crontab定时任务
在编辑任务的时候,有个坑先填一下:python命令要写全路径,文件路径也写全路径;另外如果到了设置的时间,邮件却没有发送成功,看看电脑是不是处于睡眠状态。
下面这个定时任务是每个工作日下午3点半定时发邮件的。
30 15 * * 1-5 /usr/local/bin/python3.7 /Users/admin/Desktop/stock.py
邮件内容截个图,瞄一眼

