Professional Documents
Culture Documents
Unsplash
Problem Statement
What are the basic tools to get started with stocks quickly?
How do we know when we should enter and exit the stocks market?
Given the ease of setting up trading accounts in the middle of pandemic, many have
turned around to personal investing. And if you are reading this article, then
congratulations, this will be your first step to learn.
If you want to trade, you would need to ask these questions to start:
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 1/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
I have covered the first question in Value Investing. So in this publication, I would
focus on defining momentum in Key Market Indicators (KMI).
The objective for this publication is for you to understand one way of
analyzing stocks momentum with KMI using quick and dirty Python Code. Just
spend 10 minutes to read this article — or even better, contribute. Then you could get a
quick glimpse to code your first financial analysis with KMI.
Over 3 years of investing, I have received 62% of Stocks Portfolio Returns. This method
is simple and includes the peace of mind that often eludes risky investors.
Instructions
Colab Notebook
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 2/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
StocksMarketIndicators
Edit description
colab.sandbox.google.com
You can just click “Runtime > Run All” on Google Colab to run all the codes and generate
the graphs. You can also change the file repository by defining a new Github link
in link variable.
Finally, you can save all charts you created by uncommenting the following line. Define
variable “title” to name the picture title.
plt.savefig(f’{title}.png’)
Import Data
I borrowed Raj Shah’s Google Stocks Price CSV data which is hosted publicly on Github.
The code and the charts are presented below.
import pandas as pd
import requests
import numpy as
np
import
matplotlib.pyplot as plt
import datetime as dt
# Feel free to change the link to any you want or maybe web scrape the
value.https://towardsdatascience.com/value-investing-dashboard-with-
python-beautiful-soup-and-dash-python-43002
link = ‘https://raw.githubusercontent.com/raj-shah14/Predicting-Google-
Stock-Prices/master/Google_Stock_Price_Train.csv'
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 3/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
pandas_data = pd.read_csv(link)
print(pandas_data)
Data Cleaning
In most analysis of the key indicators, it is good to forwardfill and backfill the data to
close the gap of missing dates in unclean stocks data. This is to prevent propagating null
values in our analysis and use the nearest existing future dataset to cover the missing
dates.
def ffill_bfill(prices):
prices_temp = prices.copy()
prices_temp = prices_temp.fillna(method='ffill')
prices_temp = prices_temp.fillna(method='bfill')
return prices_temp
SMA is a tool that is commonly used by many analysts to predict security price changes.
It averages the prices within a window to identify overall trends and cycles. This is
calculated through the rolling mean of the stock’s normalized price. Each data point is
averaged equally in each period of the rolling window.
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 4/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
Prices (normalized).rolling(window).mean()
With signals:
* Overbought
prices_temp = prices.copy()
sma = prices_temp.rolling(window=window).mean()
sma.columns = [‘sma’]
return sma
def get_psma(prices,sma):
prices_temp = prices.copy()
psma = prices_temp/sma
return psma
price_df['sma'] = get_sma(price_df['Price'],10)
price_df['psma'] = get_psma(price_df['Price'],price_df['sma'])
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 5/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
SMA (upper) and PSMA (bottom) for GOOG 2014 Stocks (Sourced by Author)
The Bollinger Bands are charted by drawing lines with 2 standard deviations gaps from
the mean at any given time. These standard deviations are used with normalized prices
similar to SMA.
With signals:
— Lower bands) / (Upper Bands — Lower Bands)
* BBP = (Price
* Overbought scans → BBP >1
It works by quantifying the price closer to its BB upper and lower which indicates strong
overbought or strong oversold. By using this, we can still identify the trends with BB
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 6/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
while quantifying its situation to trigger actions when the entry point is right.
bb = pd.DataFrame(index=prices.index,columns = [‘Lower’,’Upper’])
bb[‘Upper’] = sma + std * 2
bb[‘Price’] = prices_temp
return bb
def get_bbp(bb):
bbp_df.columns=[‘bbp’]
return bbp_df
BB (Upper) and BBP (Bottom) for GOOG 2014 Stocks (Sourced by Author)
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 7/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
The formula includes calculating momentum through the stock price differences over a
window period with the early price as the denominator.
Through these signals, traders could identify bullish and bearish momentum. This allows
traders to take advantage of the market sentiment to predict rising or declining stocks
prices until the opposite swing comes. This is a good match to compare with SMA and
BBP Short which respond relatively quickly to price changes in the stocks market.
prices_temp[‘up’] = 0
prices_temp[‘down’] = 0
prices_temp[‘rsi’] = 0
prev_day = current_datetime-dt.timedelta(days=1)
try:
prev_day >= sd:
if
prev_price = prices_temp.loc[prev_day,’Price’]
if prev_price < row[‘Price’]:
continue
up_ewm = prices_temp[‘up’].ewm(span=periods).mean()
down_ewm = prices_temp[‘down’].ewm(span=periods).mean()
prices_temp.loc[:added_date,’rsi’] = np.nan
return prices_temp[[‘rsi’]]
price_df['rsi'] = get_rsi(price_df,dt.datetime(2008,1,28))
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 8/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
MACD
Similar to RSI, MACD also uses momentum indicators which plots relationships among
two Moving Averages. The formula subtracts 26 periods from 12 periods of Exponential
Moving Averages (EMA). Apart from the MACD formula, we also identify the signal line
which is calculated within 9 days EMA. We will put BUY actions if MACD crosses above
the signal line and SELL when MACD crosses below its signal line.
# From Investopedia
— 26 Period EMA
MACD = 12 Period EMA
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 9/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
usage of Exponential Moving Average (EMA) used in tandem with RSI to paint a clearer
picture of momentum in the market.
def get_macd(prices):
exp_1 = prices.ewm(span=12,adjust=False).mean()
exp_2 = prices.ewm(span=26,adjust=False).mean()
macd_df.columns = [‘macd’,’signal’]
return macd_df
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 10/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
Signal:
* When
def get_obv(prices,sd,volume):
price_temp = prices.copy()
volume_temp = volume.copy()
price_temp.columns = [‘Price’]
volume_temp.columns = [‘Volume’]
price_temp[‘Volume’] = volume_temp[‘Volume’]
price_temp[‘obv’] = 0
current_datetime = index
prev_day = current_datetime-dt.timedelta(days=1)
if prev_day >= sd:
prev_price = price_temp.loc[prev_day,’Price’]
prev_obv = price_temp.loc[prev_day,’obv’]
price_temp.loc[index,’obv’] = prev_obv
except:
continue
return price_temp[[‘obv’]]
price_df['obv'] =
get_obv(price_df[['Price']],dt.datetime(2008,1,28),volume_df)
With that, I hope you can get started in looking these signals and purchase your stocks.
Apart from his stint at Google, Vincent is also Georgia Tech CS MSc Alumni, a triathlete,
and a featured writer for Towards Data Science Medium to guide aspiring ML and data
practitioners with 1M+ viewers globally.
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 12/13
2/4/22, 2:50 PM Analyse Stocks with Key Market Indicators (KMI) In 10 Minutes | by Vincent Tatan | DataDrivenInvestor
https://medium.datadriveninvestor.com/analyse-stocks-with-key-market-indicators-kmi-in-10-minutes-36ec4fe409ae 13/13