Python staring robot can monitor the stock price in real time and notify you by email

Posted by supernova on Tue, 01 Feb 2022 09:59:03 +0100

preface

With its high development efficiency and powerful features, Python stands out among many programming languages and has become an analytical tool in the era of big data.

According to my understanding for many years, programming language is just an efficient tool to realize specific functions according to people's intention. The core decision-making function realized by programming still needs artificial intelligence. In the field of quantitative investment and trading, the trading logic considered by investors is very important, which is the so-called sword without edge, Great skill does not work (the real sword skill does not depend on the blade, but on personal practice, so does investment, and the quality of investors is the most important). Therefore, 80% of the time and energy should be devoted to the thinking of investment model construction and 20% to programming implementation.

As you are about to embark on quantitative investment trading, if you want to do a good job, you must first sharpen your tools. It is undoubtedly the wisest to take Python as the preferred language for quantitative investment trading. The rest of your life is very short. Please use python with me!

thinking

In terms of quantitative trading, it should be desirable for many people to automatically mark the stock and find trading signals through computer programs. However, the nine story platform starts from tiring the soil and a journey of thousands of miles begins with a single step. Only by laying a solid foundation and making comprehensive use of each knowledge point one by one, can we build our own complete quantitative trading system.

Today, let's start with the most basic introductory knowledge of quantitative trading. Through Python program, write a robot for real-time marking the stock price. When the stock price triggers a certain increase condition, it will automatically send e-mail or text message to inform investors. This scene can be applied to investors who are happy to speculate in stocks but have no time to mark the stock price.
Through the study of this article, readers can master the knowledge points such as obtaining the real-time price of securities (including stocks and funds), sending e-mail, regularly running the program and packaging the program into exe file.

Working flow chart and effect diagram of disk staring robot

In order to help readers understand the logic of the whole program from the overall view, the flow chart is drawn as follows.

1. Procedure flow chart


2. Effect of stock price monitoring

For example, on July 19, 2021, the monitored target stock Three Gorges energy (stock exchange code: 600905) reached the monitoring level due to the rise and fall of a certain time point, and automatically triggered an email reminder to inform investors of the current price, rise and fall, profit and loss and other data by email. The effect is shown in the figure below.

code implementation

1. Third party library to be installed and brief introduction

First of all, let's introduce some Python libraries that need to be used in this article.

  • Tushare: a free and open source python financial data interface package through the get of the library_ realtime_ The method of quotes (code) (the code is the trading code of the target securities, including the trading code of stocks and ETF funds), can return the current quotation and transaction information of stocks. The data type of the returned value is DataFrame, which includes name (Securities name), open (today's opening price), pre_ Close (yesterday's closing price), price (current price)... Time, etc. according to this demand, only some dimensions are required. For other dimensions, readers can view all dimension information by printing ().
  • pandas: the core library of data analysis, because it calls the get of Tushare library_ realtime_ The quotes (code) method returns the DataFrame data type, so the library is required to operate on the returned data.
    schedule: in the system of securities trading, there are trading and closing times. To realize the regular operation of the program, this library is essential. See the introduction to the usage of this library in the program part for details.
  • SMTP lib: this library mainly realizes the sending of e-mail.
  • Sys: the market is closed after 15:00 on the trading day. To avoid waste of resources, you can call sys The exit () method realizes the automatic exit of the program.
  • pyinstaller: with this library, the program can be packaged into an executable exe format file to facilitate the operation of the program.
    The third-party libraries required above can be installed by using pip instruction.

2. Program code implementation

① Prepare methods for obtaining current securities price information

def get_now_jiage(code):
   df = ts.get_realtime_quotes(code)[['name','price','pre_close','date','time']]
   return df

The parameter code is the trading code of the target stock, for example, the securities trading code of the stock name "Three Gorges energy" is "600905". Call Tushare's get_realtime_quotes('600905 ') method can return data of DataFrame type. According to the functional requirements, we only need to obtain name (stock name), price (current price) and pre_ Close (yesterday's closing price), date (the date corresponding to the price) and time (the time corresponding to the price).

