Dashboards
  • Reddit Stocks

  • Top Finance News Based on Comments and Tweets

  • Stocks Trading Ideas

  • Twitter Stocks

  • StockTwits Stocks

  • Most Discussed Crypto Currencies

  • New Crypto Currencies

  • Reddit Crypto Currencies

  • Reddit Penny Stocks

  • Reddit Spacs

  • Jim Cramer Stocks

  • Stock Market Movers

  • Stocks Sma 10 Crossed 20 Crossed 30

  • Stocks above 10 but below 20 and 30 SMA

  • Top Trending Crypto Currencies

  • Top US ETF Options By Open Interest

  • Most Active US ETF Options By Volume

Tradestie.com
  • Post Idea
  • Blogs
  • Dashboards
    • Economy Bell
      Weather Stocks
    • Oil Stocks
    • Smh Stocks
    • QQQ Stocks
    • SPY Stocks
    • ARKK Stocks
    • Cyber Security Stocks
    • Cloud Stocks
    • More
  • Stocks
    • Reddit Stocks
    • Twitter Stocks
    • Stock Twits Stocks
    • Stock Market Movers
    • Stock Market Sector Performance
    • Stocks Trading Ideas
    • Stocks W Candlestick Patterns
    • Stocks Above 10 20 and 30 SMA
    • Stocks Above And Below 20 Day Price
    • OpenAi Finance News
  • Crypto
    • Top Crypto Currencies
    • New Crypto Currencies
    • Top Crypto Stocks
  • Options
    • Top 10 Stocks By Max Change In Options Open Interest
    • Top Stocks By Options Money At Open Interest
    • Top Stocks By Options Open Interest
    • Top Stocks By Most Active Options
    • Top Etfs By Options Open Interest
    • Top Etfs By Most Active Options
  • Influencers
    • Cathie Woods
    • Jim Cramer
    • Pete Najarian
  • API
  • Profile Photo

    • Build Dashboard
    • Login
    • Privacy Policy
Tradestie.com
  • Post Idea
  • Blogs
  • Dashboards
    • Economy Bell
      Weather Stocks
    • Oil Stocks
    • Smh Stocks
    • QQQ Stocks
    • SPY Stocks
    • ARKK Stocks
    • Cyber Security Stocks
    • Cloud Stocks
    • More
  • Stocks
    • Reddit Stocks
    • Twitter Stocks
    • Stock Twits Stocks
    • Stock Market Movers
    • Stock Market Sector Performance
    • Stocks Trading Ideas
    • Stocks W Candlestick Patterns
    • Stocks Above 10 20 and 30 SMA
    • Stocks Above And Below 20 Day Price
    • OpenAi Finance News
  • Crypto
    • Top Crypto Currencies
    • New Crypto Currencies
    • Top Crypto Stocks
  • Options
    • Top 10 Stocks By Max Change In Options Open Interest
    • Top Stocks By Options Money At Open Interest
    • Top Stocks By Options Open Interest
    • Top Stocks By Most Active Options
    • Top Etfs By Options Open Interest
    • Top Etfs By Most Active Options
  • Influencers
    • Cathie Woods
    • Jim Cramer
    • Pete Najarian
  • API
  • Profile Photo

    • Build Dashboard
    • Login
    • Privacy Policy

Candlestick Patterns Using Python

In this tutorial, I will build a candlestick chart pattern scanner using Python and pandas ta lib.

I have the stocks data stored in mongoDB. It is very easy to retrieve and insert data in mongo.

Let us first import the necessary packages for pandas, talib and pymongo. Make sure you have numpy, pandas_ta, talib,pymongo and mongoDB installed.

In [1]:
import pymongo
from pymongo import MongoClient
import datetime
import pandas as pd
from talib.abstract import *
import pandas_ta as ta


Let us initiate the mongo DB Connection.

In [2]:
client = MongoClient('mongodb://149.56.26.138:27017')
db = client['stocksdata']

Let us look at our stock document. Document is similar to a row in MySQL.

In [3]:
db.eod_stock_data.find_one()
Out[3]:
{'_id': ObjectId('6202f99a80d4ed2d9c536156'),
 'date': datetime.datetime(2020, 1, 2, 0, 0),
 'open': 21.86,
 'high': 21.86,
 'low': 21.315,
 'close': 21.42,
 'adjusted_close': 21.3733,
 'volume': 3062541,
 'ticker': 'AA',
 'perchange': None}

For this tutorial, let us try to find the candlestick patterns for APPLE (ticker aapl) stock.

Below command will extract the data from mongo for the last 300 days.

In [4]:
db.eod_stock_data.find({'ticker':'AAPL'}).sort([('date',pymongo.DESCENDING)]).limit(300)
Out[4]:
<pymongo.cursor.Cursor at 0x7fd02223bfa0>

Note above command will return a mongo Cursor, we will have iterate over it to see the data for each day.

Let us store this data in a variable.

In [39]:
docs = db.eod_stock_data.find({'ticker':'AAPL'}).sort([('date',pymongo.DESCENDING)]).limit(300)
In [40]:
for doc in docs:
    print(doc)
    break
{'_id': ObjectId('6378006ca528ace221e1a5ac'), 'date': datetime.datetime(2022, 11, 18, 0, 0), 'open': 152.305, 'high': 152.57, 'low': 149.97, 'close': 151.29, 'adjusted_close': 151.29, 'volume': 70799117, 'ticker': 'AAPL', 'perchange': 0.38}

Let us convert the above data in to pandas Dataframe. since pandas_ta requires pandas dataframe as an input.

