Statistical functions
Percent Change
Both Series and DataFrame has a method pct_change to compute the percent change over a given number of periods (using fill_method to fill NA/null values).
In [376]: ser = Series(randn(8)) In [377]: ser.pct_change() Out[377]: 0 NaN 1 -1.602976 2 4.334938 3 -0.247456 4 -2.067345 5 -1.142903 6 -1.688214 7 -9.759729 dtype: float64
In [378]: df = DataFrame(randn(10, 4)) In [379]: df.pct_change(periods=3) Out[379]: 0 1 2 3 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 -0.218320 -1.054001 1.987147 -0.510183 4 -0.439121 -1.816454 0.649715 -4.822809 5 -0.127833 -3.042065 -5.866604 -1.776977 6 -2.596833 -1.959538 -2.111697 -3.798900 7 -0.117826 -2.169058 0.036094 -0.067696 8 2.492606 -1.357320 -1.205802 -1.558697 9 -1.012977 2.324558 -1.003744 -0.371806
Covariance
The Series object has a method cov to compute covariance between series (excluding NA/null values).
In [380]: s1 = Series(randn(1000)) In [381]: s2 = Series(randn(1000)) In [382]: s1.cov(s2) Out[382]: 0.00068010881743109321
Analogously, DataFrame has a method cov to compute pairwise covariances among the series in the DataFrame, also excluding NA/null values.
In [383]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e']) In [384]: frame.cov() Out[384]: a b c d e a 1.000882 -0.003177 -0.002698 -0.006889 0.031912 b -0.003177 1.024721 0.000191 0.009212 0.000857 c -0.002698 0.000191 0.950735 -0.031743 -0.005087 d -0.006889 0.009212 -0.031743 1.002983 -0.047952 e 0.031912 0.000857 -0.005087 -0.047952 1.042487
DataFrame.cov also supports an optional min_periods keyword that specifies the required minimum number of observations for each column pair in order to have a valid result.
In [385]: frame = DataFrame(randn(20, 3), columns=['a', 'b', 'c']) In [386]: frame.ix[:5, 'a'] = np.nan In [387]: frame.ix[5:10, 'b'] = np.nan In [388]: frame.cov() Out[388]: a b c a 1.210090 -0.430629 0.018002 b -0.430629 1.240960 0.347188 c 0.018002 0.347188 1.301149 In [389]: frame.cov(min_periods=12) Out[389]: a b c a 1.210090 NaN 0.018002 b NaN 1.240960 0.347188 c 0.018002 0.347188 1.301149
Correlation
Several methods for computing correlations are provided. Several kinds of correlation methods are provided:
Method name | Description |
---|---|
pearson (default) | Standard correlation coefficient |
kendall | Kendall Tau correlation coefficient |
spearman | Spearman rank correlation coefficient |
All of these are currently computed using pairwise complete observations.
In [390]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e']) In [391]: frame.ix[::2] = np.nan # Series with Series In [392]: frame['a'].corr(frame['b']) Out[392]: 0.013479040400098763 In [393]: frame['a'].corr(frame['b'], method='spearman') Out[393]: -0.0072898851595406388 # Pairwise correlation of DataFrame columns In [394]: frame.corr() Out[394]: a b c d e a 1.000000 0.013479 -0.049269 -0.042239 -0.028525 b 0.013479 1.000000 -0.020433 -0.011139 0.005654 c -0.049269 -0.020433 1.000000 0.018587 -0.054269 d -0.042239 -0.011139 0.018587 1.000000 -0.017060 e -0.028525 0.005654 -0.054269 -0.017060 1.000000
Note that non-numeric columns will be automatically excluded from the correlation calculation.
Like cov, corr also supports the optional min_periods keyword:
In [395]: frame = DataFrame(randn(20, 3), columns=['a', 'b', 'c']) In [396]: frame.ix[:5, 'a'] = np.nan In [397]: frame.ix[5:10, 'b'] = np.nan In [398]: frame.corr() Out[398]: a b c a 1.000000 -0.076520 0.160092 b -0.076520 1.000000 0.135967 c 0.160092 0.135967 1.000000 In [399]: frame.corr(min_periods=12) Out[399]: a b c a 1.000000 NaN 0.160092 b NaN 1.000000 0.135967 c 0.160092 0.135967 1.000000
A related method corrwith is implemented on DataFrame to compute the correlation between like-labeled Series contained in different DataFrame objects.
In [400]: index = ['a', 'b', 'c', 'd', 'e'] In [401]: columns = ['one', 'two', 'three', 'four'] In [402]: df1 = DataFrame(randn(5, 4), index=index, columns=columns) In [403]: df2 = DataFrame(randn(4, 4), index=index[:4], columns=columns) In [404]: df1.corrwith(df2) Out[404]: one -0.125501 two -0.493244 three 0.344056 four 0.004183 dtype: float64 In [405]: df2.corrwith(df1, axis=1) Out[405]: a -0.675817 b 0.458296 c 0.190809 d -0.186275 e NaN dtype: float64
Data ranking
The rank method produces a data ranking with ties being assigned the mean of the ranks (by default) for the group:
In [406]: s = Series(np.random.randn(5), index=list('abcde')) In [407]: s['d'] = s['b'] # so there's a tie In [408]: s.rank() Out[408]: a 5.0 b 2.5 c 1.0 d 2.5 e 4.0 dtype: float64
rank is also a DataFrame method and can rank either the rows (axis=0) or the columns (axis=1). NaN values are excluded from the ranking.
In [409]: df = DataFrame(np.random.randn(10, 6)) In [410]: df[4] = df[2][:5] # some ties In [411]: df Out[411]: 0 1 2 3 4 5 0 -0.904948 -1.163537 -1.457187 0.135463 -1.457187 0.294650 1 -0.976288 -0.244652 -0.748406 -0.999601 -0.748406 -0.800809 2 0.401965 1.460840 1.256057 1.308127 1.256057 0.876004 3 0.205954 0.369552 -0.669304 0.038378 -0.669304 1.140296 4 -0.477586 -0.730705 -1.129149 -0.601463 -1.129149 -0.211196 5 -1.092970 -0.689246 0.908114 0.204848 NaN 0.463347 6 0.376892 0.959292 0.095572 -0.593740 NaN -0.069180 7 -1.002601 1.957794 -0.120708 0.094214 NaN -1.467422 8 -0.547231 0.664402 -0.519424 -0.073254 NaN -1.263544 9 -0.250277 -0.237428 -1.056443 0.419477 NaN 1.375064 In [412]: df.rank(1) Out[412]: 0 1 2 3 4 5 0 4 3 1.5 5 1.5 6 1 2 6 4.5 1 4.5 3 2 1 6 3.5 5 3.5 2 3 4 5 1.5 3 1.5 6 4 5 3 1.5 4 1.5 6 5 1 2 5.0 3 NaN 4 6 4 5 3.0 1 NaN 2 7 2 5 3.0 4 NaN 1 8 2 5 3.0 4 NaN 1 9 2 3 1.0 4 NaN 5
rank optionally takes a parameter ascending which by default is true; when false, data is reverse-ranked, with larger values assigned a smaller rank.
rank supports different tie-breaking methods, specified with the method parameter:
- average : average rank of tied group
- min : lowest rank in the group
- max : highest rank in the group
- first : ranks assigned in the order they appear in the array
Moving (rolling) statistics / moments
For working with time series data, a number of functions are provided for computing common moving or rolling statistics. Among these are count, sum, mean, median, correlation, variance, covariance, standard deviation, skewness, and kurtosis. All of these methods are in the pandas namespace, but otherwise they can be found inpandas.stats.moments.
Function | Description |
---|---|
rolling_count | Number of non-null observations |
rolling_sum | Sum of values |
rolling_mean | Mean of values |
rolling_median | Arithmetic median of values |
rolling_min | Minimum |
rolling_max | Maximum |
rolling_std | Unbiased standard deviation |
rolling_var | Unbiased variance |
rolling_skew | Unbiased skewness (3rd moment) |
rolling_kurt | Unbiased kurtosis (4th moment) |
rolling_quantile | Sample quantile (value at %) |
rolling_apply | Generic apply |
rolling_cov | Unbiased covariance (binary) |
rolling_corr | Correlation (binary) |
rolling_corr_pairwise | Pairwise correlation of DataFrame columns |
rolling_window | Moving window function |
Generally these methods all have the same interface. The binary operators (e.g.rolling_corr) take two Series or DataFrames. Otherwise, they all accept the following arguments:
- window: size of moving window
- min_periods: threshold of non-null data points to require (otherwise result is NA)
- freq: optionally specify a frequency string or DateOffset to pre-conform the data to. Note that prior to pandas v0.8.0, a keyword argument time_rule was used instead of freq that referred to the legacy time rule constants
These functions can be applied to ndarrays or Series objects:
In [413]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000)) In [414]: ts = ts.cumsum() In [415]: ts.plot(style='k--') Out[415]: <matplotlib.axes.AxesSubplot at 0x69342d0> In [416]: rolling_mean(ts, 60).plot(style='k') Out[416]: <matplotlib.axes.AxesSubplot at 0x69342d0>
They can also be applied to DataFrame objects. This is really just syntactic sugar for applying the moving window operator to all of the DataFrame’s columns:
In [417]: df = DataFrame(randn(1000, 4), index=ts.index, .....: columns=['A', 'B', 'C', 'D']) .....: In [418]: df = df.cumsum() In [419]: rolling_sum(df, 60).plot(subplots=True) Out[419]: array([Axes(0.125,0.747826;0.775x0.152174), Axes(0.125,0.565217;0.775x0.152174), Axes(0.125,0.382609;0.775x0.152174), Axes(0.125,0.2;0.775x0.152174)], dtype=object)
The rolling_apply function takes an extra func argument and performs generic rolling computations. The func argument should be a single function that produces a single value from an ndarray input. Suppose we wanted to compute the mean absolute deviation on a rolling basis:
In [420]: mad = lambda x: np.fabs(x - x.mean()).mean() In [421]: rolling_apply(ts, 60, mad).plot(style='k') Out[421]: <matplotlib.axes.AxesSubplot at 0x74e1f90>
The rolling_window function performs a generic rolling window computation on the input data. The weights used in the window are specified by the win_type keyword. The list of recognized types are:
- boxcar
- triang
- blackman
- hamming
- bartlett
- parzen
- bohman
- blackmanharris
- nuttall
- barthann
- kaiser (needs beta)
- gaussian (needs std)
- general_gaussian (needs power, width)
- slepian (needs width).
In [422]: ser = Series(randn(10), index=date_range('1/1/2000', periods=10)) In [423]: rolling_window(ser, 5, 'triang') Out[423]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 NaN 2000-01-04 NaN 2000-01-05 -0.622722 2000-01-06 -0.460623 2000-01-07 -0.229918 2000-01-08 -0.237308 2000-01-09 -0.335064 2000-01-10 -0.403449 Freq: D, dtype: float64
Note that the boxcar window is equivalent to rolling_mean:
In [424]: rolling_window(ser, 5, 'boxcar') Out[424]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 NaN 2000-01-04 NaN 2000-01-05 -0.841164 2000-01-06 -0.779948 2000-01-07 -0.565487 2000-01-08 -0.502815 2000-01-09 -0.553755 2000-01-10 -0.472211 Freq: D, dtype: float64 In [425]: rolling_mean(ser, 5) Out[425]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 NaN 2000-01-04 NaN 2000-01-05 -0.841164 2000-01-06 -0.779948 2000-01-07 -0.565487 2000-01-08 -0.502815 2000-01-09 -0.553755 2000-01-10 -0.472211 Freq: D, dtype: float64
For some windowing functions, additional parameters must be specified:
In [426]: rolling_window(ser, 5, 'gaussian', std=0.1) Out[426]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 NaN 2000-01-04 NaN 2000-01-05 -0.261998 2000-01-06 -0.230600 2000-01-07 0.121276 2000-01-08 -0.136220 2000-01-09 -0.057945 2000-01-10 -0.199326 Freq: D, dtype: float64
By default the labels are set to the right edge of the window, but a center keyword is available so the labels can be set at the center. This keyword is available in other rolling functions as well.
In [427]: rolling_window(ser, 5, 'boxcar') Out[427]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 NaN 2000-01-04 NaN 2000-01-05 -0.841164 2000-01-06 -0.779948 2000-01-07 -0.565487 2000-01-08 -0.502815 2000-01-09 -0.553755 2000-01-10 -0.472211 Freq: D, dtype: float64 In [428]: rolling_window(ser, 5, 'boxcar', center=True) Out[428]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 -0.841164 2000-01-04 -0.779948 2000-01-05 -0.565487 2000-01-06 -0.502815 2000-01-07 -0.553755 2000-01-08 -0.472211 2000-01-09 NaN 2000-01-10 NaN Freq: D, dtype: float64 In [429]: rolling_mean(ser, 5, center=True) Out[429]: 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 -0.841164 2000-01-04 -0.779948 2000-01-05 -0.565487 2000-01-06 -0.502815 2000-01-07 -0.553755 2000-01-08 -0.472211 2000-01-09 NaN 2000-01-10 NaN Freq: D, dtype: float64
Binary rolling moments
rolling_cov and rolling_corr can compute moving window statistics about two Series or any combination of DataFrame/Series or DataFrame/DataFrame. Here is the behavior in each case:
- two Series: compute the statistic for the pairing
- DataFrame/Series: compute the statistics for each column of the DataFrame with the passed Series, thus returning a DataFrame
- DataFrame/DataFrame: compute statistic for matching column names, returning a DataFrame
For example:
In [430]: df2 = df[:20] In [431]: rolling_corr(df2, df2['B'], window=5) Out[431]: A B C D 2000-01-01 NaN NaN NaN NaN 2000-01-02 NaN NaN NaN NaN 2000-01-03 NaN NaN NaN NaN 2000-01-04 NaN NaN NaN NaN 2000-01-05 -0.262853 1 0.334449 0.193380 2000-01-06 -0.083745 1 -0.521587 -0.556126 2000-01-07 -0.292940 1 -0.658532 -0.458128 2000-01-08 0.840416 1 0.796505 -0.498672 2000-01-09 -0.135275 1 0.753895 -0.634445 2000-01-10 -0.346229 1 -0.682232 -0.645681 2000-01-11 -0.365524 1 -0.775831 -0.561991 2000-01-12 -0.204761 1 -0.855874 -0.382232 2000-01-13 0.575218 1 -0.747531 0.167892 2000-01-14 0.519499 1 -0.687277 0.192822 2000-01-15 0.048982 1 0.167669 -0.061463 2000-01-16 0.217190 1 0.167564 -0.326034 2000-01-17 0.641180 1 -0.164780 -0.111487 2000-01-18 0.130422 1 0.322833 0.632383 2000-01-19 0.317278 1 0.384528 0.813656 2000-01-20 0.293598 1 0.159538 0.742381
Computing rolling pairwise correlations
In financial data analysis and other fields it’s common to compute correlation matrices for a collection of time series. More difficult is to compute a moving-window correlation matrix. This can be done using the rolling_corr_pairwise function, which yields a Panel whose itemsare the dates in question:
In [432]: correls = rolling_corr_pairwise(df, 50) In [433]: correls[df.index[-50]] Out[433]: A B C D A 1.000000 0.604221 0.767429 -0.776170 B 0.604221 1.000000 0.461484 -0.381148 C 0.767429 0.461484 1.000000 -0.748863 D -0.776170 -0.381148 -0.748863 1.000000
You can efficiently retrieve the time series of correlations between two columns using ixindexing:
In [434]: correls.ix[:, 'A', 'C'].plot() Out[434]: <matplotlib.axes.AxesSubplot at 0x79e4e10>
Expanding window moment functions
A common alternative to rolling statistics is to use an expanding window, which yields the value of the statistic with all the data available up to that point in time. As these calculations are a special case of rolling statistics, they are implemented in pandas such that the following two calls are equivalent:
In [435]: rolling_mean(df, window=len(df), min_periods=1)[:5] Out[435]: A B C D 2000-01-01 -1.388345 3.317290 0.344542 -0.036968 2000-01-02 -1.123132 3.622300 1.675867 0.595300 2000-01-03 -0.628502 3.626503 2.455240 1.060158 2000-01-04 -0.768740 3.888917 2.451354 1.281874 2000-01-05 -0.824034 4.108035 2.556112 1.140723 In [436]: expanding_mean(df)[:5] Out[436]: A B C D 2000-01-01 -1.388345 3.317290 0.344542 -0.036968 2000-01-02 -1.123132 3.622300 1.675867 0.595300 2000-01-03 -0.628502 3.626503 2.455240 1.060158 2000-01-04 -0.768740 3.888917 2.451354 1.281874 2000-01-05 -0.824034 4.108035 2.556112 1.140723
Like the rolling_ functions, the following methods are included in the pandas namespace or can be located in pandas.stats.moments.
Function | Description |
---|---|
expanding_count | Number of non-null observations |
expanding_sum | Sum of values |
expanding_mean | Mean of values |
expanding_median | Arithmetic median of values |
expanding_min | Minimum |
expanding_max | Maximum |
expanding_std | Unbiased standard deviation |
expanding_var | Unbiased variance |
expanding_skew | Unbiased skewness (3rd moment) |
expanding_kurt | Unbiased kurtosis (4th moment) |
expanding_quantile | Sample quantile (value at %) |
expanding_apply | Generic apply |
expanding_cov | Unbiased covariance (binary) |
expanding_corr | Correlation (binary) |
expanding_corr_pairwise | Pairwise correlation of DataFrame columns |
Aside from not having a window parameter, these functions have the same interfaces as theirrolling_ counterpart. Like above, the parameters they all accept are:
- min_periods: threshold of non-null data points to require. Defaults to minimum needed to compute statistic. No NaNs will be output once min_periods non-null data points have been seen.
- freq: optionally specify a frequency string or DateOffset to pre-conform the data to. Note that prior to pandas v0.8.0, a keyword argument time_rule was used instead of freq that referred to the legacy time rule constants
Note
The output of the rolling_ and expanding_ functions do not return a NaN if there are at least min_periods non-null values in the current window. This differs from cumsum, cumprod,cummax, and cummin, which return NaN in the output wherever a NaN is encountered in the input.
An expanding window statistic will be more stable (and less responsive) than its rolling window counterpart as the increasing window size decreases the relative impact of an individual data point. As an example, here is the expanding_mean output for the previous time series dataset:
In [437]: ts.plot(style='k--') Out[437]: <matplotlib.axes.AxesSubplot at 0x7e2b410> In [438]: expanding_mean(ts).plot(style='k') Out[438]: <matplotlib.axes.AxesSubplot at 0x7e2b410>
Exponentially weighted moment functions
A related set of functions are exponentially weighted versions of many of the above statistics. A number of EW (exponentially weighted) functions are provided using the blending method. For example, where is the result and
the input, we compute an exponentially weighted moving average as
One must have , but rather than pass
directly, it’s easier to think about either the span or center of mass (com) of an EW moment:
You can pass one or the other to these functions but not both. Span corresponds to what is commonly called a “20-day EW moving average” for example. Center of mass has a more physical interpretation. For example, span = 20 corresponds to com = 9.5. Here is the list of functions available:
Function | Description |
---|---|
ewma | EW moving average |
ewmvar | EW moving variance |
ewmstd | EW moving standard deviation |
ewmcorr | EW moving correlation |
ewmcov | EW moving covariance |
Here are an example for a univariate time series:
In [439]: plt.close('all') In [440]: ts.plot(style='k--') Out[440]: <matplotlib.axes.AxesSubplot at 0x87c9f90> In [441]: ewma(ts, span=20).plot(style='k') Out[441]: <matplotlib.axes.AxesSubplot at 0x87c9f90>
Note
The EW functions perform a standard adjustment to the initial observations whereby if there are fewer observations than called for in the span, those observations are reweighted accordingly.
Linear and panel regression
Note
We plan to move this functionality to statsmodels for the next release. Some of the result attributes may change names in order to foster naming consistency with the rest of statsmodels. We will provide every effort to provide compatibility with older versions of pandas, however.
We have implemented a very fast set of moving-window linear regression classes in pandas. Two different types of regressions are supported:
- Standard ordinary least squares (OLS) multiple regression
- Multiple regression (OLS-based) on panel data including with fixed-effects (also known as entity or individual effects) or time-effects.
Both kinds of linear models are accessed through the ols function in the pandas namespace. They all take the following arguments to specify either a static (full sample) or dynamic (moving window) regression:
- window_type: 'full sample' (default), 'expanding', or rolling
- window: size of the moving window in the window_type='rolling' case. If window is specified, window_type will be automatically set to 'rolling'
- min_periods: minimum number of time periods to require to compute the regression coefficients
Generally speaking, the ols works by being given a y (response) object and an x (predictors) object. These can take many forms:
- y: a Series, ndarray, or DataFrame (panel model)
- x: Series, DataFrame, dict of Series, dict of DataFrame or Panel
Based on the types of y and x, the model will be inferred to either a panel model or a regular linear model. If the y variable is a DataFrame, the result will be a panel model. In this case, the x variable must either be a Panel, or a dict of DataFrame (which will be coerced into a Panel).
Standard OLS regression
Let’s pull in some sample data:
In [442]: from pandas.io.data import DataReader In [443]: symbols = ['MSFT', 'GOOG', 'AAPL'] In [444]: data = dict((sym, DataReader(sym, "yahoo")) .....: for sym in symbols) .....: In [445]: panel = Panel(data).swapaxes('items', 'minor') In [446]: close_px = panel['Close'] # convert closing prices to returns In [447]: rets = close_px / close_px.shift(1) - 1 In [448]: rets.info() <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 810 entries, 2010-01-04 00:00:00 to 2013-03-22 00:00:00 Data columns (total 3 columns): AAPL 809 non-null values GOOG 809 non-null values MSFT 809 non-null values dtypes: float64(3)
Let’s do a static regression of AAPL returns on GOOG returns:
In [449]: model = ols(y=rets['AAPL'], x=rets.ix[:, ['GOOG']]) In [450]: model Out[450]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <GOOG> + <intercept> Number of Observations: 809 Number of Degrees of Freedom: 2 R-squared: 0.2394 Adj R-squared: 0.2385 Rmse: 0.0156 F-stat (1, 807): 253.9945, p-value: 0.0000 Degrees of Freedom: model 1, resid 807 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- GOOG 0.5262 0.0330 15.94 0.0000 0.4615 0.5909 intercept 0.0009 0.0006 1.58 0.1134 -0.0002 0.0020 ---------------------------------End of Summary--------------------------------- In [451]: model.beta Out[451]: GOOG 0.526216 intercept 0.000872 dtype: float64
If we had passed a Series instead of a DataFrame with the single GOOG column, the model would have assigned the generic name x to the sole right-hand side variable.
We can do a moving window regression to see how the relationship changes over time:
In [452]: model = ols(y=rets['AAPL'], x=rets.ix[:, ['GOOG']], .....: window=250) .....: # just plot the coefficient for GOOG In [453]: model.beta['GOOG'].plot() Out[453]: <matplotlib.axes.AxesSubplot at 0x8d9e650>
It looks like there are some outliers rolling in and out of the window in the above regression, influencing the results. We could perform a simple winsorization at the 3 STD level to trim the impact of outliers:
In [454]: winz = rets.copy() In [455]: std_1year = rolling_std(rets, 250, min_periods=20) # cap at 3 * 1 year standard deviation In [456]: cap_level = 3 * np.sign(winz) * std_1year In [457]: winz[np.abs(winz) > 3 * std_1year] = cap_level In [458]: winz_model = ols(y=winz['AAPL'], x=winz.ix[:, ['GOOG']], .....: window=250) .....: In [459]: model.beta['GOOG'].plot(label="With outliers") Out[459]: <matplotlib.axes.AxesSubplot at 0x8db0750> In [460]: winz_model.beta['GOOG'].plot(label="Winsorized"); plt.legend(loc='best') Out[460]: <matplotlib.legend.Legend at 0x9a4e710>
So in this simple example we see the impact of winsorization is actually quite significant. Note the correlation after winsorization remains high:
In [461]: winz.corrwith(rets) Out[461]: AAPL 0.988561 GOOG 0.973117 MSFT 0.998421 dtype: float64
Multiple regressions can be run by passing a DataFrame with multiple columns for the predictors x:
In [462]: ols(y=winz['AAPL'], x=winz.drop(['AAPL'], axis=1)) Out[462]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <GOOG> + <MSFT> + <intercept> Number of Observations: 809 Number of Degrees of Freedom: 3 R-squared: 0.3283 Adj R-squared: 0.3266 Rmse: 0.0139 F-stat (2, 806): 196.9405, p-value: 0.0000 Degrees of Freedom: model 2, resid 806 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- GOOG 0.4579 0.0382 12.00 0.0000 0.3831 0.5327 MSFT 0.3090 0.0424 7.28 0.0000 0.2258 0.3921 intercept 0.0009 0.0005 1.84 0.0663 -0.0001 0.0019 ---------------------------------End of Summary---------------------------------
Panel regression
We’ve implemented moving window panel regression on potentially unbalanced panel data (see this article if this means nothing to you). Suppose we wanted to model the relationship between the magnitude of the daily return and trading volume among a group of stocks, and we want to pool all the data together to run one big regression. This is actually quite easy:
# make the units somewhat comparable In [463]: volume = panel['Volume'] / 1e8 In [464]: model = ols(y=volume, x={'return' : np.abs(rets)}) In [465]: model Out[465]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <return> + <intercept> Number of Observations: 2427 Number of Degrees of Freedom: 2 R-squared: 0.0193 Adj R-squared: 0.0188 Rmse: 0.2648 F-stat (1, 2425): 47.6083, p-value: 0.0000 Degrees of Freedom: model 1, resid 2425 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- return 3.2605 0.4725 6.90 0.0000 2.3343 4.1866 intercept 0.2248 0.0077 29.37 0.0000 0.2098 0.2398 ---------------------------------End of Summary---------------------------------
In a panel model, we can insert dummy (0-1) variables for the “entities” involved (here, each of the stocks) to account the a entity-specific effect (intercept):
In [466]: fe_model = ols(y=volume, x={'return' : np.abs(rets)}, .....: entity_effects=True) .....: In [467]: fe_model Out[467]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <return> + <FE_GOOG> + <FE_MSFT> + <intercept> Number of Observations: 2427 Number of Degrees of Freedom: 4 R-squared: 0.7400 Adj R-squared: 0.7397 Rmse: 0.1364 F-stat (3, 2423): 2298.9069, p-value: 0.0000 Degrees of Freedom: model 3, resid 2423 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- return 4.4246 0.2447 18.08 0.0000 3.9449 4.9043 FE_GOOG -0.1554 0.0068 -22.87 0.0000 -0.1687 -0.1421 FE_MSFT 0.3852 0.0068 56.52 0.0000 0.3719 0.3986 intercept 0.1348 0.0058 23.36 0.0000 0.1235 0.1461 ---------------------------------End of Summary---------------------------------
Because we ran the regression with an intercept, one of the dummy variables must be dropped or the design matrix will not be full rank. If we do not use an intercept, all of the dummy variables will be included:
In [468]: fe_model = ols(y=volume, x={'return' : np.abs(rets)}, .....: entity_effects=True, intercept=False) .....: In [469]: fe_model Out[469]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <return> + <FE_AAPL> + <FE_GOOG> + <FE_MSFT> Number of Observations: 2427 Number of Degrees of Freedom: 4 R-squared: 0.7400 Adj R-squared: 0.7397 Rmse: 0.1364 F-stat (4, 2423): 2298.9069, p-value: 0.0000 Degrees of Freedom: model 3, resid 2423 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- return 4.4246 0.2447 18.08 0.0000 3.9449 4.9043 FE_AAPL 0.1348 0.0058 23.36 0.0000 0.1235 0.1461 FE_GOOG -0.0206 0.0055 -3.73 0.0002 -0.0315 -0.0098 FE_MSFT 0.5200 0.0054 96.10 0.0000 0.5094 0.5306 ---------------------------------End of Summary---------------------------------
We can also include time effects, which demeans the data cross-sectionally at each point in time (equivalent to including dummy variables for each date). More mathematical care must be taken to properly compute the standard errors in this case:
In [470]: te_model = ols(y=volume, x={'return' : np.abs(rets)}, .....: time_effects=True, entity_effects=True) .....: In [471]: te_model Out[471]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <return> + <FE_GOOG> + <FE_MSFT> Number of Observations: 2427 Number of Degrees of Freedom: 812 R-squared: 0.8166 Adj R-squared: 0.7244 Rmse: 0.1313 F-stat (3, 1615): 8.8641, p-value: 0.0000 Degrees of Freedom: model 811, resid 1615 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- return 3.5003 0.3480 10.06 0.0000 2.8182 4.1824 FE_GOOG -0.1571 0.0066 -23.95 0.0000 -0.1700 -0.1442 FE_MSFT 0.3826 0.0066 57.94 0.0000 0.3697 0.3956 ---------------------------------End of Summary---------------------------------
Here the intercept (the mean term) is dropped by default because it will be 0 according to the model assumptions, having subtracted off the group means.
Result fields and tests
We’ll leave it to the user to explore the docstrings and source, especially as we’ll be moving this code into statsmodels in the near future.
http://pandas.pydata.org/pandas-docs/dev/computation.html