RSI indicators of stock, for example, send learn Python mail function (including RSI indicator to determine the selling strategy)

    I wrote a number of "programmers to add financial business" article series aimed at Python knowledge about the case through the stock before himself, so that everyone at the same time learning the Python can acquire the relevant knowledge of stocks, the so-called double benefit.

    In the previous article in the series, we can see the case K line, moving averages, volume, in this paper, we can see messages about the Python programming knowledge by RSI cases, the text in the subsequent series, everyone can see the MACD, BIAS, KDJ and other indicators related cases.

Principles and algorithms described in 1 RSI indicators

    Relative Strength Index (RSI) is determined by comparing the price of a single share of ups and downs within a certain period of time to determine the extent of the strength of both long and short, in order to predict future trends. From the numerical point of view, it reflects a stock trading power, so investors are able to forecast the future price trend, in practice, is usually used in conjunction with the moving average line, to improve the accuracy of the analysis.

    As shown in the RSI is calculated as follows.

    The first step, RS (relative intensity) = N rising values ​​and the number of days after closing of closing ÷ mean number of days and the rate of reduction of N Mean

    The second step, RSI (relative strength index) = 100-100 ÷ (1 + RS)

    Note that, where "mean" is calculated may be a simple moving average (SMA), or may be weighted moving average (WMA) Exponential Moving Average (EMA). This book uses a relatively simple algorithm simple moving average, some software uses an average of the last two algorithms. Using different algorithms will lead to an average RSI of different values, but the trend will not change, the significance of the transaction will not change.

    To 6 RSI indicator, for example, calculated from the date of counting forward six trading days, get to seven, including today's closing price, minus the closing price of the previous day's closing prices each day to 6 values ​​obtained in this way, these values ​​are positive or negative. Step four is then press the RSI is calculated as follows.

    The first step, up = 6 and the number of digital Chiang Kai-shek average.

    The second step, down = absolute value of the first six digits of the sum in the negative, then the absolute value averaging.

    The third step, RS = up divided down, RS represents the relative intensity

    The fourth step, RSI (relative strength index) = 100-100 ÷ (1 + RS)

    If the result of the fourth step again performs mathematical transformations obtained can be further RS ​​to about factors to obtain the following conclusions: RSI = 100x (up) ÷ (up + down), that is, RSI 100 equals multiplied up other to (up and down and).

    In essence, RSI reflects a certain stage (such as within 6 days) price increases caused by the fluctuation of the total percentage rate volatility, the greater the percentage, indicating the strength of this period of time the stock, whereas if the percentage is smaller, then the strong stock level of disadvantage.

    From the above formula we can see that the RSI value is between 0-100, currently more common reference period is 6 days \ 12th and 24th. The RSI value of each trading day points on the graph connected curve, i.e., the index line can be drawn as RSI, i.e., the index line currently in stock markets RSI is made three curves, as shown in FIG.

  

Figure 2 RSI indicators drawn with Matplotlib saved as a picture

    In DrawRSI.py case are as follows, we will draw 600584 (Changjiang Electronics Technology) based on the algorithm from September 2018 to 6 May 2019 between May 12 and 24 days RSI indicator.

    In this case the data from csv file, and the data of the file from a network share interface, as you can read the contents before Bowen. In this case, also generated by the pattern stored in png format matplotlib, then to facilitate the transmission mail.    

