起初需求是这样的,新手买卖股票,容易犯的一个错误就是频繁看盘,于是我就把买卖股票的软件卸载了,可是我又想知道自己的总盈亏,该怎么办呢?

    我想有没有办法通过脚本获取特定几支股票的最新收盘价,并根据自己买入的成本计算收益,然后每天定时的发邮件给自己。比如每个工作日的下午3点半。下面这个脚本就是用来干这个事情的。邮件正文是自己买入几支股票的最新收盘价,最新涨跌,以及最新盈亏。同时附件内容为最近n天内的总盈亏,可通过绘制直方图查看盈亏的趋势。

    1. import pandas as pd
    2. import tushare as ts
    3. def income(cost, price, num):
    4. return round((price - cost) * num, 3)
    5. def get_stock_detail(days, code, desc, cost, num):
    6. df = ts.get_hist_data(code)
    7. # 收盘价 涨跌幅
    8. df = df[['close', 'p_change']][:days]
    9. df['income'] = df['close'].apply(lambda s: income(cost, s, num))
    10. a = [[desc] * 3, ['close', 'p_change', 'income']]
    11. index = pd.MultiIndex.from_arrays(a, names=['股票名称', '行情'])
    12. df.columns = index
    13. return df
    14. days = 10
    15. code = ['000651', '002230', '002415', '002236']
    16. desc = ['格力电器', '科大讯飞', '海康威视', '大华股份']
    17. cost = [64.89, 31.056, 33.077, 19.47]
    18. num = [200, 300, 300, 500]
    19. # 将查询结果进行横向拼接
    20. res = pd.DataFrame()
    21. for i in range(len(code)):
    22. df = get_stock_detail(days, code[i], desc[i], cost[i], num[i])
    23. res = pd.concat([res, df], axis=1)
    24. # 计算总收益
    25. res['total_income'] = 0
    26. for i in range(len(code)):
    27. res['total_income'] += res[(desc[i], 'income')]
    28. res['total_income'] = round(res['total_income'], 3)
    29. # 写入文件
    30. file_name = "最近" + str(days) + "日盈亏汇总.txt"
    31. res['total_income'].to_csv(file_name, sep="\t", index=True, encoding='utf-8', header=True)
    32. # 通过直方图的形式直观查看
    33. # res['total_income'].sort_index().plot.bar()
    34. #---------------------------获取当天日期-----------------------------
    35. from datetime import datetime
    36. dt = datetime.now()
    37. y = dt.year
    38. m = dt.month
    39. d = dt.day
    40. def format(n):
    41. return str(0) + str(n) if n < 10 else str(n)
    42. curDay = str(y) + '-' + format(m) + '-' + format(d)
    43. #---------------------------发送邮件---------------------------------
    44. import smtplib
    45. from email.mime.text import MIMEText
    46. from email.header import Header
    47. from email.mime.multipart import MIMEMultipart
    48. from email.mime.application import MIMEApplication
    49. # 第三方 SMTP 服务
    50. mail_host="smtp.qq.com" #设置服务器
    51. mail_user="jinfeng.wang60@qq.com" #用户名
    52. mail_pass="xxxxxx" #密码
    53. authentication_pass="xxxxxx" # 授权码
    54. sender = 'jinfeng.wang60@qq.com'
    55. # 多个收件人,用列表组装
    56. receivers = "jinfeng.wang60@qq.com"
    57. # 正文内容
    58. priceDesc = '\n格力最新收盘价:' + str(res.iloc[0][(desc[0], 'close')])
    59. priceDesc += '\n格力最新涨跌幅:' + str(res.iloc[0][(desc[0], 'p_change')])
    60. priceDesc += '\n格力盈亏:' + str(res.iloc[0][(desc[0], 'income')])
    61. priceDesc += '\n'
    62. priceDesc += '\n科大最新收盘价:' + str(res.iloc[0][(desc[1], 'close')])
    63. priceDesc += '\n科大最新涨跌幅:' + str(res.iloc[0][(desc[1], 'p_change')])
    64. priceDesc += '\n科大盈亏:' + str(res.iloc[0][(desc[1], 'income')])
    65. priceDesc += '\n'
    66. priceDesc += '\n海康最新收盘价:' + str(res.iloc[0][(desc[2], 'close')])
    67. priceDesc += '\n海康最新涨跌幅:' + str(res.iloc[0][(desc[2], 'p_change')])
    68. priceDesc += '\n海康盈亏:' + str(res.iloc[0][(desc[2], 'income')])
    69. priceDesc += '\n'
    70. priceDesc += '\n大华最新收盘价:' + str(res.iloc[0][(desc[3], 'close')])
    71. priceDesc += '\n大华最新涨跌幅:' + str(res.iloc[0][(desc[3], 'p_change')])
    72. priceDesc += '\n大华盈亏:' + str(res.iloc[0][(desc[3], 'income')])
    73. priceDesc += '\n'
    74. # 附件
    75. txtPart = MIMEApplication(open(file_name, 'rb').read())
    76. txtPart.add_header('Content-Disposition', 'attachment', filename=file_name)
    77. m = MIMEMultipart()
    78. textApart = MIMEText(priceDesc, 'plain', 'utf-8')
    79. m.attach(txtPart)
    80. m.attach(textApart)
    81. m['From'] = sender
    82. m['to'] = receivers
    83. #邮件主题
    84. subject = ' ' + curDay + ' 累计总盈亏: ' + str(res['total_income'][0])
    85. m['Subject'] = subject
    86. try:
    87. smtpObj = smtplib.SMTP()
    88. smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
    89. smtpObj.login(mail_user,authentication_pass)
    90. smtpObj.sendmail(sender, receivers, m.as_string())
    91. print (curDay + " 邮件发送成功\n")
    92. except smtplib.SMTPException as e:
    93. print ("Error: 无法发送邮件")
    94. print(e)

    要想让这个脚本完整的跑起来,有几个条件需要满足一下:

    1. 电脑要有python的环境,可以跑python脚本
    2. 安装pandas,tushare,lxml库 (如果报错说缺少什么库,直接使用pip install 命令进行安装即可)
    3. 替换脚本中的用户名,密码,授权码,收件人邮箱,发件人邮箱为自己的。

    这样就可以跑起来了,甚至可以根据自己的实际需求用起来。要想做价值投资者,股价没必要天天看,如果是好公司的股票,那好好拿着就是,多分析下公司本身,行业大趋势,经济政策这些,同时增加自己的投资知识储备。要记住:投资靠的是国运和时间的复利;同时投资和生活中的一切都息息相关。

    我是通过crontab来跑定时任务的,简单记住两个常见的命令

    1. crontab -l # 列出本地电脑上所有的crontab定时任务
    1. crontab -e # 编辑本地电脑上的crontab定时任务

    在编辑任务的时候,有个坑先填一下:python命令要写全路径,文件路径也写全路径;另外如果到了设置的时间,邮件却没有发送成功,看看电脑是不是处于睡眠状态。

    下面这个定时任务是每个工作日下午3点半定时发邮件的。

    1. 30 15 * * 1-5 /usr/local/bin/python3.7 /Users/admin/Desktop/stock.py

    邮件内容截个图,瞄一眼

    项目结果.png