Detecting & Trading Technical Chart Patterns w/ Python (2024)

Algorithmic Trading Basics
Alpaca Team 25 Jan 2019
Detecting & Trading Technical Chart Patterns w/ Python (2)

Listening -

Detecting & Trading Technical Chart Patterns w/ Python (3)

Defining Technical Chart Patterns Programmatically

Ever wondered how to programmatically define technical patterns in price data?

At the fundamental level, technical patterns come from local minimum and maximum points in price. From there, the technical patterns may be defined by relative comparisons in these min/max points.

Let’s see if we could have played this by algorithmically identifying any inverse head & shoulders patterns!

Follow along with the notebook here.

samchaaa/alpaca_tech_screener

Contribute to samchaaa/alpaca_tech_screener development by creating an account on GitHub.

Detecting & Trading Technical Chart Patterns w/ Python (4)GitHubsamchaaa

Detecting & Trading Technical Chart Patterns w/ Python (5)

The following code can easily be retooled to work as a screener, backtester, or trading algo, with any timeframe or patterns you define.

Disclaimer: this code is intended as a starting point for finding technical patterns, it is for educational purposes only. The framework for this code came from here.

An Empirical Algorithmic Evaluation of Technical Analysis

At a recent meeting of the Quantopian staff journal club, I presented a paper by Andrew Lo, Harry Mamaysky, and Jiang Wang called Foundations of Technical Analysis: Computational Algorithms, Statistical Inference, and Empirical Implementation (2000) . In this paper, the authors utilize non-parametr…

Detecting & Trading Technical Chart Patterns w/ Python (6)Deleted User

Detecting & Trading Technical Chart Patterns w/ Python (7)

Step 1.) Read in data

I’m reading in data using the Alpaca API (which I’ll also use to place trades later).

I wrote this function to grab data beyond the one request limit of 2,000 minute bars. Later we’ll resample to our timeframe of choice.

import pandas as pdfrom datetime import timedeltaimport alpaca_trade_api as tradeapiapi = tradeapi.REST('YOUR API KEY HERE', 'YOUR API SECRET CODE HERE', 'https://paper-api.alpaca.markets')def get_data(symbol, lookback): all_data = pd.DataFrame() for x in range(lookback): if x == 0: data = api.polygon.historic_agg('minute', symbol, limit=None).df else: data = api.polygon.historic_agg('minute', symbol, _from = (data.index.min() - timedelta(days=5)).strftime('%x %X'), to = start, limit = None).df start = data.index.min().strftime('%x %X') end = data.index.max().strftime('%x %X') all_data = pd.concat([data, all_data], axis=0) all_data.drop(columns=['volume'], inplace=True) all_data.dropna(inplace=True) all_data = all_data[~all_data.index.duplicated()] all_data.replace(0, method='bfill', inplace=True) return all_datadata = get_data('CAT', 3)data

We’ll resample data separately, in case we want to try out different timeframes later.

resampled_data = data.resample('60T', closed='right', label='right').agg({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'}).dropna()resampled_data

Step 2.) Find minima and maxima

For this step we’ll use a function from scipy’s signal processing library to find peaks in the data.

This code looks complicated, but the point is to return the integer index values with price, for each min/max point.

import numpy as npfrom scipy.signal import argrelextremadef get_max_min(prices, smoothing, window_range): smooth_prices = prices['close'].rolling(window=smoothing).mean().dropna() local_max = argrelextrema(smooth_prices.values, np.greater)[0] local_min = argrelextrema(smooth_prices.values, np.less)[0] price_local_max_dt = [] for i in local_max: if (i>window_range) and (i<len(prices)-window_range): price_local_max_dt.append(prices.iloc[i-window_range:i+window_range]['close'].idxmax()) price_local_min_dt = [] for i in local_min: if (i>window_range) and (i<len(prices)-window_range): price_local_min_dt.append(prices.iloc[i-window_range:i+window_range]['close'].idxmin()) maxima = pd.DataFrame(prices.loc[price_local_max_dt]) minima = pd.DataFrame(prices.loc[price_local_min_dt]) max_min = pd.concat([maxima, minima]).sort_index() max_min.index.name = 'date' max_min = max_min.reset_index() max_min = max_min[~max_min.date.duplicated()] p = prices.reset_index() max_min['day_num'] = p[p['timestamp'].isin(max_min.date)].index.values max_min = max_min.set_index('day_num')['close'] return max_minsmoothing = 3window = 10minmax = get_max_min(resampled_data, smoothing, window)minmax

Let’s plot it with the resampled price data to visually confirm we’re on the right track.

Detecting & Trading Technical Chart Patterns w/ Python (8)

Step 3.) Find patterns

