Эта программа использует matplotlib для отображения исторических цен закрытия S&P 500 на одной оси Y и цен Russell 2000 на второй оси Y. Время - это ось X (конечно). Видео с используемой здесь программой: https://youtu.be/GX78vg6XbKc У меня тоже есть данные для истории кривой доходности, и если я прокомментирую одну из этих строк, я могу отобразить либо или. Вторичная ось Y зависит от того, какая линия у меня активна. Как переключаться вперед и назад с помощью переключателей?
plt.plot(rus_df['Date'], rus_df['Close'], color='blue', label=symbol2)
# OR
plt.plot(inv_yld_crv_df['Date'], inv_yld_crv_df['Diff_10Y_Minus_3M'], color='blue', label=inv_yld_crv_symbol)
Я добавил переключатели для выбора данных Russell 2000 и инвертированной кривой доходности. Когда я нажимаю Russell 2000, я хочу, чтобы отображались данные Russell 2000 и то же самое для выбора данных кривой доходности. Есть идеи?
from datetime import date
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
import pandas as pd
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
def choose_axis(event):
if event == "Russell 2000":
print(event)
return "Russell 2000"
else:
print(event)
"Inverted Yield Curve"
def compare_indices():
today = str(date.today())
symbol1 = '^GSPC'
spfile = "C:/Users/Notebook/Desktop/Data/S&P 500 " + today + ".csv"
sp_df = pd.read_csv(spfile)
sp_df['Date'] = pd.to_datetime(sp_df['Date'])
sp_df = sp_df.sort_values('Date', ascending=True)
symbol2 = '^RUT'
russfile = "C:/Users/Notebook/Desktop/Data/Russell 2000 " + today + ".csv"
rus_df = pd.read_csv(russfile)
rus_df['Date'] = pd.to_datetime(rus_df['Date'])
rus_df = rus_df.sort_values('Date', ascending=True)
inv_yld_crv_symbol = "Inverted Yield Curve"
iyc_file = "C:/Users/Notebook/Desktop/Data/Treasury Yield Curve " + today + ".csv"
inv_yld_crv_df = pd.read_csv(iyc_file)
inv_yld_crv_df['Date'] = pd.to_datetime(inv_yld_crv_df['Date'])
inv_yld_crv_df = inv_yld_crv_df.sort_values('Date', ascending=True)
inv_yld_crv_df['Diff_10Y_Minus_3M'] = inv_yld_crv_df['10 YR'] - inv_yld_crv_df['3 MO']
start_date = '1990-01-01'
end_date = '2022-01-01'
sp_df = sp_df[(sp_df['Date'] >= start_date) & (sp_df['Date'] < end_date)]
# rus_df = rus_df[(rus_df['Date'] >= start_date) & (rus_df['Date'] < end_date)]
fig, ax = plt.subplots(figsize=(14, 6))
# plt.title(symbol1 + ' & ' + inv_yld_crv_symbol)
# Adjusts plot to allow room for radio buttons
plt.subplots_adjust(left=0.21)
# Radio button information
selector_color = "lightgoldenrodyellow"
selector_ax = plt.axes([0.02, 0.7, 0.15, 0.15], facecolor=selector_color)
labels = {"Russell 2000", "Yield Curve"}
y_axis_selector = RadioButtons(selector_ax, labels)
ax.plot(sp_df['Date'], sp_df['Close'], color='red', label=symbol1)
plt.grid()
ax.legend(loc='lower right')
ax2 = ax.twinx()
# Draws Horizontal Line
plt.axhline(0, color='orange')
# NEED HELP HERE!
get_event = y_axis_selector.on_clicked(choose_axis)
# This plots the Russell 2000
plt.plot(rus_df['Date'], rus_df['Close'], color='blue', label=symbol2)
# This plots the Inverted Yield Curve
# plt.plot(inv_yld_crv_df['Date'], inv_yld_crv_df['Diff_10Y_Minus_3M'], color='blue', label=inv_yld_crv_symbol)
ax2.legend(loc='upper left')
# Needed for IDEs, not needed for local host (i.e., Jupyter Notebook)
plt.show()
compare_indices()