単純線形回帰

Pythonで学ぶ時系列解析

Rob Reider

Adjunct Professor, NYU-Courant Consultant, Quantopian

回帰とは?

  • 単純線形回帰

$\ \ \ \ y_t = \alpha + \beta x_t + \epsilon_t$

Pythonで学ぶ時系列解析

回帰とは?

  • 最小二乗法(OLS)
Pythonで学ぶ時系列解析

回帰に使用するPythonパッケージ

  • statsmodelsの場合:
    import statsmodels.api as sm
    sm.OLS(y, x).fit()
    
  • numpyの場合:
    np.polyfit(x, y, deg=1)
    
  • pandasの場合:
    pd.ols(y, x)
    
  • scipyの場合:
    from scipy import stats
    stats.linregress(x, y)
    

注意:xy の順序はパッケージによって異なります

Pythonで学ぶ時系列解析

例:大型株リターンに対する小型株リターンの回帰

  • statsmodelsモジュールをインポートする
    import statsmodels.api as sm
    
  • 両系列の変化率を計算する
    df['SPX_Ret'] = df['SPX_Prices'].pct_change()
    df['R2000_Ret'] = df['R2000_Prices'].pct_change()
    
  • 回帰の切片用に定数をDataFrameに追加する
    df = sm.add_constant(df)
    
Pythonで学ぶ時系列解析

回帰の例(続き)

  • 最初の行のリターンがNaNであることに注意
                SPX_Price  R2000_Price   SPX_Ret  R2000_Ret
    Date                                                     
    2012-11-01  1427.589966   827.849976       NaN        NaN
    2012-11-02  1414.199951   814.369995 -0.009379  -0.016283
    
  • NaNの行を削除する
      df = df.dropna()
    
  • 回帰を実行する
      results = sm.OLS(df['R2000_Ret'],df[['const','SPX_Ret']]).fit()
      print(results.summary())
    
Pythonで学ぶ時系列解析

回帰の例(続き)

  • 回帰の出力

  • 切片は results.params[0]
  • 傾きは results.params[1]
Pythonで学ぶ時系列解析

回帰の例(続き)

  • 回帰の出力

Pythonで学ぶ時系列解析

R二乗と相関係数の関係

  • $ [\text{corr} (x,y)]^2 = R^2$(決定係数)
  • $ \text{sign(corr)} = \text{sign(regression slope)}$
  • 前の例では:
    • R二乗 = 0.753
    • 傾きは正
    • 相関係数 = $ + \sqrt{0.753} = 0.868$
Pythonで学ぶ時系列解析

練習しましょう!

Pythonで学ぶ時系列解析

Preparing Video For Download...