Search code examples
pythonpandasfunctiondataframefinance

Python: Is there a way to apply a function separately on all columns of a dataframe specified in a list? Pyfinance package


I would appreciate, if someone could give a me good answer, as I am not moving forward currently. Neither any resources helped my and my tries to create a loop failed.

I have a big dataframe of stock returns, I tried to create a test dataset of it below. The used function to derive rolling betas on the stock (vs. market) returns works well. However, I don't manage to create a function to apply it on all/selected columns separately.

I would be interested in two solutions:

i) which helps me to apply/loop the ols.PandasRollingOLS function to each column of the dataframe seperately

ii) and the other to solely run the ols.PandasRollingOLS function seperately over columns specified in a list

import pandas as pd

# intialise data 
data = {'Market':[0.03, -0.01, 0.01, -0.01],
        'Stock1':[0.01, -0.02, 0.03, -0.02],
        'Stock2':[0.01, -0.011, 0.01, -0.011],
        'Stock3':[0.01, -0.011, 0.01, -0.011], 
        'Stock4':[0.02, -0.1, 0.02, 0.09],
        'Stock5':[-0.01, 0.01, 0.01, 0.005]}

list_stocks = ["Stock1", "Stocks2", "Stock3"]

# Create DataFrame
df = pd.DataFrame(data)


The following code yields the right results, but given the size of the dataframe I cannot work with this solution for the dataset:


#!pip3 install pyfinance
from pyfinance import ols

y=df["Market"]
w = 2 
roll_beta["Stock1"] = ols.PandasRollingOLS(y=y, x=df[["Stock1"]], window=w).beta["Stock1"]
roll_beta["Stock2"] = ols.PandasRollingOLS(y=y, x=df[["Stock2"]], window=w).beta["Stock2"]
roll_beta["Stock3"] = ols.PandasRollingOLS(y=y, x=df[["Stock3"]], window=w).beta["Stock3"]


print(roll_beta)
$     Stock1    Stock2    Stock3
1  1.333333  1.904762  1.904762
2  0.400000  0.952381  0.952381
3  0.400000  0.952381  0.952381


Solution

  • You said you'd tried a loop but not what the issue was. Here's a simple loop based on your example - does this work for you?

    from pyfinance import ols
    
    y=df["Market"]
    w = 2
    roll_beta = DataFrame()
    
    for col in df.columns[1:]: 
        roll_beta[col] = ols.PandasRollingOLS(y=y, x=df[[col]], window=w).beta[col]
    
    
    print(roll_beta)