Showing posts with label Technical Indicators. Show all posts
Showing posts with label Technical Indicators. Show all posts

15 April 2020

Calculation of Supertrend (ST)

The Supertrend is one of the most widely used Indicator among the Indian traders. And unfortunately there is very little documentation on this subject at Investopedia or the chart school of Stockcharts or even with Zerodha Varsity. So it required quite some investigation to arrive at the right method to calculate the Supertrend.

In its simplest form, when the Supertrend is overlayed over a candlestick chart, if the Supertrend crosses to below the Price we take a Long Position and when the Supertrend crosses to above the Price, we take a Short position. Here is a snapshot of the Supertrend.

This article from Economic Times is probably a good place to start with to get a qucik overview of Supertrend.

So let us dive straight into and get the calculation of Supertrend. Check this Google Sheet for the Calculation of Supertrend. 

Given below is the pseudo code for the calculation of Supertrend:

Basic UpperrBand = (High + Low) / 2 + Multiplier * ATR
Basic LowerBand =  (High + Low) / 2 - Multiplier * ATR

Final UpperBand = IF((Current BasicUpperband < Previous Final UpperBand) OR 
                    (Previous Close > Previous Final UpperBand))  THEN 
                    (Current Basic UpperBand) ELSE
                    (Previous FinalUpperBand)

Final LowerBand = IF((Current Basic LowerBand > Previous Final LowerBand) OR
                    (Previous Close < Previous Final LowerBand)) THEN
                    (Current Basic LowerBand) ELSE
                    (Previous Final LowerBand)

SuperTrend = IF((Previous SuperTrend = Previous Final UpperBand) AND 
               (Current Close <= Current Final UpperBand)) THEN 
               Current Final UpperBand
             ELSE
                IF((Previous SuperTrend = Previous Final UpperBand) AND
                  (Current Close > Current Final UpperBand)) THEN
                  Current Final LowerBand
                ELSE
                   IF((Previous SuperTrend = Previous Final LowerBand) AND
                     (Current Close >= Current Final LowerBand)) THEN
                     Current Final LowerBand
                   ELSE
                      IF((Previous SuperTrend = Previous Final LowerBand) AND
                        (Current Close < Current Final LowerBand)) THEN
                        Current Final UpperBand

Now lets see how this is calculated in Python. Lets first download the OHLCV data from the above google sheet into a CSV file. Name it as "test data". We can use this as our input file for the Python program.

Lets first take a look at the Imports and Global Declarations that we will use in this program:
#imports used in the program
import numpy as np
import pandas as pd

#Global Declarations
input_file = "test data.csv"
multiplier = 2 # An integer to indicate the value to multiply the ATR.
period = 14
atr = 'ATR' + '_' + str(period)
st = 'SuperTrend' + '_' + str(period) + '_' + str(multiplier)

03 December 2019

Calculation of Average True Range (ATR)

Average True Range (ATR) is a Technical Indicator that measures Market Volatiity. This indicator was developed by Welles Wilder

From Statistics , we know that Range in Trading refers to the (High - Low) for the timeperiod/candlestick in concern. Wilder has started a Concept caled True Range which is defined as the Greater of the following:
  • Current High minus the current Low
  • Absolute Value of Current High minus the previous Close
  • Absolute Value of Current Low minus the previous Close
For more details on ATR, check out Investopedia

Welles Wilder used the Absolute Values as he was interested in measuring the distance between two points, not the direction.

Take a look at the Google Sheet for Calculation of ATR. I have used GOOGLEFINANCE function to retreive the OHLCV of NIFTY for the first quarter of 2019. The GOOGLEFINANCE function is actually what makes Google Sheets such a compelling use. In due course I intend to publish a post to retreive OHLCV data for 1 minute candlestick from Google Sheets , on that can be used with Pandas DataFrame. In my opinion, once we create such an API, it is a better alternative to Quandl or Alpha Vantage or Quantra Blueshift or Twelve Data API for Backtesting. It also gives us the opportunity to do Live Testing of a Trading System with Live Data , but without risking actual Money. But more on that later on .... Here is the Google Sheet for now :

https://docs.google.com/spreadsheets/d/13pKpTZuDgPlb7jqH2Pyp8ypo7G97NKgV1YIgJ4j4toI/edit#gid=1308165568

The calculation in the above google sheet is based on the standards as per StockCharts

