본문 바로가기
미래걱정/주식

S&P500 그래프와 장단기금리차의 그래프를 같이 그려보자 (with Chat gpt, ax1.twinx) - 2

by JHistory_ 2023. 1. 27.
반응형

* quandl을 통해 PER band그리는 것 해보기 전에 장단기 금리차와 S&P500의 그래프를 같이 그리는 것을 해볼 것이다. 크게 어렵지 않을 것이라 판단되어 가본다.

* 왜냐면 PER band를 그려보려면 그래프가 최소 3개 정도는 그려져야 하는데, 그 예행 공부정도라고 말할 수 있을 것 같다.


● 그래프 2개 그리기

 이게 저번 1탄에서 Chat GPT가 도시해준 마지막 코드이다. 이걸 가지고 그래프를 2개를 그려보자.

import matplotlib.pyplot as plt
from fredapi import Fred
import pandas as pd

# Initialize the FRED api
fred = Fred(api_key='your API KEY')

# Specify the series code for S&P500
series_code = 'SP500'

# Specify the start and end date for the data
start_date = '2012-01-01'
end_date = '2022-12-31'

# Fetch the data for the series
data = fred.get_series(series_code, start_date, end_date)

# Plot the chart
plt.plot(data.index, data, label='S&P500')
plt.legend()
plt.show()

이때, 10y2y에 대한 추가를 요구하면 아래와 같이 알려준다.

import matplotlib.pyplot as plt
from fredapi import Fred
import pandas as pd

# Initialize the FRED api
fred = Fred(api_key='YOUR_API_KEY')

# Specify the series code for S&P500
sp500_code = 'SP500'

# Specify the series code for 10y2y
teny2y_code = 'T10Y2Y'

# Specify the start and end date for the data
start_date = '2022-01-01'
end_date = '2022-12-31'

# Fetch the data for the series
sp500_data = fred.get_series(sp500_code, start_date, end_date)
teny2y_data = fred.get_series(teny2y_code, start_date, end_date)

# Plot the chart
plt.plot(sp500_data.index, sp500_data, label='S&P500')
plt.plot(teny2y_data.index, teny2y_data, label='10y2y')

이게 근데, plt legend랑 plot show같은게 사라졌다. 처음 코드에 10y2y를 적절하게 삽입해보자.

import matplotlib.pyplot as plt
from fredapi import Fred
import pandas as pd

# Initialize the FRED api
fred = Fred(api_key='Your API Keys')

# Specify the series code for S&P500
series_code = 'SP500'

# Specify the series code for 10y2y
teny2y_code = 'T10Y2Y'

# Specify the start and end date for the data
start_date = '2012-01-01'
end_date = '2022-12-31'

# Fetch the data for the series
data = fred.get_series(series_code, start_date, end_date)
teny2y_data = fred.get_series(teny2y_code, start_date, end_date)

# Plot the chart
plt.plot(data.index, data, label='S&P500')
plt.plot(teny2y_data.index, teny2y_data, label='10y2y')

plt.legend()
plt.show()

이렇게 코드를 넣고 RUN을 하면 아래와 같이 도시된다.

아뿔싸 ! 10y2y는 0근처에서 왔다갔다하는 금리 수준인데 S&P500과 scale이 똑같으니까 큰 의미가 없는 것 처럼 보인다. 보조축을 설정해보도록하다.

● 보조축 설정하기

chat GPT께 보조축을 어떻게 그리냐고 여쭤보았다.


I want to draw a graph with S&P500 and 10y2y. But, The code that you gave me has a same axis within 2 different value. So, I want to set the axis on the left for S&P500 and on the right for 10y2y which means that I want to set the y-axis of 10y2y for auxiliary axis. Can you fix the code please?


그랬더니 아래와 같이 코드를 주셨다.

import matplotlib.pyplot as plt
from fredapi import Fred
import pandas as pd

# Initialize the FRED api
fred = Fred(api_key='94b2c42951f77424bb93cc597be8c9f3')

# Specify the series code for S&P500
sp500_code = 'SP500'

# Specify the series code for 10y2y
teny2y_code = 'T10Y2Y'

# Specify the start and end date for the data
start_date = '2013-01-25'
end_date = '2022-12-31'

# Fetch the data for the series
sp500_data = fred.get_series(sp500_code, start_date, end_date)
teny2y_data = fred.get_series(teny2y_code, start_date, end_date)

# Plot the chart
fig, ax1 = plt.subplots()

ax1.plot(sp500_data.index, sp500_data, label='S&P500')
ax1.set_xlabel('Date')
ax1.set_ylabel('S&P500')
ax1.legend(loc="upper left")

ax2 = ax1.twinx()
ax2.plot(teny2y_data.index, teny2y_data, 'r', label='10y2y')
ax2.set_ylabel('10y2y')
ax2.legend(loc="upper right")

plt.show()

여기서 ax1.twinx가 핵심이다. 이 기능은 plt에서 ax1을 그려서 x와 y를 셋팅한 뒤, x축을 공유하는 다른 y축을 그리는 기능이라고 한다. 이걸 무지성 RUN을 해봤더니 아래와 같이 산출되었다. 

오~ 뭔가 그럴듯해 ! 그래서 2002년도로 부터 설정을 바꿨다. 근데 그랬더니 FRED의 S&P500 data가 2013년도 1월부터만 있는 것을 확인하였다.

오 마이 갓 ~ 그래서 2013년도 1월 25일 부터로 셋팅을해주었더니, 아래와 같이 셋팅되었다.

오 ~ 그렇구만 다음 시간에는 진짜 PER band 그려보도록 하겠다 ! 글 읽기가 귀찮으면 아래 영상으로 넘어와도 좋을 것 같다.

 

https://www.youtube.com/watch?v=NKJaSW6BHBA 

 

반응형

댓글