'how to calculate the rolling profit in a python pandas dataframe column?

I have buy and sell signals coming through and I want to calculate the rolling profit of those signals. I have a price and signal column and I want the rolling profit column to look something like this:

price   signal  Rolling_profit
50      buy     0
45      nan     0
30      nan     0
25      nan     0
75      sell    25
25      buy     0
30      nan     0
45      sell    45

Now the idea I had was to turn the sell signal prices negative and get the buy signal prices and just calculate the cumilative sum but that isnt necessarily the profit, is there a clean way to do this?



Solution 1:[1]

It is possible to use cumulative sum over a DataFrame.

sg['prof']=(sg['price']*(sg['sg'].map({'buy':-1,'sell':1}))).cumsum(axis=0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Y U