Trades of the stock KPITTECH.NS
I am new to Python and data analysis actually. In the above dataframe, I want to use the FIFO method to find the profit/loss made. I want to take each transaction where the stock was bought, calculate its returns till the selling date using FIFO.
I tried iterating through the values, added the quantities sold till the sold quantity >= quantity bought. But from here I am unable to take it forward.
To calculate the profit/loss using the FIFO (First-In, First-Out) method for stock trades, you need to keep track of the purchase history and match each selling transaction with the earliest available buying transaction. Here's an example of how you can implement this in Python:
This code assumes you have a DataFrame named trades_df that contains the stock trade data, including columns for the date, action (buy or sell), quantity, and price. The code first sorts the trades by date in ascending order to ensure the FIFO order. Then, it iterates over each trade, keeping track of the purchased quantity and price. When encountering a selling transaction, it matches the earliest buying transaction(s) to calculate the profit/loss and updates the Profit/Loss column accordingly. After running this code, you will have an updated trades_df DataFrame with the profit/loss calculated for each trade.