#. 1! / Usr / bin / Python the env 
2 # = UTF-Coding. 8 
. 3 Import PANDAS AS PD 
. 4 Import matplotlib.pyplot AS PLT 
. 5 # RSI calculation method, the reference period list incoming periodList 
6 def calRSI (df, periodList ): 
7 # calculated closing price and the trading day difference 
.. 8 DF [ 'the diff'] = DF [ "the close"] - DF [ "the close"] Shift (. 1) 
.. 9 DF [ 'the diff'] fillna (0, InPlace = True)     
10 DF [ 'up'] = DF [ 'the diff'] 
. 11 # filtered off value of less than 0. 
12 is DF [ 'up'] [DF [ 'up']] = 0 
13 is DF [ ' Down '] = DF [' the diff '] 
14 # filtered off value greater than 0 
15 DF [' Down '] [DF [' Down ']] = 0 
16 # for loop sequentially calculates periodList in RSI different periods, and the like values 
. 17 for period in periodList:  
18 is DF [ 'upAvg'+str(period)] = df['up'].rolling(period).sum()/period
. 19 DF [ 'upAvg' + STR (period)].fillna(0, inplace = True)
20	        df['downAvg'+str(period)] = abs(df['down'].rolling(period).sum()/period)
21	        df['downAvg'+str(period)].fillna(0, inplace = True)
22	        df['RSI'+str(period)] = 100 - 100/((df['upAvg'+str(period)]/df['downAvg'+str(period)]+1))
23	    return df

    In line 5, we define calRSI method for calculating the value of RSI, the method is the first parameter df dataframe type of object information comprises date closing price, the second parameter is the period list.

    In line 8, we put the trading day and the previous day's closing price difference into a 'diff' column, there is a shift (1) df to get in on the line (ie trading) closing price. Since the value of the first row diff is NaN, it is necessary to use a method fillna line 9 is updated to the value 0 NaN.

    In line 11, in the df object is created in the up column, the column value is temporarily and diff values ​​are the same, positive and negative, but soon the df line of 12 [ 'up'] [df [ 'up' ] <0] = 0 codes, up to a negative value in the column is set to 0, so that, in the column up to only contain "N number of days up to the closing price." On line 13 and line 15, the same way, the object create df down the column, and in which is stored with "N days, the number of fall closing price."

    Followed by the second line 17 for loop, traversing the object stored in periodList period is, in fact, by the following code in line 26, we can see the RSI period are calculated 6 days, 12 days and 24 days. For each cycle, the first line 18, closing this period was calculated and the mean number of rising values, and this average value is stored in the object df 'upAvg' + str (period) column, such as the current period is 6 , then the average number is stored up df [ 'upAvg6'] column. In line 20, the mean number of closing drop in price within the period is calculated and stored 'downAvg' + str (period) column. Finally, in line 22, calculates the value of RSI week period, and placed in the object df 'RSI' + str (period) in. 

Filename = 24 'D: \\ StockData \ \\ 6005842018-09-012019-05-31.csv CH10' 
25 pd.read_csv DF = (filename, encoding = 'GBK' ) 
26 is List = [6,12,24] period list # 
27 # call the method of calculating the RSI 
28 stockDataFrame = calRSI (DF, list) 
29 #Print (stockDataFrame) 
30 # begin drawing 
31 is     plt.figure () 
32 stockDataFrame [ 'RSI6']. plot (Color = "Blue", label = 'RSI6' )  33 is stockDataFrame [ 'RSI12']. Plot (Color = "Green", label = 'RSI12' )  34 is stockDataFrame [ 'RSI24']. Plot (Color = "Purple", label = 'RSI24' ) 35 plt.legend (loc = 'best' ) # 36 # is provided to draw the legend label x coordinate and the rotation angle 37 major_index = stockDataFrame.index [stockDataFrame.index==0] 38 major_xtics=stockDataFrame['Date'][stockDataFrame.index==0] 39 plt.xticks (major_index, major_xtics) 40 plt.setp (plt.gca (). Get_xticklabels (), rotation = 30 ) # 41 is gridlines, and are provided in a grid pattern 42 plt.grid (linestyle = '-.' ) 43 is plt.title ( "the RSI effects FIG." ) 44 is plt.rcParams [ 'serif-font.sans'] = [' SimHei ' ] plt.savefig 45 (' D: \\ StockData \ CH10 \\ 6005842018-09-012019-05-31.png ' ) 46 is plt.show ()

     In line 25, we get the data contains information such as the date of the closing price from the specified csv file, and specifies three calculation period in the 26th row. In line 28, we call calRSI method of calculating the value of the RSI three cycles, and stored stockDataFrame objects, the output line 29 of the current statement is commented out in the open, we can see the results of the calculation value containing upAvg6, downAvg6 RSI6 and other columns.

    After obtaining RSI data, begin drawing the line 31, the more important step through line 32 to line 34 of the code, plotted three curves plot method, followed by the legend by legend method line 35 through the first 37 and 38 of the line of code to set the text line and the x-axis scale rotation effect, provided by the code design grid line 42, 43 is provided by the code for the first header.

    Before drawing line 46 through the show method, we adopted the code for the first 45 rows, with savefig method to save the drawing to the specified directory, please note that this statement needs to be placed before the show method, otherwise save the picture will be empty.

    Run the code, as shown below can be seen results in RSI FIG. Incidentally, since the present embodiment in calculating the mean and closing prices go and closing drop in price and number average, using a simple moving average algorithm, and the drawn graphics may be inconsistent in some software, but the same tendency. Moreover, in the specified directory, to see the png image.

     

