[Python] How do I highlight the VIX plot above 30 level with red color?

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I want to highlight the parts of a VIX plot where the index exceeds 30 points in red.

    The following example code is as below:

    import yfinance as yf
    import matplotlib.pyplot as plt

    # Fetch VIX data
    vix_data = yf.download('^VIX', start='2020-01-01', end='2024-12-31')

    # Extract the dates and VIX closing values
    dates = vix_data.index
    vix_close = vix_data['Close']

    # Plot the VIX data
    plt.figure(figsize=(12, 6))
    plt.plot(dates, vix_close, label='VIX Close', color='blue', linewidth=1.5)

    # Highlight regions where VIX is above 30
    # TODO
    plt.fill_between(dates, vix_close, 30, where=(vix_close > 30), color='red', alpha=0.5, label='Above 30')

    # Add threshold lines
    plt.axhline(y=30, color='red', linestyle='--', label='Threshold (30 pts)')
    plt.axhline(y=20, color='orange', linestyle='--', label='Threshold (20 pts)')

    # Add labels and title
    plt.title('VIX Index with Highlights Above 30', fontsize=16)
    plt.xlabel('Date', fontsize=12)
    plt.ylabel('VIX Level', fontsize=12)
    plt.legend(fontsize=10)
    plt.grid(True)

    # Show the plot
    plt.show()


    My code could not pass beyond the fill_between function, so I marked it with TODO.

    I am new to matplotlib. Could you advise how I might be able to fix this Python code?

    My tools list used as below:

    matplotlib 3.10.0rc1
    yfinance 0.2.50


    My code break-up below these lines:

    File "C:...\venv\Lib\site-packages\matplotlib\axes\_axes.py", line 5626, in fill_between
    return self._fill_between_x_or_y(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:...\venv\Lib\site-packages\matplotlib\axes\_axes.py", line 5611, in _fill_between_x_or_y
    collection = mcoll.FillBetweenPolyCollection(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    Continue reading...

Compartilhe esta Página