我有一个开放/高/低/收盘价的 Pandas 数据框,并且我正在写一个函数,该函数将抛物线SAR添加到我的数据框中。现在,PSAR的数量正疯狂地增长,在牛市和熊市之间转换时,我似乎从未得到太多 yield 。任何有助于理解我的PSAR为何如此疯狂的帮助都将是巨大的。我已经尝试过对此代码进行几种变体,但均无济于事。
对于那些不熟悉PSAR的人:
上升SAR
Current SAR = Prior SAR + Prior AF(Prior EP - Prior SAR)
例如:10年4月13日: SAR = 48.28 = 48.13 + .14(49.20-48.13)
SAR下降
Current SAR = Prior SAR - Prior AF(Prior EP - Prior SAR)
例如:10年2月9日: SAR = 43.56 = 43.84-.16(43.84-42.07)
在反转期间,PSAR变为先前的极限点EP,而新的EP则取决于翻转的方向,成为先前的最高点或最低点。 AF重置为0.02。
我的功能:
def addSAR(df):
df.loc[0, 'AF'] =0.02
df.loc[0, 'PSAR'] = df.loc[0, 'low']
df.loc[0, 'EP'] = df.loc[0, 'high']
df.loc[0, 'PSARdir'] = "bull"
for a in range(1, len(df)):
if df.loc[a-1, 'PSARdir'] == 'bull':
df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'EP']-df.loc[a-1, 'PSAR']))
df.loc[a, 'PSARdir'] = "bull"
if df.loc[a, 'low'] < df.loc[a-1, 'PSAR']:
df.loc[a, 'PSARdir'] = "bear"
df.loc[a, 'PSAR'] = df.loc[a-1, 'EP']
df.loc[a, 'EP'] = df.loc[a-1, 'low']
df.loc[a, 'AF'] = .02
else:
if df.loc[a, 'high'] > df.loc[a-1, 'EP']:
df.loc[a, 'EP'] = df.loc[a, 'high']
if df.loc[a-1, 'AF'] <= 0.18:
df.loc[a, 'AF'] =df.loc[a-1, 'AF'] + 0.02
else:
df.loc[a, 'AF'] = df.loc[a-1, 'AF']
elif df.loc[a, 'high'] <= df.loc[a-1, 'EP']:
df.loc[a, 'AF'] = df.loc[a-1, 'AF']
df.loc[a, 'EP'] = df.loc[a-1, 'EP']
elif df.loc[a-1, 'PSARdir'] == 'bear':
df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] - (df.loc[a-1, 'AF']*(df.loc[a-1, 'EP']-df.loc[a-1, 'PSAR']))
df.loc[a, 'PSARdir'] = "bear"
if df.loc[a, 'high'] > df.loc[a-1, 'PSAR']:
df.loc[a, 'PSARdir'] = "bull"
df.loc[a, 'PSAR'] = df.loc[a-1, 'EP']
df.loc[a, 'EP'] = df.loc[a-1, 'high']
df.loc[a, 'AF'] = .02
else:
if df.loc[a, 'low'] < df.loc[a-1, 'EP']:
df.loc[a, 'EP'] = df.loc[a, 'low']
if df.loc[a-1, 'AF'] <= 0.18:
df.loc[a, 'AF'] = df.loc[a-1, 'AF'] + 0.02
else:
df.loc[a, 'AF'] = df.loc[a-1, 'AF']
elif df.loc[a, 'low'] >= df.loc[a-1, 'EP']:
df.loc[a, 'AF'] = df.loc[a-1, 'AF']
df.loc[a, 'EP'] = df.loc[a-1, 'EP']
return df
最佳答案
想通了Facepalm
df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'EP']-df.loc[a-1, 'PSAR']))
应该是
df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'PSAR']-df.loc[a-1, 'EP']))
最后两个变量转置!真是痛苦
现在我可以清理功能并使它变得更好..
希望这可以帮助别人做一些愚蠢的事情并坚持2天