# How to Calculate Profit and Loss (P&Ls) for Your Trading Strategies (Hint: it’s not as easy as you think)

## Quantitative Trading Toolbox | Python for Financial Analysis

--

Calculating Profit and Loss (P&L) for your trading strategy can be surprisingly tricky at times. Traders are often surprised when their calculations of realised and unrealised P&Ls don’t match up. Today let’s see how it can be done by going through a **Moving Average (MA) Crossover strategy**.

To start with we create an arbitrary price series from normally distributed random numbers. Of course, you could also use market data from your favourite instrument, it doesn’t matter so much here as we are focussed on calculating strategy P&L curves.

## Backtesting for the MA Crossover Strategy

In the next step we create a backtest. In this backtest, we loop through our price data, calculate two moving averages and whenever the two moving averages cross we change from short to long and vice versa.

This part of the code shows a switch from a long to a short entry. When the second moving average is smaller than the first and we are not short, we first calculate the realised PnL, which is the profit of the whole trade. But first We want to make sure that we are already in a position, by using the “if inpos” condition. For long trades we subtract the entry price from the current price and for short trades we do the opposite.

This, of course, is a simplified backtest where we assume “perfect” execution, zero spreads and no commission. Note that