I would like to compare 2 rows in a pandas dataframe but I always get an Error saying: AttributeError: 'float' object has no attribute 'MACD'.
This is the df:
time open high low close tick_volume spread real_volume EMA_LONG EMA_SHORT MACD SIGNAL HIST 200EMA
0 2018-01-05 03:00:00 1.20775 1.20794 1.20700 1.20724 2887 1 0 1.206134 1.206803 0.000669 0.000669 0.000000 1.207240
1 2018-01-05 04:00:00 1.20723 1.20743 1.20680 1.20710 2349 1 0 1.206216 1.206849 0.000633 0.000649 -0.000016 1.207170
2 2018-01-05 05:00:00 1.20709 1.20755 1.20709 1.20744 1869 1 0 1.206318 1.206941 0.000622 0.000638 -0.000016 1.207261
Now I want to count on how many times it would buy and sell based on some information in the rows so I'm trying to iterate through it like this:
buy = 0
sell = 0
for i, row in df.iterrows():
if i == 0:
continue
if row.MACD > row.SIGNAL and row[i - 1].MACD < row[i - 1].SIGNAL:
if row.HIST < 0 and row.MACD > row['200EMA'] and row.SIGNAL > row['200EMA']:
buy = 1
elif row.MACD < row.SIGNAL and row[i - 1].MACD > row[i - 1].SIGNAL:
if row.HIST > 0 and row.MACD < row['200EMA'] and row.SIGNAL < row['200EMA']:
sell = 1
print("BUY: " buy "SELL: " sell)
I am getting the following Error:
AttributeError: 'float' object has no attribute 'MACD'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-75-ff4a2b3629bc> in <module>
8 if row.HIST < 0 and row.MACD > row['200EMA'] and row.SIGNAL > row['200EMA']:
9 buy = 1
---> 10 elif row.MACD < row.SIGNAL and row[i - 1].MACD > row[i - 1].SIGNAL:
11 if row.HIST > 0 and row.MACD < row['200EMA'] and row.SIGNAL < row['200EMA']:
12 sell = 1
AttributeError: 'float' object has no attribute 'MACD'
I know this Error has already been here but I the solutions there didn't help me.
Thank you already!
CodePudding user response:
your problem his here row[i - 1].MACD
when you are accesessing the row[i-1] place you get the value of the location in the service if i = 1 then you will get the row[0] for the row and not the preivice row in the dataframe you should probably switch it by df.iloc[i-1].MACD