Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Log-returns for Multiple Securities in Python

here's what I have thus far - I have built a price table (as shown in the image), and I would like to calculate the log-returns of the respective tickers. Price Table priceData = pd.read_excel(r'..\PriceData.xlsx', skiprows=range(1),

usecols = 'B:SN', index_col = 0)

priceData = priceData.drop(priceData.index[[0,1]])

priceData.index.names = ['Date']

priceData.index = priceData.index.map(pd.to_datetime)

priceData.sort_index()

# To adjust all time series data to start from 1990-01-25 to 2018-09-24
for column in priceData.columns:
    if np.isnan(priceData[column].iloc[0]):
        priceData = priceData.drop([column],axis=1, inplace=True)

stocks = list(table)

returns = table.apply(lambda x: np.log(x)-np.log(x.shift(1)))

*table is my dataframe name.

The error message I have faced is:

"TypeError: ("unsupported operand type(s) for /: 'float' and >'datetime.datetime'", 'occurred at index LYB UN Equity')"

Update

I have tried with:

returns = table.apply(lambda x: np.log(x)-np.log(x.shift(1)))

But I am met with a new error message:

("'float' object has no attribute 'log'", 'occurred at index LYB UN Equity')

Please advise!

like image 668
fauxpas Avatar asked May 15 '26 23:05

fauxpas


1 Answers

I have figured out a more intuitive way.

# Calculate returns
returns = table.pct_change() # simple linear returns
log_rets = np.log(1+returns)

This will work when calculating log returns of multiple securities in the same dataframe. Cheers!

like image 84
fauxpas Avatar answered May 18 '26 13:05

fauxpas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!