Now lets copy the Values in the Excel We can copy the OHLCV data from the above google sheet and calculate the rest of the data. If you do it n a Excel spreadsheet, you will see that the ATR obtained from the excel is the same as the ATR obtained from Google Sheet. Now let us convert the excel to csv and use this csv file as the Input for our Python program.

07 January 2017

Calculating Exponential Moving Average (EMA) using Google Sheets

The concept of Exponential Moving Average is explained here in this link

The calculation of the Exponential Moving Average(EMA) can get tricky, unlike the calculation of the Simple Moving Average(SMA). If you take the same set of data points and determine the EMA on Google Sheets, Excel and Python, you will find that there is a difference in the EMA. That's becos to calculate the EMA there are different methods in adjusting the weights, which is handled differently (internally) in Excel , Google Sheets and Python.

Or from a traders perspective, you would have noticed that there is a difference between the values of EMA in Sharekhan, Zerodha PI, Amibroker etc. This is becos: 
  1. There is a variance in the data feeds that these trading terminals use. This also leads to a difference in calculation of SMA or any other technical indicator.
  2. There is a variance in the method that they use internally to determine the calculation of EMA.
  3. Or probably one of them is using Excel, another is using Google Sheets and the third is using Python !!!

Thanks to the efforts of  Marcello, we now have an easier google sheets method to calculate the EMA for use in trading. Here is the link:  https://docs.google.com/spreadsheets/d/1iBxaU-yeiG_ta4waj0YD6O8mn6DgbKUfE5Ap6W4aIis/edit#gid=0

In case you want a Python based method, check out this oneliner code I mentioned in Stackoverflow . Or scroll below for more details.

Here is a good explanation for the calculation of EMA using Pandas:

Now lets get to the Python Code for the Calculation of SMA and EMA. Lets have an input file in the standard OHLCV format with Date/Datetime includedlabelled as Open, High, Low, Close, Volume. Now lets say that we want to calculate the SMA and the EMA for the Close price
#imports and Declarations used in the program

import pandas as pd
input_file = "test data.csv"
period = 10
sma = 'SMA' + '_' + str(period)
ema = 'EMA' + '_' + str(period)

These would be the functions that we use in the program
def SMA(df_stock, base_column, target_column, period=14):
    """
    Function to compute Simple Moving Average (SMA)
    
    Arguments :
        df_stock : This is the Pandas DataFrame which contains ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] columns
        base_column : The String that indicates the column name from which the SMA is computed.
        target_column : The string that indicates the column name in which the computed data will be stored.
        period : This integer that indicates the period of computation in terms of number of candles
        
    Returns :
        df_stock : Pandas DataFrame with new column added with SMA for the period mentioned.
    """
    
    df_stock[target_column] = df_stock[base_column].rolling(window=period).mean()
    df_stock[target_column].fillna(0, inplace=True)

    return df_stock
 
def EMA(df_stock, base_column, target_column, period=14, alpha=False):
    """
    Function to compute Exponential Moving Average (EMA)
    
    Args :
        df_stock : Pandas DataFrame which contains the columns ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
        base_column : The String that indicates the column name from which the EMA needs to be computed
        target_column : The String that indicates the column name in which the computed data will be stored
        period : An Integer that indicates the period of computation in terms of number of candles
        alpha : Boolean Value- If True indicates to use the formula for computing EMA using alpha (default is False)
        
    Returns :
        df : Pandas DataFrame with new column added with name 'target'
    """

    con = pd.concat([df_stock[:period][base_column].rolling(window=period).mean(), df_stock[period:][base_column]])
    
    if (alpha == True): #  set alpha=True for calculation of ATR
        df_stock[target_column] = con.ewm(alpha=1 / period, adjust=False).mean()
    else: # set alpha=False for Calculation of EMA
        df_stock[target_column] = con.ewm(span=period, adjust=False).mean()
    
    df_stock[target_column].fillna(0, inplace=True)
    return df_stock

Next is to call the functions from the manin program:
df_stock = pd.read_csv(input_file,header='infer',infer_datetime_format=True)
df_stock['Date'] = pd.to_datetime(df_stock['Date']) # convert date to datetime

SMA(df_stock, 'Close', sma, period)

EMA(df_stock, 'Close', ema, period, False)
The EMA calculated using this method is in sync with the EMA retreived from brokers like Sharekhan and Zerodha. In case there is a variance, try and increase the number of datapoints. The trick is to to have more datapoints for accurate smoothing, preferrably 250 datapoints or more.

The EMA calcuation using Python was taken from https://github.com/arkochhar/Technical-Indicators. Thank you arkochhar