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 when interval='1d'. Defaults to None.

  • end (str, optional): End date for fetching historical data in the format 'YYYY-MM-DD'. Used only when interval='1d'. Defaults to None.

  • 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 and end are ignored.

  • show_signals (bool, optional): If set to True, displays buy/sell signals on the chart. Default is True.

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 ignores start and end 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 specified start and end dates.


Method: _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 for stock1, indicating dates, prices, and signal direction ('up' or 'down').

  • long_signals_stock2 (list): A list of tuples containing signals for stock2, indicating dates, prices, and signal direction ('up' or 'down').


Method: plot()

Generates an interactive Plotly chart that visualizes price movements, normalized prices, log return spreads, and buy/sell signals for both stocks.

Chart Features:

  1. Top pane 1: Displays the linear stock prices of stock1.

  2. Top pane 2: Displays the linear stock prices of stock2.

  3. Second pane: Displays the normalized prices of stock1 and stock2.

  4. Third pane: Displays the normalized spread between stock1 and stock2.

  5. 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:

# Create a MeanAnalyzer object for 'POOL' and 'SWK' stocks with 60-minute interval aggregation
analyzer = MeanAnalyzer('POOL', 'SWK', interval='60m', show_signals=True)

# Plot the results
analyzer.plot()
# Create a MeanAnalyzer object for 'AAPL' and 'MSFT' stocks with daily data and no signals displayed
analyzer = MeanAnalyzer('AAPL', 'MSFT', start='2022-01-01', end='2022-12-31', interval='1d', show_signals=False)

# Plot the results
analyzer.plot()

Expected Output:

A detailed interactive Plotly chart with the following elements:

  • Stock prices for both stock1 and stock2.

  • 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.

5 Pane Chart to analyze the Mean between a pair.

Customization Options:

Date Range or Time Interval:

  • You can choose between specifying a date range (using start and end) for daily data or using a time aggregation interval (e.g., '60m') to analyze intraday data.

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 and stock2 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