Issue
I have the following multi-indexed dataframe:
I want to add a new column labeled returns
and assign the percentage change applied to the close
column i.e
bars.loc[symbol, 'returns'] = bars.loc[symbol]['close'].pct_change()
The challenge is that the returns
column does not get populated as expected. So with the snippet below, here is what I got
for symbol in symbols:
bars.loc[symbol, 'returns'] = bars.loc[symbol]['close'].pct_change()
print(df.loc[symbols[0]].tail())
The returns column has NaN as their values, what am I doing wrong here?
Solution
You need to assign the values to the new column. Assuming the DF is bars and symbol index is level_0 then for the loop, you can use the code below. This assumes you want 10.0 as the return % and not 0.1.
idx_list = bars.index.levels[0]
for symbol in idx_list:
x = bars.loc[symbol, 'close'].pct_change()*100
bars.loc[symbol, 'returns'] = x.values
Answered By - user19077881
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.