如何解决使用 Pandas DF 计算 ADX 指标/平滑平均问题
我在 Python 中使用 Pandas DF 计算 ADX 指标时遇到问题。过去几天一直在绞尽脑汁想知道出了什么问题。我的想法可能与平滑平均值有关?结果的最后几行是:最后一行“2021-07-03”的 ADX 应该在 33 左右。
i. date. open. high. low. close. +DI. -DM EMa. -DI. DX. ADX.
396 2021-06-30 35894.90 36088.87 34013.34 35036.58 ... 0.629251 -132.284380 -4.690877 1.309852 5.418229
397 2021-07-01 35048.78 35048.78 32720.03 33506.98 ... -4.476247 57.794871 2.098175 2.764602 5.479026
398 2021-07-02 33502.26 33971.12 32698.40 33796.99 ... -9.798669 52.972888 2.071717 1.536231 5.483165
399 2021-07-03 33831.62 34807.59 33322.38 34632.63 ... -4.374875 -37.287497 -1.544599 0.478130 5.475540
我的代码如下:
def adx_calc(df):
for current in range(1,len(df.index)):
previous = current - 1
#True Range:
tr = max((df.loc[current,'high'] - df.loc[current,'low']),(df.loc[current,'high'] - df.loc[previous,'close']),abs((df.loc[previous,'close'] - df.loc[current,'low'])))
df.loc[current,'TR'] = tr
df['ATR'] = df['TR'].ewm(span = 14).mean()
# DM's:
df.loc[current,'+DM'] = df.loc[current,'high']
df.loc[current,'-DM'] = df.loc[previous,'low'] - df.loc[current,'low']
# + DI:
df['+DM_EMA'] = pd.DataFrame.ewm(df['+DM'],span = adx_time_period).mean()
df.loc[current,'+DI'] = ((df.loc[current,'+DM_EMA'] / df.loc[current,'ATR']) * 100)
# - DI:
df['-DM_EMA'] = pd.DataFrame.ewm(df['-DM'],'-DI'] = ((df.loc[current,'-DM_EMA'] / df.loc[current,'ATR']) * 100)
# # DX:
df.loc[current,'DX'] = (abs((df.loc[current,'+DI'] - df.loc[current,'-DI'])) / abs((df.loc[current,'+DI'] + df.loc[current,'-DI'])))
# # ADX:
df['ADX'] = df['DX'].rolling(window=14).mean()```
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。