After transmitting Message 3 K line integration

    In DrawKwithRSI.py code, we will complete the work of the following three, first, calculating 6, RSI values ​​of 12 and 24 days. Second, draw lines plus moving average K plus the RSI chart, and save the result as png format images. Third, send messages, and the png image displayed in the message body in rich text format.

1    #!/usr/bin/env python
2    #coding=utf-8
3    import pandas as pd
4    import matplotlib.pyplot as plt 
5    from mpl_finance import candlestick2_ochl
6    from matplotlib.ticker import MultipleLocator
7    import smtplib
8    from email.mime.text import MIMEText
9    from email.mime.image import MIMEImage
10    from email.mime.multipart importMimeMultipart
 . 11     # calculation method of RSI, the incoming reference periodList period list 
12 is     DEF calRSI (DF, periodList):
 13 is the same case and DrawRSI.py    

    From line 3 to line 10, we introduced the relevant library file, exactly the same methods and calRSI case before the line 12 defined, so it is no longer given code.    

Filename = 14 'D: \\ StockData \ \\ 6005842018-09-012019-05-31.csv CH10' 
15 pd.read_csv DF = (filename, encoding = 'GBK') 
16 List = [6,12,24] period list # 
17 # call the method of calculating the RSI 
18 is stockDataFrame = calRSI (DF, list) 
. 19 Figure plt.figure = () 
20 is to create sub-picture #      
21 is (axPrice, axRSI) = figure.subplots (2, sharex = True) 
22 is # method is called to draw the first axPrice sub-picture in the K line in FIG. 
23 candlestick2_ochl (ax = axPrice, opens = df [ "Open"]. values, closes = df [ "Close"]. values, highs = df [ "High"] .values, Lows DF = [ "Low"]. values, width = 0.75, colorup = 'Red', colordown = 'Green') 
24 axPrice.set_title ( "K-line diagram and FIG EMA") # set the sub-title FIG. 
25 stockDataFrame [ 'Close']. rolling (window = 3) .mean (). plot (ax = axPrice, color = "red", label = '3 -day moving average')
26 stockDataFrame [ 'Close']. Rolling (window = 5) .mean (). Plot (ax = axPrice, color = "blue", label = '5 -day moving average') 
27 stockDataFrame [ 'the Close']. Rolling (window = 10) .mean (). plot (ax = axPrice, color = "green", label = '10 day moving average ') 
28 axPrice.legend (LOC =' Best ') drawing legend # 
29 axPrice.set_ylabel ( "price ( unit: yuan) ") 
30 axPrice.grid (lineStyle = '-.') gridlines #         
31 # RSI pattern drawn in FIG axRSI sub 
32 stockDataFrame [ 'RSI6'] plot (ax = axRSI, color =." Blue ", label = 'RSI6') 
33 is stockDataFrame [ 'RSI12']. Plot (AX = axRSI, Color =" Green ", label = 'RSI12') 
34 is stockDataFrame [ 'RSI24']. Plot (AX = axRSI, Color = "Purple", label = 'RSI24') 
35 plt.legend (LOC = 'Best') drawing legend # 
36 plt.       rcParams [ 'font.sans-serif'] = [ 'SimHei'] 
Title 37 axRSI.set_title ( "RSI FIG.") # Set subgraph 
38 is axRSI.grid (lineStyle = '-.') Gridlines # 
39 # Set x coordinate and the rotation angle of the tab 
40 major_index = stockDataFrame.index [stockDataFrame.index% 7 == 0]
41	major_xtics=stockDataFrame['Date'][stockDataFrame.index%7==0]
42	plt.xticks(major_index,major_xtics)
43	plt.setp(plt.gca().get_xticklabels(), rotation=30) 
44	plt.savefig('D:\\stockData\ch10\\600584RSI.png')

    In line 18, we got three periods RSI data by calling calRSI method. In line 21, the set of two sub axRSI axPrice and FIG shared x-axis labels, the line K drawn line in FIG. 23, in the line 25 to the line 27, the drawn 3, 5 and 10 day moving average, in line 32 to line 34, the three RSI indicator plotted in FIG. 6, 12 and 24 days. Through the line 44 in savefig method, the presence of the specified directory contains the K-line pattern, the line average and the RSI.     

