Can Candlestick Patterns Make You Rich? Exploring the Answer Through Machine Learning.
Introduction
Candlesticks are widely used in technical analysis for price movement predictions by identifying patterns. The candlestick is the most popular way to visualize price data. Through a candlestick chart, one can interpret the price movements and price actions of anything tradable, from stocks, funds, and Bitcoin to iPhone prices.
This post by Sofien Kaabar explains candlesticks and some of their patterns. If you are interested, you can check it out.
In this post, I will explore whether we can make use of historical data to form candlesticks that can help predict price direction and inform investment decisions, and whether using chart patterns is a good investment strategy or if there is a better strategy.
Objectives
By using the price data of S&P 500 and BitCoin from Yahoo Finance, I aim to achieve the following.
- Examine the price movement and market trend of the current market of S&P 500.
- Examine whether prices have patterns
- Predict price direction using historical data
- Examine the profitability of trading based on historical price actions
- Examine if buy-and-hold is a better strategy
1. Examine the price movement and market trend of the current market of S&P 500.
To analyze the price movement and market trend of the current S&P 500 market, I utilized data sourced from Yahoo Finance, encompassing essential metrics such as date, open price, close price, highest price, lowest price, and trading volume. Leveraging the Python mpf
package, I constructed insightful candlestick charts that visually illustrate the stock's price fluctuations over time, facilitating informed investment decisions. By scrutinizing these candlestick patterns, investors can glean valuable insights into prevailing market sentiment and potential future price trajectories.
Disclaimer: This presentation is intended solely for educational purposes within the context of our school project. The analysis and discussion of S&P 500 prices presented herein do not constitute financial or investment advice. Any decisions made based on the content of this presentation are at your own risk. We strongly encourage consulting with a qualified financial advisor before making any investment decisions. The information provided is subject to change and should not be relied upon as a guarantee of future performance. Past performance is not indicative of future results. We do not endorse or recommend any specific investments or trading strategies.
The chart initially depicts a downtrend characterized by a succession of red candlesticks, indicating closing prices lower than opening prices. However, by early October, a notable reversal occurs, marked by a conspicuous uptrend evidenced by an increasing prevalence of blue candlesticks, reflecting closing prices surpassing opening prices. Furthermore, the upward sloping trajectory of both the 10-day and 20-day moving averages corroborates this bullish trend.
Notably, during late November and early December, spikes in trading volume coincide with price surges, signifying robust buying activity. Moreover, the price consistently forms higher highs and higher lows, indicative of a sustained bullish trend. The transition from red to blue candlesticks, coupled with heightened trading volume, underscores a shift from bearish to bullish sentiment in early September.
Throughout the depicted period, the moving averages serve as dynamic support levels, with the price maintaining its position above these thresholds post-trend reversal. This adherence suggests these moving averages act as areas of significant buying interest. Furthermore, the upward slope of the moving averages, combined with the formation of higher highs and higher lows, reaffirms the strength of the upward trend.
As the chart concludes, there is no discernible indication of a reversal pattern, implying the likelihood of the continued upward trajectory of the market. In summary, the prevailing market sentiment appears decidedly bullish during this period, as evidenced by the consistent upward trend depicted in both the price action and the behavior of the moving averages.
2. Examine whether prices have patterns
Exploring whether any cool patterns are hiding in the daily prices of the S&P 500 from 1990 to 2024 was quite the journey! I ended up creating a whopping 8600 candlestick charts, each one showing 14 price points. Then, I fed all of this data into a machine-learning model to see if we could spot any trends or clusters.
Now, why did I go for 16 patterns, you might ask? Well, imagine slicing each chart in half — left for past trends, right for future ones. Each half could either be flat, going up, going down, or swinging around. So, when you combine these possibilities, you get 16 different combinations! Pretty neat, right?
After crunching the numbers, I did find some interesting stuff. Not every chart fits neatly into a category, but that’s the nature of the beast. Still, some recurring themes were popping up. It took some eyeballing to confirm, but there are some patterns.
This whole process was a reminder of just how complex the stock market can be. But, uncovering these patterns could be a game-changer for understanding market dynamics and making smarter investment moves down the line.
3. Predict price direction using historical data
I trained another machine learning model for forecasting move movements.
I took all those candlestick charts I had before and chopped off the right half, leaving only the historical data. Then, I fed the first 7 candlesticks into a supervised learning model, splitting the data into training and testing sets — 80% for training and 20% for testing.
Now, here is where things got interesting. When I tested the model, hoping it could predict which cluster the price trend belonged to, the accuracy rate was a dismal 18%. This is not a great result.
But, all hope was not lost. Even though the model could not nail down the exact cluster, it might still be onto something. For instance, if both Cluster 3 and Cluster 7 indicate upward movements, then misclassifying a chart from Cluster 3 as Cluster 7 wouldn’t be the end of the world, right? We could still make a buy decision based on that prediction.
Sure, the model is not perfect, and we’re far from the accuracy rates needed for profitable algorithmic trading. But, every little insight counts in the world of stocks, and even imperfect predictions can sometimes lead to smart decisions. With this regard, it flows into my next objective.
4. Examine the profitability of trading based on historical price actions
To assess the profitability of trading based on historical price actions, I conducted a trade simulation using a machine learning model that I trained. Here are the details of the simulation and its outcomes:
Assumptions:
- Initial amount: $1000
- Trading vehicle: Bitcoin (continuous data availability, no market holidays, unbiased — may be biased if we use stock market because the model is trained on stock market data)
- Maximum 1 buy or short position and one exit trade per day
- Each trade will be closed 7 days after entry
- Trade amount is 1% of the account balance
- Trade decisions are based on predicted cluster numbers derived from candlestick patterns
- No trading occurs when there are less than 7 days left until the end of the trading period
- The minimum loss is the trade amount
Trading Period: January 1, 2023, to February 14, 2024
I implemented this simulation using Microsoft Excel by adding a few columns after the price data.
Result Analysis:
During the trading period, despite the increasing trend in Bitcoin’s price, my portfolio consistently decreased. This indicates that the trading strategy based on historical price actions did not perform well under the given conditions.
The table below outlines each trade made during the specified period, including the position type, direction, entered amount, trade amount, closed date, close price, profit or loss (P/L), and the remaining amount in the portfolio after each trade.
Despite the effort to trade based on historical price actions, the results indicate a consistent decline in the portfolio’s value. This suggests that the trading strategy may require refinement or adjustment to better align with market conditions or the specific behavior of Bitcoin’s price movements during the given period.
How the investment strategy could be improved:
- Allowing to close the position when the position has a certain profit percentage (say 30%), not necessarily to close after 7 days
- Setting stop loss to close the position as a risk management measure (say 10%)
- Enter only long positions and no short positions because the long-term trend for both S&P 500 and Bitcoin is upward
This result also ties to my next and final objective of this project.
5. Assessing the “Keep -Buying-and-Hold” Strategy
Recently, I stumbled upon a book advocating a timeless investment approach: buy-and-hold. The book emphasizes disregarding short-term price fluctuations, trends, highs, and lows. Instead, it promotes consistent, long-term investment in strong businesses, echoing the philosophy of renowned investor Warren Buffett. This strategy prioritizes patience, prudent financial decisions, and continuous learning in the realm of investing.
Inspired by this philosophy, I decided to simulate the “buy-and-hold” strategy in the context of trading Bitcoin. Here are the parameters and outcomes of this simulation:
Simulation Details:
- Initial Amount: $1000
- Trading Vehicle: Bitcoin (continuous data availability, no market holidays, unbiased results)
- Strategy: Keep buying every day and hold until the last trading day
- Trade Amount: Account balance * 0.01
- Trade Decision: Based on predicted cluster numbers
- No Trading: When there are less than 7 days left until the end of the trading period
- Minimum Loss: Set to the trade amount
- Trading Period: January 1, 2023, to February 14, 2024
Results:
The simulation yielded promising results, with the equity curve indicating an 80% return over the 13-month period. Despite fluctuations and potential purchases at high prices, the strategy of consistently buying and holding Bitcoin proved profitable. This outcome aligns with the book’s philosophy, demonstrating that even if investments are made at high points, the long-term upward trajectory of the asset can lead to profitability over time.
To sum up, the “buy-and-hold” strategy, as exemplified by the simulation, underscores the importance of patience, resilience, and a focus on long-term growth rather than short-term fluctuations. While individual trades may not always be timed perfectly, the overall upward trend of the asset can still result in significant returns. This approach resonates with the timeless wisdom advocated by seasoned investors like Warren Buffett, emphasizing the value of holding onto strong assets through market fluctuations for sustained wealth accumulation.
Conclusion
Navigating the twists and turns of investment strategies can feel like chasing shadows in a foggy maze. This exploration has shown that spotting clear-cut patterns in markets is no easy feat. What seems obvious at first often proves to be more complex upon closer inspection.
Patterns are Tricky:
Market patterns are like elusive phantoms, slipping through our fingers just as we think we’ve caught them. The ever-changing nature of financial markets makes it tough to predict trends with certainty. What looks like a sure thing one day can flip upside down the next.
Subjectivity in Interpretation:
The interpretation of market patterns is inherently subjective. Investors often perceive the same signals differently, influenced by their individual biases, perspectives, and analytical methods. What one investor regards as a bullish signal might be seen as bearish by another. This subjectivity adds complexity to investment decision-making, as diverse viewpoints lead to divergent strategies and outcomes.
Keep it Simple:
In the midst of all this complexity, simplicity often wins out. The age-old “buy-and-hold” or the keep-buying strategies stand as a testament to this. While other tactics may dazzle with complexity, sticking to the basics can often yield the best results in the long run.
Finally, Investing doesn’t have to be rocket science. By embracing the straightforward approach of buying quality assets and holding onto them for the long haul, you can navigate the ups and downs of the market with confidence. It’s not about chasing every trend or deciphering every pattern — sometimes, the simplest strategy is the most effective.
The Python code (data gathering, candlestick charts generation, machine learning model), Excel simulation model, and the clustered images of candlesticks can be found on my GitHub.