I was attempting to follow the code on a YouTube video (https://www.youtube.com/watch?v=nPD_hZgwS00) which demonstrates how to make a stock screener. I watched the video linked above and the three previous videos as well. Following those videos I was able to detect a bullish engulfing pattern in a single stock (ticker PZZA). However when insert that function into the block of code below just as the content creator from the video had done, it failed to detect bullish engulfing patterns. The output from the code was:
- AMCR = 2020-06-12 is bullish engulfing
- HBAN = 2020-06-12 is bullish engulfing
- UAA = 2020-06-12 is bullish engulfing
However, these seem to be incorrect outputs if one looks at the charts on tradingview or other platform or on the csv files that were generated by the content creator in a previous part of the series. Here the open and close values for the three stocks identified by the code are:
AMCR 2020-06-11 Open: 9.57, Close: 9.19 AMCR 2020-06-12 Open: 10, Close: 9.81
HBAN 2020-06-11 Open: 9.82, Close: 9.48 HBAN 2020-06-12 Open: 10.03, Close: 9.89
UAA 2020-06-11 Open: 9.6, Close: 9.47 UAA 2020-06-12 Open: 10.01, Close: 9.7
Here you can see that the current day's open price (2020-06-12) for each of them is higher than the previous day's closing price (2020-06-11) even though my code stipulates that I want the current day's open price to be smaller than the previous day's close.
After trying all day I'm unable to identify where I went wrong. Any help would be appreciated. I plan to use this code to see if it is effective on my paper trading account as a fun exercise to use code instead of finding stocks to trade manually on websites.
Kind regards,
wdg
import csv
def is_bullish_candlestick(candle):
return candle['Close'] > candle['Open']
def is_bearish_candlestick(candle):
return candle['Close'] < candle['Open']
def is_bullish_engulfing(candles, index):
current_day = candles[index]
previous_day = candles[index-1]
if is_bearish_candlestick(previous_day)\
and current_day['Close'] > previous_day['Open']\
and current_day['Open'] < previous_day['Close']:
return True
return False
def is_bearish_engulfing(candles, index):
current_day = candles[index]
previous_day = candles[index-1]
if is_bullish_candlestick(previous_day)\
and current_day['Open'] > previous_day['Close']\
and current_day['Close'] < previous_day['Open']:
return True
return False
sp500_file = open('C:/Users/William/Desktop/Detecting Candlestick Patterns in Python/sp500_companies.csv')
sp500_companies = csv.reader(sp500_file)
for company in sp500_companies:
ticker, company_name = company
history_file = open('C:/Users/William/Desktop/Detecting Candlestick Patterns in Python/SP500_history/{}.csv'.format(ticker))
reader = csv.DictReader(history_file)
candles = list(reader)
#now to get most recent date
candles = candles[-2:]
if len(candles) > 1:
if is_bullish_engulfing(candles, 1):
print("{} = {} is bullish engulfing".format(ticker, candles[1]['Date']))