Search code examples
pythonfinance

How do i fix this ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool() for my candlestick scanner?


This candlestick I have made currently works for single stocks but when manipulated to multiple stocks comes up with this error

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Here is my work so far:

import datetime as dt 
import pandas_datareader as web
import pandas as pd

start = dt.datetime(2020,1,1)
end = dt.datetime.now()
Stock = ['ANZ.AX','APT.AX']

df = web.DataReader(Stock, 'yahoo', start, end)

# Change data to omit volume and adjusted close (can change later to display volume)
data = df[['Open', 'High', 'Low', 'Close']]

for i in range(2, df.shape[0]):
    current = df.iloc[i, :]
    prev = df.iloc[i - 1, :]
    prev_2 = df.iloc[i - 2, :]

    realbody = abs(current['Open'] - current['Close'])
    candle_range = current['High'] - current['Low']

    idx = df.index[i]

    # Bullish engulfing
    df.loc[idx, 'Bullish engulfing'] = prev['Open'] > prev['Close'] and current['Close'] > current['Open'] \
    and current['High'] > prev['High'] and current['Low'] < prev['Low']

df.fillna(False, inplace=True)

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print(df['Bullish engulfing']) 

Solution

  • You need to use bitwise operators (& for AND and | for OR) for boolean operations in pandas:

    df.loc[idx, 'Bullish engulfing'] = (prev['Open'] > prev['Close']) & (current['Close'] > current['Open']) \
    & (current['High'] > prev['High']) & (current['Low'] < prev['Low'])