45	#发送邮件
46	def sendMail(username,pwd,from_addr,to_addr,msg):
47	    和之前sendMailWithPicAttachment.py案例中的一致
48	def buildMail(HTMLContent,subject,showFrom,showTo,attachfolder,attachFileName):
49	    message = MIMEMultipart()
50	    body = MIMEText(HTMLContent, 'html', 'utf-8')
51	    message.attach(body)
52	    message['Subject'] = subject
53	    message['From'] = showFrom
54	    message['To'] = showTo
55	    imageFile = MIMEImage(open(attachfolder+attachFileName, 'rb').read())
56	    imageFile.add_header('Content-ID', attachFileName)
57	    imageFile['Content-Disposition'] = 'attachment;filename="'+attachFileName+'"'
58	    message.attach(imageFile)
59	    return message

 And exactly the same method before sendMail case line 46 is defined, the code will not be given in detail. This is different from the previous case, in the line 48, defined specifically buildMail method for assembling mail object, many elements of the message is defined by the parameters of the process.

    Specifically, the message type defined in the line 49 is MimeMultipart, that is to say messages with attachments, and in the line 50 in line 51, constructed in accordance with the parameters HTMLContent the body of the message, on line 52, line 54 to , the correlation property value set of messages, from line 55 to line 57, constructed in accordance with the reference picture based MIMEImage type attachments, in line 58, through the method of attachment is incorporated attach message body.    

60	subject='RSI效果图'
61	attachfolder='D:\\stockData\\ch10\\'
62	attachFileName='600584RSI.png'
63	HTMLContent = '<html><head></head><body>'\
64	 '<img src="cid:'+attachFileName+'"/>'\
65	 '</body></html>'
66	message = buildMail(HTMLContent,subject,'[email protected]','[email protected]',attachfolder,attachFileName) 
67	sendMail('hsm_computer','xxx','[email protected]','[email protected]',message.as_string())  
68	#最后再绘制
69	plt.show()

 In line 60 to line 66, we set the associated property value of the message, and in line 66 years, created the e-mail subject message by calling buildMail method, in the first line 67 years, send a message by calling sendMail method, and finally in the 69th line drawn by the graphics show method. Please note that in this case the three details.

    First, the value of the first 64 rows cid needs and Content-ID value of the first 56 rows, or it can send the picture as an attachment, can not be displayed in a rich text format in the message body.

    Second, we are to build and send mail, and then draw graphics through the code line 69, and send e-mail if the reverse order to draw graphics, then, show the method is invoked after the program blocked in this position, the code can not continue. To wait until manually shut off the pop-up window by the show method will trigger sendMail method for sending mail.

    Third, in the case of line 48, we specifically encapsulated buildMail method for constructing the message object in which the dynamic parameter message constructed so that if you want to send other messages, you can call the method, which can improve the code reusability.

    Run the code, we can see the renderings after the K line, moving average and RSI indicators integrated in the chart pop-up window, and can see the same view of the body of the message inside.

     

