Let's assume I have an array of trades (Buys/Sells), associated with timestamps.
[
{
"time": "01-05-2021", // DD-MM-YYYY
"operation": "BUY",
"amount": 2,
"price": 10
},
{
"time": "01-06-2021",
"operation": "SELL",
"amount": 1,
"price": 15
},
{
"time": "01-07-2021",
"operation": "BUY",
"amount": 2,
"price": 20
},
{
"time": "01-08-2021",
"operation": "SELL",
"amount": 3,
"price": 25
}
]
And I want to calculate P&L on these trades, using FIFO, but for arbitrary time period.
The problem is - calculated value depends on time period I'll choose.
- For 08.2021 it'll be 0 (3 items were sold, none was bought).
- For 07-08.2021 it'll be 10 (2 items were bought for total of 40, 2 were sold for total 50).
- For 06-08.2021 it'll be 0 (SELL 1 on 15 -> BUY 1 on 20 == -5 and BUY 1 on 20 -> SELL 1 on 25 == 5).
And so on. The only working solution that I have right now is to calculate P&L values for each deal, from the beginning of trading activity. And then, just "cut off" everything beside required period. But it's not scalable, because with even without automated trading it can be thousands of deals each year. The most obvious thing to do is to add some initial state to the beginning of given period, which will be starting point for all further calculations.
Are there any algorithms or tools which I can utilize to perform this task? I'm a Javascript developer, and my solution works in the browser's runtime. Maybe I need some backend, maybe I need R with it's statistics-dedicated package...