当我想计算2771行的加权移动平均值并且我的n = 3时 ,我得到2771行的77783.446664(相同的答案)。我的代码出了点问题。我需要更改什么?
我的数据如下:
Date, Open, High, Low, Close, Adj Close, Volume
11/16/2007,228.259995,229.570007,222.570007,225.25,196.770523,10083400
11/19/2007,223.520004,228.399994,216.619995,220.539993,192.656067,11007900
11/20/2007,220.399994,226.229996,213.5,217.479996,189.982925,13433000
11/21/2007,213.410004,215.270004,206.440002,209.5,183.011887,14874300
11/23/2007,212.520004,216.479996,211.800003,216.479996,189.109329,4737100
11/26/2007,214.649994,217.449997,205.419998,207.449997,181.221085,9815200
11/27/2007,210,213.979996,206.190002,213.330002,186.357651,11946400
11/28/2007,217.580002,227.860001,217.080002,227.520004,198.753555,15710600
11/29/2007,226.020004,228.309998,222.5,224.380005,196.010559,9774200
11/30/2007,232.649994,234.220001,224.770004,226.639999,197.984848,11878600
12/3/2007,226.089996,229.350006,223.600006,226.889999,198.203201,6800300
我的代码是:
import pandas as pd
#WMA = ( Price n + Price(1) n-1 + ...+Price( n-1 ) 1) / ( n ( n + 1 ) / 2 ), (n = time period).
def wma(data, n):
for i in range(n, 0, -1):
data[abs(n-i)] = i * data[abs(n-i)]
print(data[i])
return sum(data) / ((n * (n + 1)) / 2)
data_pd = pd.read_csv('GS.csv')
format = '%m/%d/%Y'
data_pd['Date'] = pd.to_datetime(data_pd['Date'], format=format)
data_pd = data_pd.set_index(data_pd['Date'])
data_pd = data_pd.drop(columns=['Date'])
n1 = 3
data_pd['wma'] = wma(data_pd['Close'].values, n1)
答案 0 :(得分:0)
IIUC,假设您需要对您加权的行进行3次加权,则前一次是2x,一次是在其之前的加权,那么您可以尝试此操作;
weights = np.array([1,2,3])
data_pd['wma'] = data_pd[' Close'].rolling(len(weights)).apply(lambda column: np.correlate(column,weights/sum(weights)))
data_pd.head()
Open High Low Close Adj Close \
Date
2007-11-16 228.259995 229.570007 222.570007 2027.250000 196.770523
2007-11-19 223.520004 228.399994 216.619995 882.159972 192.656067
2007-11-20 220.399994 226.229996 213.500000 217.479996 189.982925
2007-11-21 213.410004 215.270004 206.440002 209.500000 183.011887
2007-11-23 212.520004 216.479996 211.800003 216.479996 189.109329
Volume wma
Date
2007-11-16 10083400 NaN
2007-11-19 11007900 NaN
2007-11-20 13433000 740.668322
2007-11-21 14874300 324.269994
2007-11-23 4737100 214.319997