To find patterns, we simply iterate over all our min max points, and find windows where the points meet some pattern criteria.

Detecting & Trading Technical Chart Patterns w/ Python (9)

For example, an inverse head and shoulders can roughly be defined as:

C < A, B, D, E

A, E < B, D

To filter for head and shoulders with even necklines:

abs(B-D) < np.mean([B, D])*0.05

(The difference between the necklines must not be more than 5%.)

Here’s the code:

from collections import defaultdictdef find_patterns(max_min): patterns = defaultdict(list) # Window range is 5 units for i in range(5, len(max_min)): window = max_min.iloc[i-5:i] # Pattern must play out in less than n units if window.index[-1] - window.index[0] > 100: continue a, b, c, d, e = window.iloc[0:5] # IHS if a<strong and c<a and c<e and c<d and e<d and abs(b-d)<=np.mean([b,d])*0.02: patterns['IHS'].append((window.index[0], window.index[-1])) return patternspatterns = find_patterns(minmax)patterns
Detecting & Trading Technical Chart Patterns w/ Python (10)

As you can see, we are getting more patterns than we need. Our params (smoothing and window range) are too sensitive for this timeframe (60 minutes).

Step 4.) Reorganize and iterate to find best params

In order to find the best params, I reorganized my code into functions and iterated through multiple stocks, smoothing, and window parameters.

def plot_minmax_patterns(prices, max_min, patterns, stock, window, ema): incr = str((prices.index[1] - prices.index[0]).seconds/60) if len(patterns) == 0: pass else: num_pat = len([x for x in patterns.items()][0][1]) f, axes = plt.subplots(1, 2, figsize=(16, 5)) axes = axes.flatten() prices_ = prices.reset_index()['close'] axes[0].plot(prices_) axes[0].scatter(max_min.index, max_min, s=100, alpha=.3, color='orange') axes[1].plot(prices_) for name, end_day_nums in patterns.items(): for i, tup in enumerate(end_day_nums): sd = tup[0] ed = tup[1] axes[1].scatter(max_min.loc[sd:ed].index, max_min.loc[sd:ed].values, s=200, alpha=.3) plt.yticks([]) plt.tight_layout() plt.title('{}: {}: EMA {}, Window {} ({} patterns)'.format(stock, incr, ema, window, num_pat))def get_results(prices, max_min, pat, stock, ema_, window_): incr = str((prices.index[1] - prices.index[0]).seconds/60) #fw_list = [1, 12, 24, 36] fw_list = [1, 2, 3] results = [] if len(pat.items()) > 0: end_dates = [v for k, v in pat.items()][0] for date in end_dates: param_res = {'stock': stock, 'increment': incr, 'ema': ema_, 'window': window_, 'date': date} for x in fw_list: returns = (prices['close'].pct_change(x).shift(-x).reset_index(drop=True).dropna()) try: param_res['fw_ret_{}'.format(x)] = returns.loc[date[1]] except Exception as e: param_res['fw_ret_{}'.format(x)] = e results.append(param_res) else: param_res = {'stock': stock, 'increment': incr, 'ema': ema_, 'window': window_, 'date': None} for x in fw_list: param_res['fw_ret_{}'.format(x)] = None results.append(param_res) return pd.DataFrame(results)def screener(stock_data, ema_list, window_list, plot, results): all_results = pd.DataFrame() for stock in stock_data: prices = stock_data[stock] for ema_ in ema_list: for window_ in window_list: max_min = get_max_min(prices, smoothing=ema_, window_range=window_) pat = find_patterns(max_min) if plot == True: plot_minmax_patterns(prices, max_min, pat, stock, window_, ema_) if results == True: all_results = pd.concat([all_results, get_results(prices, max_min, pat, stock, ema_, window_)], axis=0) if results == True: return all_results.reset_index(drop=True)

