pythonpandaspyalgotrade

Python algo trading pandas data clean up and call from another function


I have below code and is working fine when I am executing from console. Now I want convert the code constructor which will help to call this and get data.

from kiteconnect import KiteConnect
import pandas as pd
from datetime import datetime
from dateutil.relativedelta import relativedelta
import math
import numpy as np
import talib
import json

# Setting Spyder environmental variables
pd.set_option("display.max_columns", 30)
pd.set_option("display.max_rows", 500)
pd.set_option("display.width", 1000)

with open('C:/AlgoTrade/TradeApp/config/brokerapp.json') as f:
    data = json.load(f)
    access_token = data['accessToken']
    api = data['appKey']
    kite=KiteConnect(api_key=api)
    kite.set_access_token(access_token)

End_Time = datetime.now().date()
Start_Time = End_Time + relativedelta(days=-30)

# Function to calculate DATR
   
def DATR():
    BF_DATR = pd.DataFrame(kite.historical_data(260105,Start_Time,End_Time,"day",False,True))
    atr = (talib.ATR(BF_DATR["high"], BF_DATR["low"], BF_DATR["close"], timeperiod = 14)).tail(1)
    atr2p = math.ceil(atr * .02)
    return atr, atr2p
DATR, DATRP = DATR()

print("DATR : %2d, 2 percentage of DATR : %3d" % (DATR, DATRP))


# Find explosive candles in 5 mins range

class Zones:
    def __init__(self, data):
        self.data  = data
                    
    def candle_type(self):
        """this column will be true if the candle is up """
        self.data['candle_type'] = np.where(self.data['open'] < self.data['close'], "Bullish", "Bearish")

    def body_spread(self):
        """the body of the candle"""
        self.data['body'] = (self.data['close'] - self.data['open']).abs()
        self.data['spread'] = self.data['high'] - self.data['low']

    def is_exciting_candle(self):
        self.data['candle_size'] = np.where(((self.data['body'] > (0.55*self.data['spread'])) & (self.data['body'] > DATRP)), "Exciting", "Basing")
                      
    def clean(self):
        """removes unneeded columns"""
        self.data.drop(['volume','oi', 'body', 'spread'], axis=1, inplace= True)

    def run_all(self):
        """run all the methods"""
        self.candle_type()
        self.body_spread()
        self.is_exciting_candle()
        self.clean()
        
Start_Time = End_Time + relativedelta(days=-100)
data = pd.DataFrame(kite.historical_data(260105,Start_Time,End_Time,"5minute",False,True))
data['date'] = pd.to_datetime(data['date']).apply(lambda x: x.replace(tzinfo=None))
sample =  Zones(data=data)
sample.run_all()
data = sample.data
print(data)

Now I need to convert above code to constructor and call from another function. Which should return the pandas data frame.

Expected out put is, when we call the constructor from another function it should return the data.

BANKNIFTYDATA = zone.data() print(BANKNIFTYDATA)

             date      open      high       low     close candle_type candle_size

0 2022-08-04 09:15:00 38111.05 38230.55 38111.05 38166.65 Bullish Basing 1 2022-08-04 09:20:00 38165.00 38165.00 38079.90 38098.80 Bearish Exciting 2 2022-08-04 09:25:00 38099.90 38157.50 38096.75 38113.05 Bullish Basing 3 2022-08-04 09:30:00 38114.45 38141.20 38086.10 38108.85 Bearish Basing 4 2022-08-04 09:35:00 38106.10 38115.00 38051.50 38066.40 Bearish Exciting 5 2022-08-04 09:40:00 38060.65 38111.75 38054.00 38081.95 Bullish Basing 6 2022-08-04 09:45:00 38081.80 38151.40 38080.75 38133.60 Bullish Exciting 7 2022-08-04 09:50:00 38133.85 38170.20 38131.05 38161.75 Bullish Exciting 8 2022-08-04 09:55:00 38163.20 38166.40 38112.10 38129.30 Bearish Exciting 9 2022-08-04 10:00:00 38131.70 38141.15 38093.10 38117.65 Bearish Basing


Solution

  • I got my answer..

    class NiftybankData:    
        def __init__(self):
            End_Time = datetime.now().date()
            Start_Time = End_Time + relativedelta(days=-100)
        
    def data(self):
        data = pd.DataFrame(kite.historical_data(260105,Start_Time,End_Time,"5minute",False,True))
        data['date'] = pd.to_datetime(data['date']).apply(lambda x: x.replace(tzinfo=None))
        data['candle_type'] = np.where(data['open'] < data['close'], "Bullish", "Bearish")
        data['body'] = (data['close'] - data['open']).abs()
        data['spread'] = data['high'] - data['low']
        data['candle_size'] = np.where(((data['body'] > (0.55*data['spread'])) & (data['body'] > DATRP)), "Exciting", "Basing")
        
        data.drop(['volume','oi', 'body', 'spread'], axis=1, inplace= True)
        
        return data
    
    NiftyBank = NiftybankData().data()
    print(NiftyBank)