We will use the Kiteconnect module in python for this tutorial

You will need to have zerodha API subscription and python setup for this

The following code will give the Profit and loss summary for trades taken throughout the day:



import pandas as pd
from kiteconnect import KiteConnect

def orderbook():
    orders = kite.orders()
    order_df = pd.DataFrame(orders)

    order_book = order_df[order_df.status =='COMPLETE']
    
    return order_book

orders = orderbook()

orders['symbol'] = orders['tradingsymbol'].apply(lambda x: x.split('2', 1)[0])
orders['turnover'] = orders['quantity']*orders['average_price']
orders_sell = orders[orders['transaction_type'] == 'SELL']
turnover_sell = orders_sell['turnover'].sum()


traded_symbols = orders['symbol'].to_list()
symbols_traded = unique(traded_symbols)

print("\nSymbols traded during the day:\n%s" %symbols_traded)
print("Total symbols: %s\n" % len(symbols_traded))


pos_df_1 = pd.DataFrame(kite.positions()["net"])
pos = pos_df_1[['tradingsymbol', 'exchange', 'instrument_token', 'product', 'quantity','average_price','pnl']]
pos= pos.sort_values(['pnl'], ascending=[False])
pos['symbol'] = pos['tradingsymbol'].apply(lambda x: x.split('2', 1)[0])
Pnl_summary = pos[['symbol', 'pnl']]
Pnl_summary.reset_index(drop=True, inplace=True)
Pnl_summary.loc["Total"] = Pnl_summary.sum(numeric_only=True)
Pnl_summary2 = Pnl_summary['pnl'].groupby(Pnl_summary['symbol'])
x = pd.DataFrame(Pnl_summary2.sum())
x.sort_values(['pnl'], ascending=[False], inplace=True)
x.loc["Total"] = x.sum(numeric_only=True)


turnover = orders['turnover'].sum()
No_orders = orders['turnover'].count()
brokerage = No_orders * 20
etc = turnover * 0.00053
tax = (brokerage+etc)*0.18
stt = turnover_sell * 0.0005

Total_deductions = int(brokerage+etc+tax+stt)
print("Total orders: %s\nTotal deductions for the day: %s" % (No_orders, Total_deductions))
Pnl = int(pos['pnl'].sum() - Total_deductions)
print("Net PnL for the day: Rs. %s\n" % Pnl)
print("PnL Summary:\n %s\n" % x)

After running the script we get the output as per the trades taken throughout the day. My algo traded the following instruments:

If you liked what i post here regularly then kindly subscribe and visit me at https://twitter.com/rahul_12gh

Leave a Reply