用ny进行MACD、KDJ、RSI的代码实现
时间: 2023-07-10 19:27:36 浏览: 113
以下是使用Python和ny进行MACD、KDJ、RSI指标计算的代码实现:
1. MACD指标计算代码:
```
import numpy as np
import pandas as pd
def MACD(df, n_fast=12, n_slow=26, n_signal=9):
"""
计算MACD指标
"""
EMAfast = df['close'].ewm(span=n_fast, min_periods=n_fast - 1).mean()
EMAslow = df['close'].ewm(span=n_slow, min_periods=n_slow - 1).mean()
MACD = EMAfast - EMAslow
signal = MACD.ewm(span=n_signal, min_periods=n_signal - 1).mean()
histogram = MACD - signal
return MACD, signal, histogram
```
2. KDJ指标计算代码:
```
import numpy as np
import pandas as pd
def KDJ(df, n=9):
"""
计算KDJ指标
"""
low_list = df['low'].rolling(window=n, min_periods=n).min()
high_list = df['high'].rolling(window=n, min_periods=n).max()
rsv = (df['close'] - low_list) / (high_list - low_list) * 100
K = rsv.ewm(span=3, adjust=False).mean()
D = K.ewm(span=3, adjust=False).mean()
J = 3 * K - 2 * D
return K, D, J
```
3. RSI指标计算代码:
```
import numpy as np
import pandas as pd
def RSI(df, n=14):
"""
计算RSI指标
"""
delta = df['close'].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
gain = up.rolling(window=n, min_periods=n).mean()
loss = abs(down.rolling(window=n, min_periods=n).mean())
RS = gain / loss
RSI = 100.0 - (100.0 / (1.0 + RS))
return RSI
```
以上代码实现了MACD、KDJ、RSI三个指标的计算,使用时需要传入包含股票价格信息的DataFrame,例如:
```
df = pd.read_csv('stock.csv')
MACD(df)
KDJ(df)
RSI(df)
```
其中'stock.csv'是包含股票价格信息的CSV文件,包含'open'、'high'、'low'、'close'等列。
阅读全文