3 Basic Steps of Stock Market Analysis in Python | by Roman Orac | Towards Data Science

Analyze Tesla stock in Python, calculate Trading Indicators and plot the OHLC chart. Includes a Jupyter Notebook with code examples.
I recently started reading Stan Weinstein's Secrets For Profiting in Bull and Bear Markets. In his book, Stan reveals his successful methods for timing investments to produce consistently profitable results.
Many investors say “This is the only investing book you will ever need to read”
Stan Weinstein is a professional stock market technical analysis. He became famous in 1987 when he predicted a 31% crash in the stock market where he used his chart reading skills.
My other articles about this topic:
romanorac.medium.com
Here are few links that might interest you:
- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]
Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything.
This is the first article in a series of Stock Market Analysis in Python in which I will try to describe and implement successful techniques to profit in the stock market.
Let’s start with the basics. In this article you will learn:
the easiest way to get the stock data in Python
what are trading indicators and how to calculate them
how to plot the stock data with OHLC chart
Note I am not a professional investor and I’m not responsible for your losses. This is educational content.
The easiest way to download the stock’s historical data in Python is with yfinance package. To install the package, simply run:
pip install yfinance
To download the daily stock prices for Tesla (TSLA) to a pandas DataFrame with yfinance is as simply as:
df = yf.download("TSLA", start="2018-11-01", end="2020-10-18", interval="1d")df.head()
yfinance download function has many arguments:
Instead of setting the interval to 1d, you can use 1m, 2m, 5m,15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo.
you can define multiple tickers in a list or string: “SPY AAPL MSFT”.
instead of start and end date, you can use the period “ytd” to download the data for one year from today. Other valid periods are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max.
see yfinance for more.
yfinance has many other useful functions, like the dividends function. Let’s say we would like to list dividends for AT&T (T).
t = yf.Ticker("T")t.dividends
t.dividends.plot(figsize=(14, 7))
Trading indicators are mathematical calculations, which are plotted as lines on a price chart and can help traders identify certain signals and trends within the market.
TA-LIB is one of the most used libraries in Python when it comes to technical analysis.
To use it, you first need to install TA-LIB dependency:
# Mac OS Xbrew install ta-lib# see https://github.com/mrjbq7/ta-lib for other platforms
Then you need to install python API:
pip install TA-Lib
The moving average (MA) is used to identify the direction of a current price trend, without the interference of shorter-term price spikes.
The MA indicator combines price points of a stock over a specified time frame and divides it by the number of data points to present a single trend line.
Let’s calculate 20 days (short term) and 200 days (long term) MA on TSLA Closing prices (we can calculate MA directly with pandas):
df.loc[:, 'ma20'] = df.Close.rolling(20).mean()df.loc[:, 'ma200'] = df.Close.rolling(200).mean()
Moving averages are used to identify significant support and resistance levels.
Traders watch for crossovers of longer-term moving averages by shorter-term moving averages as possible indicators of trend changes to enter long and short positions.
According to Stan Weinstein: The price must be above the short term MA in order to buy a stock.
The relative strength index (RSI) is a momentum indicator used in technical analysis that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or other asset.
The RSI is displayed as an oscillator (a line graph that moves between two extremes) and can have a reading from 0 to 100. It is most typically used on a 14-day timeframe.
If you are reading Stan Weinstein’s Secrets For Profiting in Bull and Bear Markets, Stan mentions relative strength, but don’t confuse it with RSI.
The relative strength tells about the value of a stock in comparison to another stock, index or benchmark, while the RSI tells about the performance of a stock in comparison to the recent performance of the same stock.
import talibdf.loc[:, "rsi"] = talib.RSI(df.Close, 14)
Now, let’s plot RSI with a line on 30 for oversold and 70 for overbought:
import matplotlib.pyplot as pltfig, ax = plt.subplots(1, 2, figsize=(21, 7))ax0 = df[["rsi"]].plot(ax=ax[0])ax0.axhline(30, color="black")ax0.axhline(70, color="black")df[["Close"]].plot(ax=ax[1])
An asset with RSI ≥70 is often considered overbought, while an asset with RSI ≤ 30 is often considered oversold:
an overbought signal suggests that assets may be in for a price correction.
an oversold signal could mean that short-term declines are reaching maturity and assets may be in for a rally.
In the plot above, we can observe a pattern that the TSLA price moves as the RSI suggests. When it is overbought (RSI ≥70) the price is in for correction and vise versa.
In this section, we are going to see how to plot an OHLC chart — a chart with bars Open, High, Low, Close prices, that we are used to seeing on trading platforms.
We are going to use the Plotly library for the OHLC chart. To install it:
pip install plotly
If you are using JupyterLab, you also need to install a Plotly extension, so that JupyterLab can render Plotly charts:
jupyter labextension install jupyterlab-plotly
To plot OHLC with Plotly, we simply need to set the prices on the correct inputs.
import plotly.graph_objects as gofig = go.Figure(    data=go.Ohlc(        x=df.index,        open=df["Open"],        high=df["High"],        low=df["Low"],        close=df["Close"],    ))fig.show()
As usual, you can download this Jupyter Notebook to try examples on your machine.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.