After writing this method, the master needs to pass the trading code of the target stock to get_now_jiage method, you can get the required data.

② Write a method to judge whether it is within the trading time period

On each trading day, the time of stock trading is 09:30-11:30 and 13:00-15:00. The program starts monitoring at 9:30 in the morning, which can be realized through the schedule (explained later). During the noon market closing time between 11:30-13:00, in order to avoid wasting resources, it is not necessary to call the data of Tushare interface. This time period can be called suspended trading time. The method to judge whether the transaction is suspended is written as follows:

def pd_ztjytime():#Determine whether it is trading time
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    now_datetime = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
    d1 = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d') + ' 11:30:01', '%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d') + ' 13:00:00', '%Y-%m-%d %H:%M:%S')
    delta1 = (now_datetime - d1).total_seconds()
    delta2 = (d2-now_datetime).total_seconds()
    if delta1>0 and delta2>0 : #Within the time of suspension
        return True  #Returns True within the suspended transaction time range
    else:
        return False #If it is not within the suspended trading time range, return False

③ Write the main operation program of monitoring stock price

This module serves as the core program for stock price monitoring, calculating the rise and fall of stock price and judging whether to send notice. In order to cooperate with the module that runs the program regularly at 9:30 in the morning, this module is written as an independent method. The complete program is as follows:

def do_programe(code):
    if pd_ztjytime()==False: #Judge whether it is within the time range of suspended transaction
        info=get_now_jiage(code) #Call the method to get the current DataFrame
        now_jiage=float(info['price'][0]) #Get the current price
        name=info['name'][0] #Get securities name
        pre_close=float(info['pre_close'][0]) #Get yesterday's closing price
        riqi=info['date'][0] #Get the date corresponding to the current price
        sj=info['time'][0] #Get the time corresponding to the price
        now_zdie=round((now_jiage-pre_close)/pre_close*100,2) #Calculate the current rise and fall
        all_zdie=round((now_jiage-cbj)/cbj*100,2)  #Calculate the total rise and fall of the stock during the holding period, where cbj is the cost price at the time of purchase, and the global variable needs to be agreed
        now_shizhi=round(shuliang*now_jiage,2) #Calculate the current market value of the stock, where shuliang is the number of stocks purchased, which needs to be agreed as a global variable
        ykui=round(now_shizhi-cbj*shuliang,2)  #Calculate the current total profit and loss of the stock
        if (abs(now_zdie)>=3 and abs(now_zdie)<3.09) or (abs(now_zdie)>=6  and abs(now_zdie)<6.05)  or (abs(now_zdie)>=9 and  abs(now_zdie)<9.1) : #Judge whether the current rise and fall are within the target range
            email_comment = []
            email_comment.append('<html>')
            email_comment.append('<b><p><h3><font size="2" color="black">Hello!</font></h4></p></b>')
            email_comment.append('<p><font size="2" color="#000000 "> according to the setting parameters, the monitored securities price change messages of '+ name+'('+str(code) +') are reported as follows: < / font > < / P > ')
            email_comment.append('<table border="1px" cellspacing="0px"   width="600" bgcolor=' + color_bg_fg + ' style="border-collapse:collapse">')

            email_comment.append('<tr>')
            email_comment.append('<td align="center"><b>Serial number</b></td>')
            email_comment.append('<td align="center"><b>Purchase unit price</b></td>')
            email_comment.append('<td align="center"><b>Number of shares held</b></td>')
            email_comment.append('<td align="center"><b>present price</b></td>')
            email_comment.append('<td align="center"><b>Current rise and fall</b></td>')
            email_comment.append('<td align="center"><b>Total rise and fall</b></td>')
            email_comment.append('<td align="center"><b>Current market value</b></td>')
            email_comment.append('<td align="center"><b>Profit and loss</b></td>')
            email_comment.append('<td align="center"><b>Change time</b></td>')
            email_comment.append('</tr>')

            email_comment.append('<tr>')
            email_comment.append('<td align="center">'+str(1)+'</td>')
            email_comment.append('<td align="center">'+str(cbj) + '</td>')
            email_comment.append('<td align="center">' + str(shuliang) + '</td>')
            email_comment.append('<td align="center">' + str(now_jiage) +'</td>')
            email_comment.append('<td align="center">' + str(now_zdie) + '%</td>')
            email_comment.append('<td align="center">' + str(all_zdie) + '%</td>')
            email_comment.append('<td align="center">' + str(now_shizhi) + 'element</td>')
            email_comment.append('<td align="center">' + str(ykui) + 'element</td>')
            email_comment.append('<td align="center">' + str(riqi) +' '+str(sj) +'</td>')
            email_comment.append('</tr>')
            email_comment.append('</table>')
            email_comment.append('<p><font size="2" color="black">Wish: the stock market is red every day and make a fortune every day!</font></p>')
            email_comment.append('</html>')
            send_msg = '\n'.join(email_comment)
            send_Email(email_add[0], send_msg)

