여러 종목 가져오기 및 MultiIndex 관리

Python으로 금융 데이터 가져오기와 관리

Stefan Jansen

Instructor

여러 종목 데이터 가져오기

  • 상장 정보로 여러 종목을 선택합니다
    • 예: 섹터별 시가총액 상위 3개
  • Yahoo! Finance로 여러 종목 데이터를 가져옵니다
  • 더 복잡한 데이터셋을 다루는 강력한 도구인 pandas MultiIndex를 관리하는 방법을 학습합니다
Python으로 금융 데이터 가져오기와 관리

상위 5개 기업의 가격 불러오기

nasdaq = pd.read_excel('listings.xlsx', sheet_name='nasdaq', na_values='n/a')

nasdaq.set_index('Stock Symbol', inplace=True)
top_5 = nasdaq['Market Capitalization'].nlargest(n=5) # Top 5 top_5.div(1000000) # Market Cap in million USD
AAPL     740024.467000
GOOG     569426.124504
...      ...
Name: Market Capitalization, dtype: float64
tickers = top_5.index.tolist() # Convert index to list
['AAPL', 'GOOG', 'MSFT', 'AMZN', 'FB']
Python으로 금융 데이터 가져오기와 관리

상위 5개 기업의 가격 불러오기

df = DataReader(tickers, 'yahoo', start=date(2020, 1, 1))
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 712 entries, 2020-01-02 to 2022-10-27
Data columns (total 30 columns):
 #   Column             Non-Null Count  Dtype  
 --  ------             --------------  -----  
 0   (Adj Close, AAPL)  712 non-null    float64
 1   (Adj Close, GOOG)  712 non-null    float64
 2   (Adj Close, MSFT)  712 non-null    float64
...
 28  (Volume, AMZN)     712 non-null    float64
 29  (Volume, FB)       253 non-null    float64
dtypes: float64(30)
memory usage: 172.4 KB
df = df.stack()
Python으로 금융 데이터 가져오기와 관리

상위 5개 기업의 가격 불러오기

df.info()
MultiIndex: 3101 entries, (Timestamp('2020-01-02 00:00:00'), 'AAPL') to (Timestamp('2022-10-27 00:00:00'), 'FB')
Data columns (total 6 columns):
 #   Column     Non-Null Count  Dtype  
 --  ------     --------------  -----  
 0   Adj Close  3101 non-null   float64
...
Python으로 금융 데이터 가져오기와 관리

.unstack()로 데이터 재구조화

unstacked = df['Close'].unstack()
unstacked.info()
DatetimeIndex: 712 entries, 2020-01-02 to 2022-10-27
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype  
 --  ------  --------------  -----  
 0   AAPL    712 non-null    float64
 1   GOOG    712 non-null    float64
 2   MSFT    712 non-null    float64
 3   AMZN    712 non-null    float64
 4   FB      253 non-null    float64
dtypes: float64(5)
memory usage: 33.4 KB
Python으로 금융 데이터 가져오기와 관리

롱 포맷에서 와이드 포맷으로

unstacked = df['Close'].unstack() # Results in DataFrame

언스택 다이어그램

Python으로 금융 데이터 가져오기와 관리

주가: 시각화

unstacked.plot(subplots=True)
plt.tight_layout(); plt.show()

서브플롯

Python으로 금융 데이터 가져오기와 관리

연습해 봅시다!

Python으로 금융 데이터 가져오기와 관리

Preparing Video For Download...