python3获取某股票股价,若超过指定价格发送邮件

目录

一、前言:

二、分析与实行

1、单个股票分析(格力电器为例)

 2、深沪两市对比

三、完整代码(python3)



一、前言:

对于我这种不会炒股,又想发财的人,但是又没有财路的人来说,只能跟着朋友随便买买股票,看下能不能实现一夜暴富的白日梦了。现在都还幻想着能打中一个像东鹏特饮一样的新股。。。。
好了。就说这么多。主要是因为我这个人懒,懒得整天盯着股价,所以就写了一个程序。
这个程序主要功能:
时刻获取东方财富指定股票的股价,如果这个股票股价超过了一定的金额、或者低于一定金额就发邮件告诉我。看下是否需要卖出还是继续坚持。

二、分析与实行

东方财富有几种股票,港、深、沪、科创板等等。我只买了深沪两市的股票,所以这篇文章我就写了深沪两市的取数情况。不过其他的应该也是一样的。

1、单个股票分析(格力电器为例)

首先我们在东方财富复制某个股票的URL出来,或者直接在电脑上面搜索东方财富,可以进入PC端的东方财富页面。找到格力电器的股票页面,我们可以看到他的股价是51.16。

然后我们按F12,搜索目前的价格。能够找到这个接口。我们到接口url如下,有长又臭,其实里面的参数不一定是必要的参数。所以我们可以对一些参数进行增删来确定最终的url。 

原始URL:
http://push2.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ut=fa5fd1943c7b386f172d6893dbfba10b&ndays=1&iscr=0&secid=0.000651&cb=jQuery112404481331582479424_1626763858500&_=1626763858528
删改之后URL:
http://push2.eastmoney.com/api/qt/stock/trends2/get?secid=0.000651&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55

发现这个接口使用一个列表记录了格力电器所有的股价,并且有时间等等的记录。那就好办了,我们只要使用python的某些模块去解析出列表最新的一条数据,就是我们要的最新股价了。 

