Back To Top

February 15, 2024

Riding the Waves of Stock Prices with Wavelet Transform Signals in Python

Towards Unlocking Market Signals for Clearer Trading Insights

You know, when you look at how stocks move up and down, it can seem as unpredictable as ocean waves. However, just like scientists can predict wave movements by understanding the underlying currents, we can also try to make sense of stock market patterns using similar tools – like the wavelet transform.

First off, by utilizing the wavelet transform, we’re essentially peering beneath the surface to uncover the deep currents driving stock prices. Furthermore, this isn’t merely about crunching numbers and data. We’re taking the seemingly erratic stock behaviors and attempting to find some rhythm behind it all.

wavelet transform signals applied to stock prices www.entreprenerdly.com

2. Wavelet Transform Theory

At the very core, a wavelet is like a brief vibration or oscillation that packs all its energy into a short burst of time. It’s intense but fades out quickly. For example, think about striking a drum – that sound is powerful but doesn’t last very long.

Now, this short-lived nature of wavelets is actually really useful when analyzing financial data that keeps changing over time. The statistical properties aren’t constant, they fluctuate. And wavelets can handle that.

Using a wavelet transform is kind of like getting a microscope to examine stock data up close. With it, you can see the big overall trends, but also zoom in on those tiny, minute fluctuations. It lets you view the details from multiple perspectives.

2.1 Why Not Fourier Transform?

Many might think, why not just use the Fourier Transform, which is a very popular tool to analyze signals? Fourier Transform breaks down a signal into its constituent sinusoids. However, its Achilles’ heel is its inability to provide both time and frequency information simultaneously.

While it can tell us the frequencies present, it’s often oblivious to when they occur. Unlike its Fourier counterpart, Wavelet Transform captures both the frequency and the time, providing a time-frequency representation of the signal.

2.2 The Essence of Wavelet Transform

Mathematically, the Wavelet Transform can be represented as:

Fourier Transform entreprenerdly.com

Equation. 1: Wavelet Transform Representation

  • f (t) represents our stock data.
  • ψ (t) is the chosen wavelet pattern.
entreprenerdly.com wavelet signal

Figure. 1: On the left, the Continuous Wavelet Transform (CWT) visualizes stock data at different scales, capturing varied time durations. On the right, a Ricker wavelet moves through the stock signal, with its correlation shown below. Together, they spotlight how wavelets localize patterns in stock data, distinguishing short-term fluctuations from long-term trends.

We’ll now delve into the Python implementation of the Wavelet Transform for deriving buy/sell signals from stock data which is what might be of interest to traders and Data Scientist. The code employs the Continuous Wavelet Transform to extract features that can indicate potential buy or sell moments in the stock’s historical data.

3.1 Setting up the Environment

Ensure you have the required Python libraries. If not, they can be installed via pip:

				
					pip install numpy pandas matplotlib yfinance scipy
				
			

3.2 Fetching the Stock Data

Using the yfinance library, we can easily fetch stock data for analysis:

				
					import yfinance as yf

ticker = "SIE.DE"
stock_data = yf.download(ticker, start="2018-01-01", end="2023-12-30")
				
			

3.3 Applying the Continuous Wavelet Transform (CWT)

The scipy library provides the required functions to compute the CWT using the Ricker wavelet:

				
					from scipy import signal

widths = np.arange(1, 15)
cwt_result = signal.cwt(stock_data['Close'].values, signal.ricker, widths)
				
			

3.4 Extracting Buy and Sell Signals

From the computed CWT, positive and negative coefficients can be extracted, indicating upward and downward movements in stock price, respectively.

				
					cwt_positive = np.where(cwt_result > 0, cwt_result, 0)
cwt_negative = np.where(cwt_result < 0, cwt_result, 0)

buy_signal = pd.Series(np.sum(cwt_positive, axis=0), index=stock_data.index)
sell_signal = pd.Series(-np.sum(cwt_negative, axis=0), index=stock_data.index)
				
			

3.5 Identifying Signal Crossovers

Crossovers between buy and sell signals can potentially indicate trading opportunities.

				
					cross_above = (buy_signal >= sell_signal) & (buy_signal.shift(1) < sell_signal.shift(1))
cross_below = (buy_signal <= sell_signal) & (buy_signal.shift(1) > sell_signal.shift(1))
				
			

3.6 Visualization

A visual representation can provide a clearer perspective on the buy/sell moments against the stock’s historical data:

				
					import matplotlib.pyplot as plt

plt.figure(figsize=(30, 6))
plt.plot(stock_data.index, stock_data['Close'], label='Close Prices', alpha=0.5)
plt.scatter(stock_data.index[cross_above], stock_data['Close'][cross_above], label='Buy Signal', marker='^', color='g')
plt.scatter(stock_data.index[cross_below], stock_data['Close'][cross_below], label='Sell Signal', marker='v', color='r')
plt.title(f'{ticker} Historical Close Prices with Wavelet Transform Buy and Sell Signals')
plt.legend()
plt.show()
				
			

3.7 Complete Python Code

Putting all the code together we get

Plotting Smarter Stock Entries & Exits With K-Reversal In Python

Implementation of the Simple, Yet Powerful K-Reversal Indicator
Prev Post

Identify Key Market Shifts with the Volatility Ratio

Next Post

Modelling Extreme Stock Market Events With Copulas in Python

post-bars
Mail Icon

Newsletter

Get Every Weekly Update & Insights

[mc4wp_form id=]

Leave a Comment