Computational tools¶
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 [187]: ser = Series(randn(8))
In [188]: ser.pct_change()
Out[188]:
0 NaN
1 -1.602976
2 4.334938
3 -0.247456
4 -2.067345
5 -1.142903
6 -1.688214
7 -9.759729
In [189]: df = DataFrame(randn(10, 4))
In [190]: df.pct_change(periods=3)
Out[190]:
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 [191]: s1 = Series(randn(1000))
In [192]: s2 = Series(randn(1000))
In [193]: s1.cov(s2)
Out[193]: 0.00068010881743109321
Analogously, DataFrame has a method cov to compute pairwise covariances among the series in the DataFrame, also excluding NA/null values.
In [194]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [195]: frame.cov()
Out[195]:
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
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 [196]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [197]: frame.ix[::2] = np.nan
# Series with Series
In [198]: frame['a'].corr(frame['b'])
Out[198]: 0.010052135416653445
In [199]: frame['a'].corr(frame['b'], method='spearman')
Out[199]: -0.0097383749534998149
# Pairwise correlation of DataFrame columns
In [200]: frame.corr()
Out[200]:
a b c d e
a 1.000000 0.010052 -0.047750 -0.031461 -0.025285
b 0.010052 1.000000 -0.014172 -0.020590 -0.001930
c -0.047750 -0.014172 1.000000 0.006373 -0.049479
d -0.031461 -0.020590 0.006373 1.000000 -0.012379
e -0.025285 -0.001930 -0.049479 -0.012379 1.000000
Note that non-numeric columns will be automatically excluded from the correlation calculation.
A related method corrwith is implemented on DataFrame to compute the correlation between like-labeled Series contained in different DataFrame objects.
In [201]: index = ['a', 'b', 'c', 'd', 'e']
In [202]: columns = ['one', 'two', 'three', 'four']
In [203]: df1 = DataFrame(randn(5, 4), index=index, columns=columns)
In [204]: df2 = DataFrame(randn(4, 4), index=index[:4], columns=columns)
In [205]: df1.corrwith(df2)
Out[205]:
one 0.803464
two 0.142469
three -0.498774
four 0.806420
In [206]: df2.corrwith(df1, axis=1)
Out[206]:
a 0.011572
b 0.388066
c -0.335819
d 0.232412
e NaN
Data ranking¶
The rank method produces a data ranking with ties being assigned the mean of the ranks (by default) for the group:
In [207]: s = Series(np.random.randn(5), index=list('abcde'))
In [208]: s['d'] = s['b'] # so there's a tie
In [209]: s.rank()
Out[209]:
a 2.0
b 4.5
c 3.0
d 4.5
e 1.0
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 [210]: df = DataFrame(np.random.randn(10, 6))
In [211]: df[4] = df[2][:5] # some ties
In [212]: df
Out[212]:
0 1 2 3 4 5
0 0.085011 -0.459422 -1.660917 -1.913019 -1.660917 0.833479
1 -0.557052 0.775425 0.003794 0.555351 0.003794 -1.169977
2 0.815695 -0.295737 -0.534290 0.068917 -0.534290 -0.513855
3 1.465947 0.021757 0.523224 -0.439297 0.523224 -0.959568
4 -0.678378 0.091855 1.337956 0.792551 1.337956 0.711776
5 -0.190285 0.187520 -0.355562 1.730964 NaN -1.362312
6 -0.776678 -2.082637 -0.165877 0.357163 NaN 0.631662
7 -1.295037 0.367656 -1.886797 -0.531790 NaN 1.270408
8 1.106052 0.848312 -0.613544 1.338296 NaN -1.150652
9 0.309979 1.088439 0.920366 -0.750322 NaN 1.563956
In [213]: df.rank(1)
Out[213]:
0 1 2 3 4 5
0 5 4 2.5 1 2.5 6
1 2 6 3.5 5 3.5 1
2 6 4 1.5 5 1.5 3
3 6 3 4.5 2 4.5 1
4 1 2 5.5 4 5.5 3
5 3 4 2.0 5 NaN 1
6 2 1 3.0 4 NaN 5
7 2 4 1.0 3 NaN 5
8 4 3 2.0 5 NaN 1
9 2 4 3.0 1 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
Note
These methods are significantly faster (around 10-20x) than scipy.stats.rankdata.
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 in pandas.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 |
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 :ref: frequency string <timeseries.alias> 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 [214]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [215]: ts = ts.cumsum()
In [216]: ts.plot(style='k--')
Out[216]: <matplotlib.axes.AxesSubplot at 0x11043e110>
In [217]: rolling_mean(ts, 60).plot(style='k')
Out[217]: <matplotlib.axes.AxesSubplot at 0x11043e110>
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 [218]: df = DataFrame(randn(1000, 4), index=ts.index,
.....: columns=['A', 'B', 'C', 'D'])
.....:
In [219]: df = df.cumsum()
In [220]: rolling_sum(df, 60).plot(subplots=True)
Out[220]:
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 [221]: mad = lambda x: np.fabs(x - x.mean()).mean()
In [222]: rolling_apply(ts, 60, mad).plot(style='k')
Out[222]: <matplotlib.axes.AxesSubplot at 0x11030d190>
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 [223]: df2 = df[:20]
In [224]: rolling_corr(df2, df2['B'], window=5)
Out[224]:
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.703188 1 -0.746130 0.714265
2000-01-06 0.065322 1 -0.209789 0.635360
2000-01-07 -0.429914 1 -0.100807 0.266005
2000-01-08 -0.387498 1 0.512321 0.592033
2000-01-09 0.442207 1 0.570186 -0.653242
2000-01-10 0.572983 1 0.713876 -0.366806
2000-01-11 0.325889 1 0.899489 -0.337436
2000-01-12 -0.389584 1 0.482351 0.246871
2000-01-13 -0.714206 1 -0.593838 0.090279
2000-01-14 -0.933238 1 -0.936087 0.471866
2000-01-15 -0.991959 1 -0.943218 0.637434
2000-01-16 -0.645081 1 -0.520788 0.322264
2000-01-17 -0.348338 1 -0.183528 0.385915
2000-01-18 0.193914 1 -0.308346 -0.157765
2000-01-19 0.465424 1 -0.072219 -0.714273
2000-01-20 0.645630 1 0.211302 -0.651308
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 items are the dates in question:
In [225]: correls = rolling_corr_pairwise(df, 50)
In [226]: correls[df.index[-50]]
Out[226]:
A B C D
A 1.000000 0.289597 0.673828 -0.589002
B 0.289597 1.000000 -0.041244 0.204692
C 0.673828 -0.041244 1.000000 -0.848632
D -0.589002 0.204692 -0.848632 1.000000
You can efficiently retrieve the time series of correlations between two columns using ix indexing:
In [227]: correls.ix[:, 'A', 'C'].plot()
Out[227]: <matplotlib.axes.AxesSubplot at 0x110330b10>
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 |
ewvar | EW moving variance |
ewstd | EW moving standard deviation |
ewmcorr | EW moving correlation |
ewmcov | EW moving covariance |
Here are an example for a univariate time series:
In [228]: plt.close('all')
In [229]: ts.plot(style='k--')
Out[229]: <matplotlib.axes.AxesSubplot at 0x10fd04d10>
In [230]: ewma(ts, span=20).plot(style='k')
Out[230]: <matplotlib.axes.AxesSubplot at 0x10fd04d10>
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 [231]: from pandas.io.data import DataReader
In [232]: symbols = ['MSFT', 'GOOG', 'AAPL']
In [233]: data = dict((sym, DataReader(sym, "yahoo"))
.....: for sym in symbols)
.....:
In [234]: panel = Panel(data).swapaxes('items', 'minor')
In [235]: close_px = panel['Close']
# convert closing prices to returns
In [236]: rets = close_px / close_px.shift(1) - 1
In [237]: rets.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 250 entries, 2011-11-09 00:00:00 to 2012-11-07 00:00:00
Data columns:
AAPL 249 non-null values
GOOG 249 non-null values
MSFT 249 non-null values
dtypes: float64(3)
Let’s do a static regression of AAPL returns on GOOG returns:
In [238]: model = ols(y=rets['AAPL'], x=rets.ix[:, ['GOOG']])
In [239]: model
Out[239]:
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <GOOG> + <intercept>
Number of Observations: 249
Number of Degrees of Freedom: 2
R-squared: 0.1691
Adj R-squared: 0.1658
Rmse: 0.0157
F-stat (1, 247): 50.2798, p-value: 0.0000
Degrees of Freedom: model 1, resid 247
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
GOOG 0.4791 0.0676 7.09 0.0000 0.3466 0.6115
intercept 0.0013 0.0010 1.28 0.2012 -0.0007 0.0032
---------------------------------End of Summary---------------------------------
In [240]: model.beta
Out[240]:
GOOG 0.479054
intercept 0.001278
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 [241]: model = ols(y=rets['AAPL'], x=rets.ix[:, ['GOOG']],
.....: window=250)
.....:
# just plot the coefficient for GOOG
In [242]: model.beta['GOOG'].plot()
Out[242]: <matplotlib.axes.AxesSubplot at 0x10fdb2890>
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 [243]: winz = rets.copy()
In [244]: std_1year = rolling_std(rets, 250, min_periods=20)
# cap at 3 * 1 year standard deviation
In [245]: cap_level = 3 * np.sign(winz) * std_1year
In [246]: winz[np.abs(winz) > 3 * std_1year] = cap_level
In [247]: winz_model = ols(y=winz['AAPL'], x=winz.ix[:, ['GOOG']],
.....: window=250)
.....:
In [248]: model.beta['GOOG'].plot(label="With outliers")
Out[248]: <matplotlib.axes.AxesSubplot at 0x10fd9e390>
In [249]: winz_model.beta['GOOG'].plot(label="Winsorized"); plt.legend(loc='best')
Out[249]: <matplotlib.legend.Legend at 0x111d7f590>
So in this simple example we see the impact of winsorization is actually quite significant. Note the correlation after winsorization remains high:
In [250]: winz.corrwith(rets)
Out[250]:
AAPL 0.991873
GOOG 0.984418
MSFT 0.998519
Multiple regressions can be run by passing a DataFrame with multiple columns for the predictors x:
In [251]: ols(y=winz['AAPL'], x=winz.drop(['AAPL'], axis=1))
Out[251]:
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <GOOG> + <MSFT> + <intercept>
Number of Observations: 249
Number of Degrees of Freedom: 3
R-squared: 0.2347
Adj R-squared: 0.2285
Rmse: 0.0144
F-stat (2, 246): 37.7281, p-value: 0.0000
Degrees of Freedom: model 2, resid 246
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
GOOG 0.4502 0.0712 6.32 0.0000 0.3107 0.5897
MSFT 0.2654 0.0748 3.55 0.0005 0.1188 0.4120
intercept 0.0009 0.0009 0.94 0.3482 -0.0009 0.0027
---------------------------------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 [252]: volume = panel['Volume'] / 1e8
In [253]: model = ols(y=volume, x={'return' : np.abs(rets)})
In [254]: model
Out[254]:
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <return> + <intercept>
Number of Observations: 747
Number of Degrees of Freedom: 2
R-squared: 0.0244
Adj R-squared: 0.0231
Rmse: 0.2105
F-stat (1, 745): 18.6418, p-value: 0.0000
Degrees of Freedom: model 1, resid 745
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
return 3.1731 0.7349 4.32 0.0000 1.7327 4.6136
intercept 0.1888 0.0111 16.95 0.0000 0.1670 0.2107
---------------------------------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 [255]: fe_model = ols(y=volume, x={'return' : np.abs(rets)},
.....: entity_effects=True)
.....:
In [256]: fe_model
Out[256]:
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <return> + <FE_GOOG> + <FE_MSFT> + <intercept>
Number of Observations: 747
Number of Degrees of Freedom: 4
R-squared: 0.7843
Adj R-squared: 0.7834
Rmse: 0.0991
F-stat (3, 743): 900.6175, p-value: 0.0000
Degrees of Freedom: model 3, resid 743
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
return 4.0218 0.3483 11.55 0.0000 3.3392 4.7044
FE_GOOG -0.1396 0.0089 -15.66 0.0000 -0.1571 -0.1221
FE_MSFT 0.3052 0.0089 34.16 0.0000 0.2877 0.3227
intercept 0.1244 0.0077 16.24 0.0000 0.1093 0.1394
---------------------------------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 [257]: fe_model = ols(y=volume, x={'return' : np.abs(rets)},
.....: entity_effects=True, intercept=False)
.....:
In [258]: fe_model
Out[258]:
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <return> + <FE_AAPL> + <FE_GOOG> + <FE_MSFT>
Number of Observations: 747
Number of Degrees of Freedom: 4
R-squared: 0.7843
Adj R-squared: 0.7834
Rmse: 0.0991
F-stat (4, 743): 900.6175, p-value: 0.0000
Degrees of Freedom: model 3, resid 743
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
return 4.0218 0.3483 11.55 0.0000 3.3392 4.7044
FE_AAPL 0.1244 0.0077 16.24 0.0000 0.1093 0.1394
FE_GOOG -0.0153 0.0073 -2.10 0.0358 -0.0295 -0.0010
FE_MSFT 0.4295 0.0071 60.08 0.0000 0.4155 0.4436
---------------------------------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 [259]: te_model = ols(y=volume, x={'return' : np.abs(rets)},
.....: time_effects=True, entity_effects=True)
.....:
In [260]: te_model
Out[260]:
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <return> + <FE_GOOG> + <FE_MSFT>
Number of Observations: 747
Number of Degrees of Freedom: 252
R-squared: 0.8445
Adj R-squared: 0.7656
Rmse: 0.0979
F-stat (3, 495): 10.7076, p-value: 0.0000
Degrees of Freedom: model 251, resid 495
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
return 3.4851 nan nan nan nan nan
FE_GOOG -0.1408 nan nan nan nan nan
FE_MSFT 0.3037 nan nan nan nan nan
---------------------------------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.