jQuery112404481331582479424_1626763858500({"rc":0,"rt":10,"svr":2887255695,
"lt":1,"full":1,"data":{"code":"000651","market":0,"type":6,"status":0,
"name":"格力电器","decimal":2,"preSettlement":0.0,"preClose":51.48,
"beticks":"33300|34200|54000|34200|41400|46800|54000","trendsTotal":241,
"time":1626763854,"kind":1,"prePrice":51.48,"trends":["2021-07-20 09:30,51.35,51.35,51.35,51.35,2766,14203410.00,51.350","2021-07-20 09:31,51.22,51.39,51.43,51.00,13884,71180454.00,51.282","2021-07-20 
中间省略了很多.....
14:49,51.17,51.22,51.22,51.17,1751,8964539.00,51.169","2021-07-20 14:50,51.22,51.27,51.28,51.22,2213,11345325.00,51.170","2021-07-20 14:51,51.28,51.22,51.28,51.22,1820,9328544.00,51.170"]}});

 2、深沪两市对比

经过多个深沪市的股票url对比,可以发现不同的是secid。深市的是【0.股票代码】,沪市的是【1.股票代码】,那么我们就可以通过这两个编码来区分深市和沪市了。

(深)格力电器:http://push2.eastmoney.com/api/qt/stock/trends2/get?secid=0.000651&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55
(沪)士兰微:  http://push2.eastmoney.com/api/qt/stock/trends2/get?secid=1.600460&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55

三、完整代码(python3)

#!/usr/bin/python3
import datetime
import os
import requests
import json,time
import importlib
import sys
importlib.reload(sys)
# 发送邮件
import smtplib
from email.mime.text import MIMEText

#设置服务器所需信息
#QQ邮箱服务器地址
mail_host = 'smtp.qq.com'
#QQ用户名
mail_user = '[email protected]'
#密码(部分邮箱为授权码)
mail_pass = 'xxxxx'

#邮件发送方邮箱地址
sender = '[email protected]'
#邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['[email protected]']
class SendEmail():
    def __init__(self):
        pass
    def sendmail(self, title, con):
        #设置email信息:邮件内容设置、邮件主题、发送方信息、接受方信息
        message = MIMEText(con,'plain','utf-8')
        message['Subject'] = title
        message['From'] = sender
        message['To'] = receivers[0]
        #登录并发送邮件:连接到服务器、登录到服务器
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(mail_host,25)
            smtpObj.login(mail_user,mail_pass)
            #发送
            smtpObj.sendmail(
                sender,receivers,message.as_string())
            #退出
            smtpObj.quit()
            print('success')
        except smtplib.SMTPException as e:
            print('error',e) #打印错误


GS_API = "https://push2.eastmoney.com/api/qt/stock/details"
TODAY = time.strftime('%Y-%m-%d',time.localtime())
class GuPiao(object):
    def __init__(self, flag, gp_name, gp_code, buy_amount, alarm_min, alarm_max):
        self.gp_code = gp_code
        self.gp_name = gp_name
        self.buy_amount = buy_amount
        self.alarm_min = alarm_min
        self.alarm_max = alarm_max
        # 实例化发送邮件服务
        self.sm = SendEmail()
        self.title = '东方财富'
        if flag == "s":
            self.flag = 0
        else:
            self.flag = 1
    
    def fg_file(self, con, fg="r"):
        filename = "%s.txt"%self.gp_code
        if not os.path.isfile(filename):
            with open(filename, 'w') as f:
                f.write("0")
        if fg == 'w':
            with open(filename, "w") as f:
                f.write(con)
                return
        else:
            with open(filename, "r") as f:
                fg_lock = f.read().strip()
                return fg_lock

    def run(self):
        url = "%s/get?secid=%s.%s&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55"%(GS_API,self.flag, self.gp_code)
        r = requests.get(url)
        details = json.loads(r.text)['data']['details']
        # print(details)
        # 获取罪行的股票值
        now_time = str(details[-1]).split(',')[0]
        new_price = str(details[-1]).split(',')[1]
        con = "[%s %s] [%s] 最新股价: %s。"%(TODAY, now_time, self.gp_name, new_price)
        print(con)
        # 获取上一次报价,避免邮件一直发
        last_price = self.fg_file("0", "r")
        new_price = float(new_price)
        if new_price >= self.alarm_max and last_price == "0":
            context = '%s,大于卖出阈值[%s],可考虑卖出!'%(con, alarm_max)
            # 发送邮件
            self.sm.sendmail(self.title,context)
            print("%s,%s"%(self.title,context))
            self.fg_file("1", "w")
        elif new_price <= self.alarm_min and last_price == "0":
            context = '%s,小于关注的阈值[%s],请留意是否需要卖出!'%(con, alarm_min)
            self.sm.sendmail(self.title,context)
            print("%s,%s"%(self.title,context))
            self.fg_file("1", "w")
        elif self.alarm_min < new_price < self.alarm_max and last_price == "1":
            self.fg_file("0", "w")



if __name__ == '__main__':
    while  True :
        # 获取当前时间,看是否再股市开始期间
        morn_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:30', '%Y-%m-%d%H:%M')
        morn_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '11:30', '%Y-%m-%d%H:%M')
        after_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '13:00', '%Y-%m-%d%H:%M')
        after_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '15:00', '%Y-%m-%d%H:%M')
        n_time = datetime.datetime.now()
        # 属于股市的时间才去获取
        if (n_time > morn_time and n_time < morn_time1) or (n_time > after_time and n_time <= after_time1):
            # 股市标识 s:深市  h:沪市, 股票标识, 买入额度,最低告警阈值,最高告警阈值
            gp_list  = [
                ['s', '格力电器', '000651', 49.83, 48.00, 52.00],
                ['s', '科大讯飞', '002230', 60.32, 58.00, 70.00],
                ['h', '士兰微', '60046', 56.72, 54.00, 63.00],
            ]
            for gupiao in gp_list:
                flag = gupiao[0]
                gp_name = gupiao[1]
                gp_code = gupiao[2]
                buy_amount = gupiao[3]
                alarm_min = gupiao[4]
                alarm_max = gupiao[5]
                obgupiao = GuPiao(flag, gp_name, gp_code, buy_amount, alarm_min, alarm_max)
                obgupiao.run()
        else:
            print("非股市开市时间,不查询结果!")
        # 10秒钟取一次数据
        time.sleep(10)



猜你喜欢

转载自blog.csdn.net/MYF12/article/details/118934736