Run the above like so:

Detecting & Trading Technical Chart Patterns w/ Python (11)

Now we can see how our timeframes, patterns, and params are playing out!

Step 5.) Go live!

To use this live, I made the following changes to screener():

def screener(stock_data, ema_list, window_list): triggers = [] all_results = pd.DataFrame() for stock in stock_data:prices = stock_data[stock] for ema_ in ema_list: for window_ in window_list: max_min = get_max_min(prices, smoothing=ema_, window_range=window_) pat = find_patterns(max_min) if len(pat) > 0: triggers.append(stock) return triggers

And ran like so:

stocklist = ['AA', 'AAL', 'AAPL', 'AMZN'] # Long list of stocks herestock_data = get_stock_data(stocklist, 2)resampled_stock_data = resample(stock_data, '360T')ema_list = [5]window_list = [5]results = screener(resampled_stock_data, ema_list, window_list)for x in results: api.submit_order(x, 100, 'buy', 'market', 'day')

Finding the right params for your pattern to play out may take experimentation. See the results() function in the notebook to confirm whether your patterns have a positive edge or not.

Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC (alpaca.markets), member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

You can find us @AlpacaHQ, if you use twitter.

Algorithmic Trading Basics

Alpaca Team

API-first stock brokerage. *Securities are offered through Alpaca Securities LLC* http://alpaca.markets/#disclosures

Detecting & Trading Technical Chart Patterns w/ Python (2024)

FAQs

Can AI identify chart patterns? ›

Every day, Pattern Search Engine (PSE) scans the charts of thousands of Stocks, ETFs, and FOREX. Users can choose any or all patterns they want to track, and the Artificial Intelligence (A.I.) will do the rest. A.I. performs the near-impossible task of scanning the market to locate your selected patterns.

What is the most accurate chart pattern to trade? ›

Some of the most successful chart patterns in trading include the Head and Shoulders pattern, Double Top and Double Bottom patterns, Triangle patterns, the Cup and Handle pattern, and the Flag and Pennant patterns.

How do you identify chart patterns automatically? ›

Chart Patterns on Charts

button next to the Chart Patterns in your top toolbar. Then, select the patterns you'd like to see. That's it! Some of the Chart Patterns do have settings (just like some indicators do have input parameters).

Can I do algo trading with Python? ›

You need to have a Trading Strategy. Intuition or gut feeling is not a successful strategy in the long run (at least in 99.9% of all cases). Relying on simple Technical Rules doesn´t work either because everyone uses them. You will learn how to develop more complex and unique Trading Strategies with Python.

Is there a free software to identify chart patterns? ›

ChartMill - ChartMill is a free website that offers chart pattern recognition for technical analysis. Their software can detect various chart patterns, including su.

Is there an AI that can analyze charts? ›

We got you covered. ChartEye will help you make better decisions. Simply click on the ChartEye extension icon while viewing a chart (e.g. on TradingView) and we will do the rest. Analyzing charts can be a daunting task, especially for those new to trading.

What chart do most day traders use? ›

A particularly popular day trading chart is the ascending triangle, also known as the "bullish pennant" called. It is a strong signal for an upward price trend. In this pattern, the apex of the triangle runs upwards, so that one can also speak of an ascending trend line.

Which trading indicator has the highest accuracy? ›

Which is one of the most accurate trading indicators? The most accurate for trading is the Relative Strength Index. It is considered one of the best momentum indicators for intraday trading. It helps investors identify the shares which are bought and sold in the market.

Which timeframe is best for chart patterns? ›