In [44]:
docs = db.eod_stock_data.find({'ticker':'AAPL'}).sort([('date',pymongo.DESCENDING)]).limit(300)
In [45]:
df = pd.DataFrame(docs)

Let us check the first row in our data.

In [46]:
df.head(1)
Out[46]:
_id date open high low close adjusted_close volume ticker perchange
0 6378006ca528ace221e1a5ac 2022-11-18 152.305 152.57 149.97 151.29 151.29 70799117 AAPL 0.38

the first row in our dataframe shows the data for latest date. However the pandas_ta require the data in ascending order. Let us change the order of our data in ascending form.

In [47]:
df = df[::-1]

Also we need to change the "date" name to "datetime".

In [48]:
df.rename(columns={'date':'datetime'},inplace=True)
In [49]:
df.head(1)
Out[49]:
_id datetime open high low close adjusted_close volume ticker perchange
299 6202f9d580d4ed2d9c5379f9 2021-09-10 155.0 155.48 148.7 148.97 148.5636 140893203 AAPL -3.31

Let us re-print our first row.

In [50]:
df.head(1)
Out[50]:
_id datetime open high low close adjusted_close volume ticker perchange
299 6202f9d580d4ed2d9c5379f9 2021-09-10 155.0 155.48 148.7 148.97 148.5636 140893203 AAPL -3.31

We would need to set the datetime as index which is also required by pandas_ta.

In [51]:
df.set_index(pd.DatetimeIndex(df["datetime"]), inplace=True)
In [52]:
df.head(1)
Out[52]:
_id datetime open high low close adjusted_close volume ticker perchange
datetime
2021-09-10 6202f9d580d4ed2d9c5379f9 2021-09-10 155.0 155.48 148.7 148.97 148.5636 140893203 AAPL -3.31

pandas_ta only requires datetime, open, high, low, close and volume. We can remove the other columns.

In [53]:
df.drop(columns=['datetime','adjusted_close','perchange','_id','ticker'],inplace=True)
In [54]:
df.head(1)
Out[54]:
open high low close volume
datetime
2021-09-10 155.0 155.48 148.7 148.97 140893203

Ok, now we have our dataframe in correct (pandas_ta) format. Let us run df.ta.strategy('All') step to calculate everything.
Note you can run it selectively too for specific patterns, for that checkout the pandas_ta documentation page.

In [55]:
df.ta.strategy("All")
0it [00:00, ?it/s]/home/anaconda3/envs/condapy38/lib/python3.8/multiprocessing/pool.py:48: FutureWarning: The series.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
  return list(map(*args))
131it [00:00, 477.00it/s]

The above step will add columns for the candlestick patterns. Let us check our dataframe. Last row will contain the data for the most recent date.

In [56]:
df.tail(1)
Out[56]:
open high low close volume ABER_ZG_5_15 ABER_SG_5_15 ABER_XG_5_15 ABER_ATR_5_15 ACCBL_20 ... VIDYA_14 VTXP_14 VTXM_14 VWAP_D VWMA_10 WCP WILLR_14 WMA_10 ZL_EMA_10 ZS_30
datetime
2022-11-18 152.305 152.57 149.97 151.29 70799117 149.762153 154.894866 144.62944 5.132713 134.810048 ... 149.822045 0.924025 0.938888 151.276667 145.953573 151.28 -19.743711 148.330364 150.943228 1.123647

1 rows × 283 columns

The above row contains 283 columns. Let us print the name of these columns.

In [57]:
df.columns
Out[57]:
Index(['open', 'high', 'low', 'close', 'volume', 'ABER_ZG_5_15',
       'ABER_SG_5_15', 'ABER_XG_5_15', 'ABER_ATR_5_15', 'ACCBL_20',
       ...
       'VIDYA_14', 'VTXP_14', 'VTXM_14', 'VWAP_D', 'VWMA_10', 'WCP',
       'WILLR_14', 'WMA_10', 'ZL_EMA_10', 'ZS_30'],
      dtype='object', length=283)

Let us print the value of some of these candlestick patterns.

In [58]:
df['CDL_3LINESTRIKE']
Out[58]:
datetime
2021-09-10    0.0
2021-09-13    0.0
2021-09-14    0.0
2021-09-15    0.0
2021-09-16    0.0
             ... 
2022-11-14    0.0
2022-11-15    0.0
2022-11-16    0.0
2022-11-17    0.0
2022-11-18    0.0
Name: CDL_3LINESTRIKE, Length: 300, dtype: float64
In [59]:
df['CDL_HAMMER']
Out[59]:
datetime
2021-09-10    0.0
2021-09-13    0.0
2021-09-14    0.0
2021-09-15    0.0
2021-09-16    0.0
             ... 
2022-11-14    0.0
2022-11-15    0.0
2022-11-16    0.0
2022-11-17    0.0
2022-11-18    0.0
Name: CDL_HAMMER, Length: 300, dtype: float64

Note if the pattern is not true, the value is 0.0, so to find out the days when there is a candlestick pattern, check when the value is not zero as shown below.

In [60]:
for index,row in df.iterrows():
    if row['CDL_HAMMER'] > 0 or row['CDL_HAMMER'] < 0:
        print(index,row['CDL_HAMMER'])
2021-10-13 00:00:00 100.0
2022-03-10 00:00:00 100.0
2022-04-25 00:00:00 100.0
2022-05-02 00:00:00 100.0
2022-09-16 00:00:00 100.0
2022-09-23 00:00:00 100.0

The actual implementation of above scanner is here...
https://tradestie.com/apps/indicators/stocks-candlestick-patterns/