Home > Mobile >  Please how can i use generate a formula in pandas
Please how can i use generate a formula in pandas

Time:04-14

df['weight_MA']= (Pn ​ ∗W1 ​ ) (Pn−1 ​ ∗W2 ​ ) (Pn−2 ​ ∗W3 ​ )... / ∑W ​

where: P = Price for the period n = The most recent period, n-1 is the prior period, and n-2 is two periods prior W = The assigned weight to each period, with the highest weight going first and then descending linearly based on the number of periods being used ​

Please how can i use that formula in pandas to get something like

((P5 * 5) (P4 *4) (P3 *3) (P2 *2) (P1 *1)) / (5 4 3 2 1)

Let’s say that the price of this stock fluctuates as so:

Day 5: $90.90

Day 4: $90.36

Day 3: $90.28

Day 2: $90.83

Day 1: $90.91

df['weight_MA'] = ((90.90 *5) (90.36 *4) (90.28 *3) (90.83 *2) (90.91 *1)) / (5 4 3 2 1) =

CodePudding user response:

weight = numpy.array([1,2,3,4,5])
df = pandas.DataFrame([90.91,90.83,90.28,90.36,90.90])

df['weight_MA'] = df.rolling(weight.shape[0]).apply(lambda x: numpy.sum(x * weight) / numpy.sum(weight))

rolling gives you a dataframe consisting of the previous n row value. Then, applying a lambda function to multiply df and your weight, and divided by the sum of weight.

  • Related