사례 연구: S&P500 가격 시뮬레이션

Python으로 시계열 데이터 다루기

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

랜덤 워크 & 시뮬레이션

  • 일별 주식 수익률은 예측하기 어렵습니다
  • 모델에서는 흔히 수익률이 무작위라고 가정합니다
  • Numpy로 난수를 생성할 수 있습니다
  • 무작위 수익률 → 가격: .cumprod() 사용
  • 두 가지 예시:
    • 무작위 수익률 생성
    • 실제 S&P500 수익률 무작위 추출
Python으로 시계열 데이터 다루기

난수 생성

from numpy.random import normal, seed

from scipy.stats import norm
seed(42)
random_returns = normal(loc=0, scale=0.01, size=1000)
sns.distplot(random_returns, fit=norm, kde=False)

ch3_3_v2 - Case Study - SP500 Simulation.011.png

Python으로 시계열 데이터 다루기

무작위 가격 경로 생성

return_series = pd.Series(random_returns)

random_prices = return_series.add(1).cumprod().sub(1)
random_prices.mul(100).plot()

ch3_3_v2 - Case Study - SP500 Simulation.013.png

Python으로 시계열 데이터 다루기

S&P 500 가격 & 수익률

data = pd.read_csv('sp500.csv', parse_dates=['date'], index_col='date')

data['returns'] = data.SP500.pct_change()
data.plot(subplots=True)

ch3_3_v2 - Case Study - SP500 Simulation.015.png

Python으로 시계열 데이터 다루기

S&P 수익률 분포

sns.distplot(data.returns.dropna().mul(100), fit=norm)

ch3_3_v2 - Case Study - SP500 Simulation.017.png

Python으로 시계열 데이터 다루기

무작위 S&P 500 수익률 생성

from numpy.random import choice

sample = data.returns.dropna()
n_obs = data.returns.count()
random_walk = choice(sample, size=n_obs)
random_walk = pd.Series(random_walk, index=sample.index)
random_walk.head()
DATE
2007-05-29   -0.008357
2007-05-30    0.003702
2007-05-31   -0.013990
2007-06-01    0.008096
2007-06-04    0.013120
Python으로 시계열 데이터 다루기

무작위 S&P 500 가격 (1)

start = data.SP500.first('D')
DATE
2007-05-25    1515.73
Name: SP500, dtype: float64
sp500_random = start.append(random_walk.add(1))

sp500_random.head())
DATE
2007-05-25    1515.730000
2007-05-29       0.998290
2007-05-30       0.995190
2007-05-31       0.997787
2007-06-01       0.983853
dtype: float64
Python으로 시계열 데이터 다루기

무작위 S&P 500 가격 (2)

data['SP500_random'] = sp500_random.cumprod()

data[['SP500', 'SP500_random']].plot()

ch3_3_v2 - Case Study - SP500 Simulation.023.png

Python으로 시계열 데이터 다루기

연습해 봅시다!

Python으로 시계열 데이터 다루기

Preparing Video For Download...