In the above program, the judgment statement to judge whether to send the notice is:

if (abs(now_zdie)>=3 and abs(now_zdie)<3.1) or (abs(now_zdie)>=6  and abs(now_zdie)<6.1)  or (abs(now_zdie)>=9 and  abs(now_zdie)<9.1) 

The above if judgment statement indicates that when the absolute value of the current rise and fall is between 3% (inclusive) and 3.1% (exclusive) (the absolute value can be used to take into account the range of rise and fall at the same time), or between 6% (inclusive) and 6.1% (exclusive), or 9% (inclusive) and 9.1% (exclusive), the notice will be sent in the form of e-mail, and the specific rise and fall trigger parameters can be modified by the reader.

The key procedures for sending e-mail are:

send_Email(email_add[0], send_msg)

Among them, email_add is in the form of a list, which can store multiple email addresses for receiving notifications. In this example, only one receiving address is set, and the global variable email_add = ['...'], so the program to obtain the address is email_add[0]. send_msg is the email content to be sent. The email content uses the list email_comment is added. The email sent here is in html format. The html format is used to facilitate drawing tables.

Send email_ The procedure of email method is as follows:

def send_Email(Email_address, email_text):
    from_addr = '*****' #Email address
    password = '*****'   #Password to send email
    title = 'Stock price change monitoring message-' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  #Email title
    msg = MIMEText(email_text, 'html', 'utf-8') #The format of email is HTML
    msg['From'] = from_addr
    msg['To'] = Email_address
    msg['Subject'] = title

    try:
        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(from_addr, password)  # Send mail
        server.send_message(msg)
        server.quit()

        # print(Email_address+'  send success!')
        #send_info.append(Email_address + '  send success!\n')
    except Exception as e:
        a+1
        # print(e)
        #send_info.append(e + '\n')
        #send_info.append(Email_address + ' send failed!\n')
        # print(Email_address+' send failed!')

from_addr is the email address of the sender, and password is the authorization code of the sender. It needs to be modified and filled in according to the actual situation.

In addition, in the program:

server = smtplib.SMTP_SSL('smtp.qq.com', 465)

Is the SMTP server address of QQ mailbox SMTP qq. COM, the default port is 465. If it is another mailbox, the corresponding server and port number should be modified.

How to get the sender's authorization code? Take QQ email as an example:

Step 1: log in to QQ email, click the "Settings" link at the top, and then click the "account" tab, as shown in the figure below.


Step 3: after clicking the "open" link, there will be a process of verifying the security. According to the instructions in the page, send the mobile phone message with the specified content to the specified number. After sending it, click the "I sent" button in the page, and a box will be popped up, which contains the SMTP authorization code, and copy and store it. This will facilitate the subsequent call.

④ Write call do_ Monitoring program of program (code)

In order to call the main program, write the run() method as follows:

def run():
    while True:
        do_programe('600905')
        now_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        d1 = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
        d2 = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d')+' 15:00:00', '%Y-%m-%d %H:%M:%S')
        delta = d2 - d1
        if delta.total_seconds()<=0:
          sys.exit()
        time.sleep(1)

⑤ Write the main program that starts monitoring at 9:30 every day

