Search code examples
pythonpandasquantitative-finance

looping through a pandas dataframe and applying an if esle function


I am trying to build a simple backtester using python, the backtester works by comparing 2 values in a certain time, as (at time x check if indicator_value > ohlc_value: order_type = 1; else order type will be = 0)

data = {'time':[0, 1, 2, 3, 4, 5], 'ohlc':[1.1, 1.2, 1.3, 1.4, 1.5,1.66], 'indicator':[1.05, 1.22, 1.4, 1.55, 1.6,1.77]}
df = pd.DataFrame(data)

how can i set those values?

if data['ohlc'] > data['indicator']:
      data['order_type'] = 1
else:
      data['order_type'] = 0

I know I cant loop dataframes like that.


Solution

  • Here you go:

    df['order_type'] = (df['ohlc'] > df['indicator']).astype(int)
    print(df)
    

    Output:

       time  ohlc  indicator  order_type
    0     0  1.10       1.05           1
    1     1  1.20       1.22           0
    2     2  1.30       1.40           0
    3     3  1.40       1.55           0
    4     4  1.50       1.60           0
    5     5  1.66       1.77           0
    

    If you have custom values to assign based on different conditions, here' one way to go (the default is 0):

    import numpy as np
    conditions = [df['ohlc'] > df['indicator']]
    choices = [-1]
    df['order_type'] = np.select(conditions, choices)
    print(df)
    

    Output:

       time  ohlc  indicator  order_type
    0     0  1.10       1.05          -1
    1     1  1.20       1.22           0
    2     2  1.30       1.40           0
    3     3  1.40       1.55           0
    4     4  1.50       1.60           0
    5     5  1.66       1.77           0