4 RSI indicator guidance for point of sale

    In general, we RSI indicator on the 6th, 12th and 24th called for short-term, medium-term and long-term indicators. KDJ indicators and the same, RSI indicators overbought and oversold area.

    Specifically, when the RSI value fluctuates between 50 and 70, representing the current state are strong, continues to rise as more than 80, then the overbought zone, most likely promoted or transferred in a short time. Conversely RSI value is between 20-50, shows that the current market is relatively weak, falls below 20 or less, into the oversold zone, the share price may rebound.

    Before telling RSI trading strategy, let's talk defect under summed up in practice RSI indicator.

    First, the short period (for example 6) of the RSI indicator is more sensitive, but the number of shocks more quickly, the reliability of relatively badly, while a longer period (such as 24) of the RSI indicator reliability, but the sensitivity is not enough often "lag" of the situation.

    Second, when the fluctuation value of 40-60, often not meaningful, specifically, when the value of the critical point 50 to break up, said the stock has been strengthened, and vice versa, said weakened down below 50, However, in practice, they would often share price did not fall after the RSI below 50, and 50 share price does not rise after the break.

    Comprehensive RSI algorithms, theories and defects, to tell the story of our next practice commonly based on the index of selling strategies.

    First, RSI short indicator (6) occurs at the intersection of gold and 20 or less long-term oversold RSI (24 or 12), i.e., line 6 through line 12 or 24, then the imminent rally If other aspects such as technical or policy no big problem, you can buy appropriate.

    Second, on the contrary, RSI short indicator (6) death occurred more than 80 intersect with long overbought RSI (24 or 12), i.e., through line 12 or 24 at the line 6, the instructions may be high reverse situation occurs, if there is no other good news, you can consider selling.

5 calculates a selling point, the message transmitted in the form of

    According to the above description, buy strategy is based on the RSI, gold and 20 or less long RSI6日线在 RSI (24 or 12) crossing occurs employed herein. In the following calRSIBuyPoints.py cases, we accordingly calculated strategy 600584 (Changjiang Electronics Technology) from selling between September 2018 to May 2019, the date of buy and send through the mail.     

#. 1! / Usr / bin / Python the env 
2 # = UTF-Coding. 8 
. 3 Import PANDAS AS PD 
. 4 Import smtplib 
. 5 from email.mime.text Import MimeText 
. 6 from email.mime.image Import MIMEImage 
. 7 from email.mime.multipart MimeMultipart Import 
. 8 # RSI calculation method, the reference period list periodList passed 
. 9 DEF calRSI (DF, periodList): 
10 cases and DrawRSI.py coincides omitted relevant code 
11 filename = 'D: \\ stockData \ ch10 \ \ 6005842018-09-012019-05-31.csv ' 
12 is pd.read_csv DF = (filename, encoding =' GBK ') 
13 is list = [6,12,24] period list # 
14 # call the method of calculating the RSI 
15 stockDataFrame = calRSI (df, list)

    In the 15th line of code, we calculated by calling the RSI value calRSI method, and this part of the relevant code 10.3.2 calRSIBuyPoints.py portion is very similar, so the description will not be repeated.   

