I want to calculate the difference between open and close price but taking to account if a trade is a Buy/Sell.
I have the conditional function below; but l do not know how to insert a new column with the results into the original dataframe which has a list of trades and l am getting an error with this function.
def pl_gap(type):
if type in mt_trades[‘type’] == ‘BUY’:
mt_trades[‘close_price’] – mt_trades[‘open_price’]
else:
mt_trades[‘open_price’] – mt_trades[‘close_price’]
mt_trades[‘pl_gap’] = mt_trades.apply(pl_gap)
>Solution :
Let me know if this works for you or If you can show me the head of your data I can help better without guessing.
Define a function to calculate the profit/loss gap based on trade type
def pl_gap(row):
if row['type'] == 'BUY':
return row['close_price'] - row['open_price']
else:
return row['open_price'] - row['close_price']
Apply the function to create a new ‘pl_gap’ column
mt_trades['pl_gap'] = mt_trades.apply(lambda row: pl_gap(row), axis=1)