Algorithmic Trading : USE Tick Data to OHLC Candlesticks with Python

kamal chanchal
4 min readJan 26, 2024

--

NIFTY 50 Intraday Data : Candlestick (OHLC) visualization

In this article, we will build Python logic to convert live Feed Data (Tick data) to OHLC Data using python. we introduce a Python class named “TickByTick” designed to extract OHLC stock data from tick data series. Leveraging Object-Oriented Programming (OOP) concepts, we access class members and methods through objects.

To Know More about Tick data in Today’s Quant Trading , Please click on the link

import pandas as pd

Within the class, we include the Pandas library to read CSV files, facilitating the conversion of 1-dimensional tick data series into a 2-dimensional series with columns representing Open, High, Low, and Close prices.

Tick Data Source:

The tick data utilized in this tutorial is sourced from NSE Second Price Data, readily available on the NSE website. Despite NSE do not providing tick data for past trading dates, our class, TickByTick, accommodates this by treating the data as tick data.

Download Tick Data from NSE Website (Above chart is Showing NIFTY 50)

Store Data in-Memory:

Once the tick data is obtained and stored in a CSV file, we utilize the Pandas library to load it into a Data Frame.

    def get_tick_data( self , path ):
self.df_tick = pd.read_csv(path)

Algorithm to Convert Tick price Data to OHLC stocks Data:

The primary objective is to demonstrate how to convert tick prices to OHLC format.

  1. For Open price calculation, we consider the starting tick as the open price.
  2. The close price is determined by the last tick, marking the end of the trading period.

However, low and high prices are dynamic, influenced by the Last Trade Price (LTP) and they both have power to change anytime according to the market scenario. Unlike open and close prices, low and high prices have a broader range of possibilities.

To calculate high and low, we employ a comparable algorithm or update the open and high values of the stock based on the Last Trade Price.

The program below outlines the steps involved in this conversion, offering a practical demonstration of the process.

if self.High < ltp:
self.High= ltp

if self.Low > ltp:
self.Low = ltp

TickByTick Class Overview:

The TickByTick class encapsulates functionality to process tick-by-tick data and generate OHLC (Open, High, Low, Close) candlestick data. Let's understand using method.

Constructor:

def __init__(self):
print("Constructor calling")
self.read_tick_by_tick_data()

Upon instantiation, the constructor initializes the object and triggers the reading of tick-by-tick data from the specified CSV file.

Automate OHLC data Logic From Tick Data:

This method computes the Open, High, Low, and Close prices from the tick-by-tick data. It iterates through each tick, updating the OHLC values accordingly.

The logic involves initializing the OHLC values with the first tick’s price, and subsequently updating the Close, High, and Low prices based on the incoming tick data.

    def AutoCreat_OHLC_data_from_tbt( self ) :
self.Open = 0.0
self.High = 0.0
self.Low = 0.0
self.Close = 0.0

mflag_ReadingFirstTick = True

for idx , row in self.df_tick.iterrows( ) :

ltp = row[ "NIFTY 50" ]
if mflag_ReadingFirstTick == True :
mflag_ReadingFirstTick = False
print( "Reading First Tick" )
self.Open = ltp
self.High = ltp
self.Low = ltp
self.Close = ltp

# close price
self.Close = ltp

# Low and High
if self.High < ltp :
self.High = ltp

if self.Low > ltp :
self.Low = ltp

self.High = max( self.High , ltp )
self.Low = min( self.Low , ltp )

"""stmt """
print( F"O :{self.Open} , H= {self.High} , L:{self.Low}, C:{self.Close}" )

Once executed, the method prints the calculated OHLC values for analysis and further processing.

Class Level implementation:

class TickByTick :

def __init__( self ) :
print( "Constructor calling -" )
self.read_tick_by_tick_data( )

def read_tick_by_tick_data( self ) :
filepath = "Provide File path"
self.df_tick = pd.read_csv( filepath )

def AutoCreat_OHLC_data_from_tbt( self ) :
self.Open = 0.0
self.High = 0.0
self.Low = 0.0
self.Close = 0.0

mflag_ReadingFirstTick = True

for idx , row in self.df_tick.iterrows( ) :

ltp = row[ "NIFTY 50" ]
if mflag_ReadingFirstTick == True :
mflag_ReadingFirstTick = False
print( "Reading First Tick" )
self.Open = ltp
self.High = ltp
self.Low = ltp
self.Close = ltp

# close price
self.Close = ltp

# Low and High
if self.High < ltp :
self.High = ltp

if self.Low > ltp :
self.Low = ltp

self.High = max( self.High , ltp )
self.Low = min( self.Low , ltp )

"""stmt """
print( F"O :{self.Open} , H= {self.High} , L:{self.Low}, C:{self.Close}" )

Calling:

# Create an instance of the TickByTick class
oQS = TickByTick()

# Call the method for automatic OHLC data creation
oQS.AutoCreat_OHLC_data_from_tbt()

Thanks For Reading .

Feel free to integrate this into your quantitative trading projects or explore how this class can enhance your understanding of market dynamics through OHLC candlesticks. Happy coding! 🚀📈

If you found this article on converting tick stock data to OHLC data using Object-Oriented Programming (OOP) style helpful or insightful, please give it a round of applause! Your support means a lot and encourages me to share more valuable content in the future. Thank you for reading and clapping! 🎉

📊You can also read my other Post Like:BackTesting Strategy Setup: Building a Python Trading Strategy Analyzer

📊Explore the full potential of this project by visiting our GitHub repository.

LinkedIn : https://www.linkedin.com/in/kamalchanchal

#hft #quantfinance #tbt #marketfeed #quant #pythonforfinance #Nifty #candlesticks #nse #niftydata #PythonProgramming #DataAnalysis #Finance #ObjectOrientedProgramming #StockMarket #algotrading #stockmarket #stocksanalysis #algotrading #algorithmictrading #investing

--

--

kamal chanchal

C# | Python | Capital Market | Artificial Intelligence | Data Science Engineering