# Trading Strategy: Technical Analysis Using Python

Predict When To Buy & Sell Stock

First let me say it is extremely hard to try and predict the stock market. Even people with a good understanding of statistics and probabilities have a hard time doing this. However with all of that being said, if you are able to successfully predict the stock market, you could gain an incredible amount of profit. Please leave claps on this article to show your appreciation !

In this article I will show you how to use python and a technical indicator called relative strength index (RSI) , which is used in the analysis of financial markets to determine if a stock is being over bought or over sold.

If a stock is over sold, then this indicates a good time to buy, and if a stock is over bought then this indicates a good time to sell. Analyst use the RSI high and low values to determine this momentum shift. The relative strength index (RSI) is calculated by the following:

RSI = 100-(100/(1+RS))

A common time period to use for RSI is 14 days. The RSI returns values on a scale from 0 to 100, with high and low level values marked at (70 and 30), (80 and 20 ), and (90 and 10). The higher the high level and the lower the low level indicate a stronger price momentum shift. For example RSI is considered overbought when above 70 and oversold when below 30. RSI values of 50 represent a neutral condition.

If you prefer not to read this article and would like a video representation of it, you can check out the YouTube Video below. It goes through everything in this article with a little more detail, and will help make it easy for you to start programming your own Machine Learning model even if you don’t have the programming language Python installed on your computer. Or you can use both as supplementary materials for learning about Machine Learning !

If you are interested in reading more on machine learning and algorithmic trading then you might want to read Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python. The book will show you how to implement machine learning algorithms to build, train, and validate algorithmic models. It will also show you how to create your own algorithmic design process to apply probabilistic machine learning approaches to trading decisions, and the book will show you how to develop neural networks for algorithmic trading to perform time series forecasting and smart analytics.

Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python

Okay now with all of that out of the way, let’s start programming !

# Start Programming:

I will start this program with a description.

`#This program shows when to buy and sell stock using RSI`

Get the libraries that we will use throughout this program.

`# Import the python librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use('fivethirtyeight')`

Load, store, and show the data.

`#Load the datafrom google.colab import filesuploaded = files.upload()#Store the dataFB = pd.read_csv('FB.csv')#Show the dataFB`

Set the index to be the date.

`#Set the date as the index for the dataFB = FB.set_index(pd.DatetimeIndex(FB['Date'].values))FB`

Visually show the price.

`#Create and plot the graphplt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5plt.plot( FB.index,FB['Adj Close Price'],  label='Adj Close Price')#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending,  label)plt.title('Adj. Close Price History')plt.xlabel('May 20, 2019 - May 20, 2020',fontsize=18)plt.ylabel('Adj. Price USD (\$)',fontsize=18)plt.show()`

Calculate the RSI.

`delta = FB['Adj Close Price'].diff(1) #Use diff() function to find the discrete difference over the column axis with period value equal to 1delta = delta.dropna() # or delta[1:]up =  delta.copy() #Make a copy of this object’s indices and datadown = delta.copy() #Make a copy of this object’s indices and dataup[up < 0] = 0 down[down > 0] = 0 time_period = 14AVG_Gain = up.rolling(window=time_period).mean()AVG_Loss = abs(down.rolling(window=time_period).mean())RS = AVG_Gain / AVG_LossRSI = 100.0 - (100.0/ (1.0 + RS))`

Visually show the data.

`plt.figure(figsize=(12.2,4.5))RSI.plot()plt.show()`

Put it all together.

`new_df = pd.DataFrame()new_df['Adj Close Price'] = FB['Adj Close Price']new_df['RSI'] = RSIplt.figure(figsize=(12.2,4.5))plt.plot(new_df.index, new_df['Adj Close Price'])plt.title('Adj. Close Price History')plt.ylabel('Adj. Price USD (\$)',fontsize=18)plt.legend(new_df.columns.values, loc='upper left')plt.show()plt.figure(figsize=(12.33,4.5))plt.title('RSI Plot')plt.plot(new_df.index, new_df['RSI'])plt.axhline(0, linestyle='--', alpha=0.5, color = 'black')plt.axhline(10, linestyle='--', alpha=0.5, color = 'orange')plt.axhline(20, linestyle='--', alpha=0.5, color = 'green')plt.axhline(30, linestyle='--',color = 'red')plt.axhline(70, linestyle='--', color = 'red')plt.axhline(80, linestyle='--', alpha=0.5, color = 'green')plt.axhline(90, linestyle='--', alpha=0.5, color = 'orange')plt.axhline(100, linestyle='--', alpha=0.5, color = 'black')plt.xlabel('May 20, 2019 - May 18, 2020',fontsize=18)plt.ylabel('RSI Values (0 - 100)',fontsize=18)plt.show()`

Now that we have this nice chart, we can began the analysis. Around March 2020, the RSI value is below 20, this is an indication that the stock was over sold and presents a buying opportunity for an investor. If an investor took that opportunity to buy the stock around that time with a value around \$160 USD and sold it around mid May 2020, then that investor would have profited a little more than \$60 per share.

Also we can see that the stock was over bought with an RSI value over 80 sometime between January 2020 and February 2020 and indeed the stock price dipped shortly afterwards.

Thanks for reading this article I hope its helpful to you all ! If you enjoyed this article and found it helpful please leave some claps to show your appreciation. Keep up the learning, and if you like machine learning, mathematics, computer science, programming or algorithm analysis, please visit and subscribe to my YouTube channels (randerson112358 & computer science).

If you are also interested in reading more on machine learning in general to immediately get started with problems and examples then I strongly recommend you check out Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems. It is a great book for helping beginners learn how to write machine learning programs, and understanding machine learning concepts.

Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems

Written by