我正在尝试重新创建下面的列'sig',但是更快,更有效。 我的尝试是“sig2”,但也会遇到自己的错误。
import numpy as np
import pandas as pd
a = np.random.standard_normal(500)
A = pd.DataFrame(np.cumsum(a))
A['Max'] = pd.rolling_max(A[0],10)
A['Min'] = pd.rolling_min(A[0],10)
A['Mean'] = pd.rolling_mean(A[0],3)
A['sig'] = 0
for t in range(1,A.shape[0]):
if (A['Max'][t] > A['Max'][t-1]) & (A['sig'][t-1]==0):
A['sig'][t] = 1
elif (A['Min'][t] < A['Min'][t-1]) & (A['sig'][t-1]==0):
A['sig'][t] = -1
elif ((A[0][t] > A['Mean'][t]) & (A['sig'][t-1]==-1)) | ((A[0][t] < A['Mean'][t]) & (A['sig'][t-1]==1)):
A['sig'][t] = 0
else:
A['sig'][t] = A['sig'][t-1]
state = 0
B = A.shift()
def get_val(A,B,prev_state):
global state
if (A['Max'] > B['Max']) & (prev_state==0):
state = 1
return state
elif (A['Min'] < B['Min']) & (prev_state==0):
state = -1
return state
elif ((A[0] > A['Mean']) & (prev_state==-1)) | ((A[0] < A['Mean']) & (prev_state==1)):
state = 0
return state
else:
return state
A['sig2'] = A.apply(lambda x: get_val(x,B,state))
谢谢