In order to realize the monitoring at the trading time point of each trading day, the required procedures are as follows:

if __name__ == '__main__':
    schedule.every().day.at("09:30").do(run)
    while True:
        schedule.run_pending()
        time.sleep(1)

⑥ Program packaging and automatic operation

After writing the program, you need to convert the program into exe format through packaging. The program in this format can be clicked or set to run automatically. The packaged library is pyinstaller. Use the command pyinstaller -w -F program path \ program name py. Where - w means that there is no black DOS interface when the generated EXE file runs. We only need the program to run "quietly" in the background.

In order to realize the automatic operation of the program when the computer starts up, you can copy the generated exe file to the Startup folder of the windbos system, click the start menu - all programs of windows, find the folder of "Startup" or "Startup", and copy the exe file to the folder. Each time you start up, the computer can automatically run the monitoring program.

Because there is no interface when the program runs, in order to check whether the program is running, you can use the shortcut key "Ctrl Alt Delete" to open the task manager. In the process, you can view the file of "stock monitoring. exe" (the file name here is the file name changed by the author), indicating that the program is under monitoring.

expectation

The program only sets up a stock as a case of simple function implementation, and there is still some room for improvement. The description is as follows.

First, in practice, it is often to build a stock pool (several stocks) to dynamically monitor the stock price and automatically judge the trading time point (such as MACD, moving average, KDJ index, etc.), which often needs to be combined with database technology to facilitate the flexible construction of stock pool.

Second, the function of sending SMS is not introduced in this paper, but only email. In fact, the idea of SMS notification is the same as that of email. If you want to realize the function of sending text messages for free, readers can log in on the twitter website( https://www.twilio.com )Register and call the corresponding functions on the website, and readers can search online again.

The third is about the Tushare data interface. The old interface API of Tushare is used in this paper. At present, the official mainly maintains the Tushare Pro interface, and the corresponding call function can only reach a certain score. However, compared with other charging interfaces, Tushare is the work of conscience in the industry. For the reference website of Tushare pro, see https://waditu.com/document/2 .

Fourth, for other commercial quantitative interfaces, you can recommend jukuan quantitative interface, which has a free trial period of about half a year, but after free, there are still thousands of yuan per month. Readers can choose to use jukuan website https://www.joinquant.com/view/community/list?listType=1 .
Fifth, the crawler obtains securities trading data. Now the websites with rich securities trading data include Dongfang fortune, flush, sina finance and Hexun, etc. The corresponding data can also be obtained through the crawler, but it should be noted that in this paper, the API is called every second on each trading day. If it is implemented by the crawler, it is not ideal, because too frequent calls may trigger the anti crawler mechanism of the website.

Sixth, the program is set to automatically start up and run on the local computer. After the program is continuously optimized and added functions, interested readers can understand the purchase of ECS deployment monitoring program.

About Python technology reserve

It's good to learn Python well, whether in employment or sideline, but to learn python, you still need to have a learning plan. Finally, let's share a full set of Python learning materials to help those who want to learn Python!

1, Python learning routes in all directions

All directions of Python is to sort out the commonly used technical points of Python and form a summary of knowledge points in various fields. Its purpose is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2, Learning software

If a worker wants to do well, he must sharpen his tools first. The commonly used development software for learning Python is here, which saves you a lot of time.

3, Getting started video

When we watch videos, we can't just move our eyes and brain without hands. The more scientific learning method is to use them after understanding. At this time, the hand training project is very suitable.

4, Actual combat cases

Optical theory is useless. We should learn to knock together and practice, so as to apply what we have learned to practice. At this time, we can make some practical cases to learn.

5, Interview materials

We must learn Python in order to find a high paying job. The following interview questions are the latest interview materials from front-line Internet manufacturers such as Alibaba, Tencent and byte, and Alibaba boss has given authoritative answers. After brushing this set of interview materials, I believe everyone can find a satisfactory job.


This complete set of Python learning materials has been uploaded to CSDN. Friends can scan the official authentication QR code of CSDN below on wechat and get it for free [guaranteed to be 100% free]

Topics: Python Programmer AI