0 CNT = 16     
. 17 sellDate = '' 
18 is the while CNT <= len (stockDataFrame) -1: 
. 19 IF (CNT> = 30): error a few days ago #, 30 days counted from the first 
20 is the try:         
21 is Rule # 1 this day RSI6 than 80 
22 is IF stockDataFrame.iloc [CNT] [ 'RSI6'] <80: 
23 is rule # 2.1, the wear RSI12 RSI6 day 
24 if stockDataFrame.iloc [cnt] [ ' RSI6'] <stockDataFrame.iloc [CNT] [ 'RSI12'] and stockDataFrame.iloc [-CNT. 1] [ 'RSI6']> stockDataFrame.iloc [-CNT. 1] [ 'RSI12']: 
25 sellDate + = sellDate stockDataFrame.iloc [CNT] [ ' DATE '] +', ' 
26 is rule # 2.2, day RSI6 beneath RSI24
27	                if  stockDataFrame.iloc[cnt]['RSI6']<stockDataFrame.iloc[cnt]['RSI24'] and stockDataFrame.iloc[cnt-1] ['RSI6']>stockDataFrame.iloc[cnt-1]['RSI24']:
28	                    if sellDate.index(stockDataFrame.iloc[cnt]['Date']) == -1:
29	                        sellDate = sellDate+stockDataFrame.iloc[cnt]['Date'] + ','
30	        except:
31	            pass                
32	    cnt=cnt+1
33	print(sellDate)

    In line 18 to line 32, while loop, we calculated the selling based on the RSI, the statement in line 22, we developed the first rule: RSI6 value is greater than 80, line 27 and line 23 we developed two parallel rules on a regular basis, through the above code, we will be stored RSI6 and more than 80 trading days through RSI12 (or RSI24) under RSI6 in sellDate objects, these trading day is the selling point.    

The sendMail DEF 34 is (username, pwd, from_addr, to_addr, MSG): 
35 and before the case exactly calRSIBuyPoints.py 
36 DEF buildMail (htmlContent, Subject, showfrom, showTo, attachfolder, attachFileName): 
37 [Case and prior calRSIBuyPoints.py is exactly the same 
38 subject = 'RSI selling analysis' 
39 attachfolder =' D: StockData \\ \\ \\ CH10 ' 
40 attachFileName =' 600584RSI.png ' 
41 is htmlContent =' <HTML> <head> </ head> < body> '\ 
42 is' selling date' + sellDate + \ 
43 is' <IMG the src = "CID: '+ attachFileName +'" /> '\ 
44 is' </ body> </ HTML>' 
45 Message = buildMail (htmlContent, Subject , 'hsm_computer 163.com @', '@ 163.com hsm_computer', attachfolder, attachFileName) 
46 is the sendMail ( 'hsm_computer','xxx','[email protected]','[email protected]',message.as_string()) 

 Two methods for sending messages and build and build previous case, line 34 and line 36 exactly the same, so no additional description.

   The message header in line 38 we define that "RSI selling point analysis" in HTMLContent target line 41 defined description of the body, our store is also "selling date", ultimately send a message to call sendMail method by line 46.

    Run the code, we can see the message shown below, including the selling date indicator and FIG. Here are more of a selling point calculated by date, by analysis, after these dates, the share price fell more than a case.

        

 

Summary 6 and Copyright

    This article is for programmers to add financial providers series, before the series as follows:

    Change Case entry to predict stock-based SVM machine learning  

    Draw integrated moving average K-line effect of the stock and the volume of matplotlib with python and numpy library (content of the code to verify trading strategies)  

    In this paper an effort to make detailed, such as code row number, and a detailed explanation for the line number, and illustrations, so if you feel you can, please try to help recommend.
This article is about the contents of a book, published in the book, is the point at which a stock of knowledge cases and we tell Python entry, stay tuned
    

    There are a lot of friends and you want to reprint reprint my blog, I am very honored, and this is I constantly write power Bowen. Copyright of this paper are as follows uniform, sorry not reply individually.

    1 This article may be reproduced without informing, please use the reprint, link the way, given the original source, do not simply given by the text, while the original author is stated hsm_computer.

    2 in the reprint, please reprint the original, declined wash draft. Otherwise, we reserve the right to pursue legal responsibilities.

 

Guess you like

Origin www.cnblogs.com/JavaArchitect/p/11463091.html