Home > Blockchain >  Pandas: create a new column based on percentage growth rates from another column
Pandas: create a new column based on percentage growth rates from another column

Time:12-23

I am pretty sure I am struggling with something very simple, but I need some help...

I am trying o add in the column Portfolio the total values of shares based on their daily price development:

Date Close Change Portfolio
2018-12-27 10381.509766 NaN 1000.000000
2018-12-28 10558.959961 0.017093 1017.092908
2019-01-02 10580.190430 0.002011 1002.010659
2019-01-03 10416.660156 -0.015456 984.543731
2019-01-04 10767.690430 0.033699 1033.698927

I am using therefore the following function:

def XP_strategy(data):
    #Starting capital
    START = 1000
    data['Change'] = data['Close'].pct_change()
    data['Portfolio'] = START
    data.loc[1:, 'Portfolio'] = data['Portfolio'].shift(1) * (1   data['Change'])

    columns = ['Close', 'Change', 'Portfolio']

    return data[columns]
    

As you can see I am not able to aply the formula for a Portfolio ion a day based on the day before. Is there someone who could help me please?

CodePudding user response:

I would go easier way about this - you just need to establish a proportion portfolio / close once, and then use the proportion to figure out the portfolio value from a given close value. Like this:

start = 1000
proportion = start/df['Close'].iloc[0]
df['Portfolio'] = proportion * df['Close']

Result:

    Date    Close   Portfolio
0   2018-12-27  10381.509766    1000.000000
1   2018-12-28  10558.959961    1017.092908
2   2019-01-02  10580.190430    1019.137935
3   2019-01-03  10416.660156    1003.385865
4   2019-01-04  10767.690430    1037.198892

CodePudding user response:

Use pct_change

START = 1000
df['Portfolio'] = START   START * df['Close'].pct_change().fillna(0)
print(df)

# Output:
         Date         Close    Change    Portfolio
0  2018-12-27  10381.509766       NaN  1000.000000
1  2018-12-28  10558.959961  0.017093  1017.092908
2  2019-01-02  10580.190430  0.002011  1002.010659
3  2019-01-03  10416.660156 -0.015456   984.543731
4  2019-01-04  10767.690430  0.033699  1033.698927
  • Related