Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert a column with a conditional function into a dataframe

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading