MeanAnalyzer()
Mean analyzer for a pair of tickers
The MeanAnalyzer
class is designed to analyze and compare two stock tickers based on their price movements, log returns, and their relationship over a specified date range or time aggregation interval. The class also generates buy/sell signals when significant deviations occur between the log returns of the two stocks.
Class: MeanAnalyzer()
Compares two stocks based on normalized price movements and log returns.
Generates trading signals when the log return spread between the two stocks exceeds specified thresholds.
Supports both date ranges and interval-based time aggregation for data fetching.
Constructor: __init__()
Initializes the MeanAnalyzer
object, fetches stock data, prepares price and log return data, and calculates thresholds for generating buy/sell signals.
Arguments:
stock1 (
str
): The ticker symbol for the first stock (e.g., 'AAPL').stock2 (
str
): The ticker symbol for the second stock (e.g., 'MSFT').start (
str
, optional): Start date for fetching historical data in the format'YYYY-MM-DD'
. Used only wheninterval='1d'
. Defaults toNone
.end (
str
, optional): End date for fetching historical data in the format'YYYY-MM-DD'
. Used only wheninterval='1d'
. Defaults toNone
.interval (
str
, optional): Time aggregation for fetching data. Accepts values like'1d'
(daily),'60m'
(hourly), etc. Defaults to'1d'
. If set to anything other than'1d'
,start
andend
are ignored.show_signals (
bool
, optional): If set toTrue
, displays buy/sell signals on the chart. Default isTrue
.
Attributes Initialized:
price1: Closing prices for
stock1
.price2: Closing prices for
stock2
.price1_norm: Normalized prices for
stock1
.price2_norm: Normalized prices for
stock2
.log_return1: Logarithmic returns for
stock1
.log_return2: Logarithmic returns for
stock2
.spread: The difference between the log returns of the two stocks.
spread_mean: The mean value of the
spread
.spread_std: The standard deviation of the
spread
.threshold_upper: Upper threshold set at 4 standard deviations above the mean.
threshold_lower: Lower threshold set at 4 standard deviations below the mean.
Data Handling:
If
interval
is anything other than'1d'
, the class ignoresstart
andend
dates and fetches data based on the interval, with the maximum lookback allowed by the data source.If
interval='1d'
, the class fetches data between the specifiedstart
andend
dates.
Method: _generate_signals()
_generate_signals()
Generates long signals for buying or selling based on the deviation of the log return spread between the two stocks. If the spread exceeds the upper threshold, the first stock's price is expected to decrease, and the second stock's price is expected to increase. The reverse applies for when the spread falls below the lower threshold.
Returns:
long_signals_stock1 (
list
): A list of tuples containing signals forstock1
, indicating dates, prices, and signal direction ('up' or 'down').long_signals_stock2 (
list
): A list of tuples containing signals forstock2
, indicating dates, prices, and signal direction ('up' or 'down').
Method: plot()
plot()
Generates an interactive Plotly chart that visualizes price movements, normalized prices, log return spreads, and buy/sell signals for both stocks.
Chart Features:
Top pane 1: Displays the linear stock prices of
stock1
.Top pane 2: Displays the linear stock prices of
stock2
.Second pane: Displays the normalized prices of
stock1
andstock2
.Third pane: Displays the normalized spread between
stock1
andstock2
.Fourth pane: Displays the log return spread and shows the mean, thresholds, and buy/sell signals.
Signals:
If
show_signals=True
, buy/sell signals are annotated on the chart with arrows:Up arrow (green): A 'buy' signal indicating the price is expected to rise.
Down arrow (red): A 'sell' signal indicating the price is expected to fall.
Visualization Details:
Line Colors: Custom colors are used for different stock prices, normalized prices, spreads, and thresholds.
Hover Mode: Enables hovering over the chart to see unified data points.
Legend: Displays all chart lines with a background color.
Layout Configuration:
Background Colors: Plot and paper background colors are set to different shades of gray.
Axes: Custom grid colors and labels for the different panes.
Height: Chart height is set to 1000px for detailed visibility.
Example Usage:
Expected Output:
A detailed interactive Plotly chart with the following elements:
Stock prices for both
stock1
andstock2
.Normalized prices for comparison.
Log return spread between the two stocks.
Threshold lines for identifying overbought/oversold signals.
Buy/sell signals are indicated by arrows.
Customization Options:
Date Range or Time Interval:
You can choose between specifying a date range (using
start
andend
) for daily data or using a time aggregation interval (e.g.,'60m'
) to analyze intraday data.
Show Signals (show_signals
)
show_signals
)Set to
True
to display buy/sell signals on the chart (default behavior).Set to
False
if you do not want signals to be displayed.
Stock Tickers
The
stock1
andstock2
arguments allow you to compare any two stocks supported by Yahoo Finance.
Additional Notes
Threshold for Signal Generation: Signals are based on deviations in log returns exceeding 4 standard deviations from the mean.
Stock Data Source: The historical stock data is fetched using the Yahoo Finance API via the
yfinance
Python package.Handling No Data: If no data is found for the given tickers or interval, an error is raised.
Last updated