Here is an example of how to use cumprod and cummax.
cumprod ・ ・ ・ Calculates the cumulative product for all elements of the array. cummax ・ ・ ・ Extracts the maximum value from all the elements of the array.
test.py
import numpy as np
import pandas as pd
dat = [
    ['2019-07-01',10],
    ['2019-07-02',12],
    ['2019-07-03',8],
    ['2019-07-04',14],
    ['2019-07-05',7],
    ['2019-07-08',3]
]
df0 = pd.DataFrame(dat,columns=["A","B"])
print(df0)
df1=df0['B'].pct_change()
df2=(1 + df1)
df3=(1 + df1).cumprod() #Calculates the cumulative product from the 0th to the i-th element.
df4=(1 + df1).cummax()  #Extracts the maximum value among the 0th to i-th elements.
print(df1)
print(df2)
print(df3)
print(df4)
<df0:Basic data>
            A   B
0  2019-07-01  10
1  2019-07-02  12
2  2019-07-03   8
3  2019-07-04  14
4  2019-07-05   7
5  2019-07-08   3
df1: (df0['B']I th and i-Calculate the first rate of change)
0         NaN
1    0.200000
2   -0.333333
3    0.750000
4   -0.500000
5   -0.571429
Name: B, dtype: float64
df2: (df1+Calculate 1)
0         NaN
1    1.200000
2    0.666667
3    1.750000
4    0.500000
5    0.428571
Name: B, dtype: float64
df2: (cumprod()Calculate the cumulative product)
0    NaN
1    1.2
2    0.8  (=1.2×0.666667)
3    1.4   (=1.2×0.666667×1.75)
4    0.7   (=1.2×0.666667×1.75×0.5)
5    0.3   (=1.2×0.666667×1.75×0.5×0.428)
Name: B, dtype: float64
df3: (cummax()Extract the maximum value from the elements.)
0     NaN
1    1.20   (df2:Maximum value among elements 1 to 1)
2    1.20   (df2:Maximum value among elements 1 to 2)
3    1.75   (df2:Maximum value among elements 1 to 3)
4    1.75   (df2:Maximum value among elements 1 to 4)
5    1.75   (df2:Maximum value among elements 1 to 5)
Name: B, dtype: float64
        Recommended Posts