Start with a primary time frame, often daily/weekly, to identify core pattern. Then choose shorter intervals, e.g. Hourly / 15-min charts to determine accurate entry/exit points. Additionally, incorporate a longer time frame, such as a monthly chart, to assess the overall trend.

Which site is best for chart patterns? ›

Chart Patterns — TradingView — India.

How do you start recognizing patterns? ›

Here are some ideas for practicing pattern recognition in the classroom.
  1. Pattern Recognition Worksheets.
  2. Ask Students to Find Patterns Around the Classroom or Home.
  3. Perform an Object Challenge.
  4. Never Have I Ever — With a Twist.
  5. Play Board Games/Card Games.
  6. Practice Pattern Recognition in Computational Thinking.
Feb 21, 2023

What is the most repeated chart pattern? ›

The head and shoulders chart pattern and the triangle chart pattern are two of the most common patterns for forex traders. They occur more regularly than other patterns and provide a simple base to direct further analysis and decision-making. Try a demo account to practise your chart pattern recognition.

Do trading firms use Python? ›

Python. Python is an open-source programming language that follows a functional programming approach. One of the many reasons why Python makes it into the list of the top 10 programming languages that traders should learn in 2022 is because you can extend python code to trading algorithms that are easy to write.

How long does it take to learn Python for trading? ›

It is widely used by Traders, Analysts, and Researchers, and companies like Stripe and Robinhood in the finance industry. The duration to learn Python for finance ranges from one week to several months, depending on the depth of the course and your prior knowledge of Python programming and data science.

Which strategy is best for algo trading? ›

  1. Trend Following. Trend following, often serving as a navigational tool for many algorithmic traders, stands as a strategy as enduring as the market itself. ...
  2. Volatility. ...
  3. Quote stuffing. ...
  4. Trading Range. ...
  5. Inter-market spreading. ...
  6. Black swan events. ...
  7. Index Fund Rebalancing. ...
  8. Mean Reversion.
Feb 24, 2024

Can AI do pattern recognition? ›

Pattern recognition systems with AI are revolutionizing data processing. These systems allow us to identify complex patterns in massive data, and they can be applied to a variety of real-world problems.

Can AI read candlestick patterns? ›

TrendSpider automatically detects the candlestick formations on any chart and timeframe, including single candlesticks and multi-candlestick patterns.

Can AI pick winning stocks? ›

The use of AI for picking stocks is still in its infancy, but it is rapidly evolving. While the technology may be more sound compared to relying on social media stock tips, for example, AI-assisted investing tools have thus far shown mixed results and appear best suited for experienced and professional traders.

Can TradingView identify patterns? ›

Once you have selected a chart pattern, the indicator will automatically draw it on the chart for you when it detects the pattern.

Top Articles
Bharat Bond ETF: A tax-efficient, safe option for debt mutual fund investors
U. S. Taxation: Partnership Firms– LLC; updated
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
‘An affront to the memories of British sailors’: the lies that sank Hollywood’s sub thriller U-571
Tyreek Hill admits some regrets but calls for officer who restrained him to be fired | CNN
Haverhill, MA Obituaries | Driscoll Funeral Home and Cremation Service
Rogers Breece Obituaries
Ems Isd Skyward Family Access
Elektrische Arbeit W (Kilowattstunden kWh Strompreis Berechnen Berechnung)
Omni Id Portal Waconia
Kellifans.com
Banned in NYC: Airbnb One Year Later
Four-Legged Friday: Meet Tuscaloosa's Adoptable All-Stars Cub & Pickle
Model Center Jasmin
Ice Dodo Unblocked 76
Is Slatt Offensive
Labcorp Locations Near Me
Storm Prediction Center Convective Outlook
Experience the Convenience of Po Box 790010 St Louis Mo
Fungal Symbiote Terraria
modelo julia - PLAYBOARD
Poker News Views Gossip
Abby's Caribbean Cafe
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Tri-State Dog Racing Results
Navy Qrs Supervisor Answers
Trade Chart Dave Richard
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Stellaris Resolution
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 6308

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.