1

The task is to use customized functions (panel_garch1) with Pandas 'rolling apply', it uses another package called 'arch', which is used to forecast volatilities, firstly let's get some data:

import numpy as np
from arch.univariate import GARCH, EGARCH, ConstantMean, Normal
import pandas as pd
from pandas.io.data import DataReader

aapl = DataReader('AAPL',  'yahoo', datetime(2006,1,1), datetime(2016,3,10))
returns = pd.DataFrame(np.diff(np.log(aapl['Adj Close'].values)))
returns.index = aapl.index.values[1:aapl.index.values.shape[0]]
returns.columns = ['AAPL Returns']

return data looks like this

2006-01-04  0.002939
2006-01-05  -0.007901
2006-01-06  0.025486
2006-01-09  -0.003282
2006-01-10  0.061328
2006-01-11  0.036906
2006-01-12  0.004638
2006-01-13  0.015305
2006-01-17  -0.010335
2006-01-18  -0.026557
2006-01-19  -0.042723

A simple function 'compute_mean' works pretty well

def compute_mean(ret):
    return np.mean(ret)
returns.rolling(center=False, window=12).apply(compute_mean)

Now I want to use this function below

def panel_garch1(df_ret):
    ret = df_ret
    am = ConstantMean(ret)
    am.volatility = EGARCH(1, 0, 1)
    am.distribution = Normal()
    cond_vol = am.fit(update_freq=0, disp='off').conditional_volatility
    return cond_vol

It works fine if I just use it alone, returns can be either dataframe or numpy array

panel_garch1(returns)

Then if I try to apply it to rolling window, it wouldn't work

returns.rolling(center=False, window=12).apply(panel_garch1)

or

pd.rolling_apply(returns, 12, lambda x: panel_garch1(x))

Pandas will complain

TypeError: only length-1 arrays can be converted to Python scalars

What's the problem here? I've already read something on stackoverflow, like here, but the answers to those questions do not apply to this case. Thank you very much!

Community
  • 1
  • 1
GrumpyJun
  • 53
  • 2
  • 6
  • `cond_vol` has to be either a scalar or an array with length 1. Apparently `panel_garch1` sometimes returns vectors. – cel Oct 05 '16 at 03:59
  • I see, now I figured out the problem, thank you @cel – GrumpyJun Oct 05 '16 at 04:23
  • 1
    How did you solve this problem @apt142857, I am having a similar question with pd.rolling – Bobe Kryant Dec 05 '16 at 05:04
  • 2
    @BobeKryant, the function in apply() must return a scalar, otherwise you are trying to pass a column to an element in one column, i.e. in the end of panel_garch1, return cond_vol[-1] – GrumpyJun Dec 06 '16 at 05:45

0 Answers0