Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate realized P&L of stock trades using the FIFO method?

I'm looking for a Python plugin that would calculate the realized P&L for a number of stock transactions using the FIFO method.

For example, assume we have the following three MSFT trades:

+75 MSFT 25.10
+50 MSFT 25.12
-100 MSFT 25.22

The sell of 100 shares at 25.22 would fully net against the buy of 75 at 25.10 and partially net against the buy of 50 at 25.12 i.e.

Realized P&L = 75 * (25.22 - 25.10) + 25 * (25.22 - 25.12) = $ 11.50

The outstanding position would be:

+25 MSFT 25.12

like image 305
Nikola Miles Avatar asked Jun 24 '10 17:06

Nikola Miles


People also ask

What is realized P?

Realized P&L (Profit and Loss) refers to profit or loss on a completed trade. This means a position which has been initiated and then closed. It also includes any and all fees and commissions associated with the transaction.

How do you calculate profit per share potential?

To calculate your profit or loss, subtract the current price from the original price. The percentage change takes the result from above, divides it by the original purchase price, and multiplies that by 100.

What is formula of gain?

The formula for calculating gain is as follows: Gain = Selling price – Purchase price.

What is realized and unrealized gains?

In accounting, there is a difference between realized and unrealized gains and losses. Realized income or losses refer to profits or losses from completed transactions. Unrealized profit or losses refer to profits or losses that have occurred on paper, but the relevant transactions have not been completed.


2 Answers

No Python, but the R project blotter --- which is part / core of the larger TradeAnalytics project on R-Forge does just that.

I recently needed a subset of the functionality in C++ and used the blotter code to benchmark / guide my port to C++. (That was at work, so no public C++ from that, sorry.)

like image 140
Dirk Eddelbuettel Avatar answered Oct 10 '22 17:10

Dirk Eddelbuettel


This should be easy to write yourself in Python. "FIFO" is short for "first in, first out queue". Buys are added to the back of the queue. Sells munch buys (or parts of them) off the front of the queue.

Python's collection.deque (double-ended queue) is what you need for the mechanics.

like image 28
John Machin Avatar answered Oct 10 '22 16:10

John Machin