I try to figure out an efficient way to create a DataFrame of returns (ReturnTable) based on prices (PriceTable). Is there a more efficient way than just iterating with a for loop over the columns?
Here I have a small example:
import pandas as pd
PriceTable = pd.DataFrame({
'Dates':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'],
'Stock1':[10, 12, 13.5, 11.5],
'Stock2':[5, 5.5, 'NaN', 'NaN'],
'Stock3':['NaN', 9, 9.5, 10.5],
'Stock4':[20, 20, 19.5, 15]})
I try to get a ReturnTable which is just the division of the price at time t and t-1.
ReturnTable = pd.DataFrame({
'Dates':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'],
'Stock1':[0, 1.2, 1.125, 0.852],
'Stock2':[0, 1.1, 'NaN', 'NaN'],
'Stock3':['NaN', 0, 1.056, 1.105],
'Stock4':[0, 1, 0.975, 0.769]})
Thanks a lot!