繁体   English   中英

Python:在数据框的多个列上使用函数

[英]Python: Using function over multiple columns of a dataframe

我敢肯定这个问题经常弹出。 但是,在经历了类似的问题之后,我没有设法得出此任务的答案。

我有一个包含多只股票的收益的数据框,将需要仅运行单变量回归来得出滚动的beta值。

Brad Solomon的ols.PandasRollingOLS对于包括窗口/滚动非常方便。 但是,我没有设法在所有股票退货列上迭代该函数。

我希望此函数循环/迭代/遍历不同股票收益的所有列。

在下面的内容中,我将使用项目描述https://pypi.org/project/pyfinance/中的代码,因为它应该有助于指出比我的项目更清楚的问题。

import numpy as np
import pandas as pd
from pyfinance import ols
from pandas_datareader import DataReader

syms = {
     'TWEXBMTH': 'usd',
     'T10Y2YM': 'term_spread',
     'PCOPPUSDM': 'copper'
     }


data = DataReader(syms.keys(), data_source='fred',
                   start='2000-01-01', end='2016-12-31')\
     .pct_change()\
     .dropna()\
     .rename(columns=syms)

y = data.pop('usd')


rolling = ols.PandasRollingOLS(y=y, x=data, window=12)

rolling.beta.head()


#DATE   term_spread copper  
#2001-01-01 0.000093    0.055448
#2001-02-01 0.000477    0.062622
#2001-03-01 0.001468    0.035703
#2001-04-01 0.001610    0.029522
#2001-05-01 0.001584    -0.044956


与其使用多元回归,我不希望该函数将每列分开并遍历整个数据框。

由于我的数据框超过50列,因此我希望避免经常编写该函数,例如以下代码(但是,会产生预期的结果):

rolling = ols.PandasRollingOLS(y=y, x=data[["term_spread"]], window=12).beta
rolling["copper"]= ols.PandasRollingOLS(y=y, x=data[["copper"]], window=12).beta["copper"]

#   term_spread copper
#DATE       
#2001-01-01 0.000258    0.055856
#2001-02-01 0.000611    0.064094
#2001-03-01 0.001700    0.047485
#2001-04-01 0.001778    0.040413
#2001-05-01 0.001353    -0.032264
#...    ... ...
#2016-08-01 -0.100839   -0.176078
#2016-09-01 -0.058668   -0.189192
#2016-10-01 -0.014763   -0.181441
#2016-11-01 0.046531    0.016082
#2016-12-01 0.060192    0.035062

我所做的尝试通常以“ SyntaxError:位置参数跟随关键字参数”结束,如下所示:

def beta(r):
    z = ols.PandasRollingOLS(y=y, x=r, window=12);
    return z

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM