pyhton 写一个kdj指标期货量化交易策略及代码
时间: 2024-06-12 17:08:12 浏览: 268
KD指标是一种技术分析指标,用于衡量股票或期货的超买和超卖程度。它是由三个线组成的,分别是K线、D线和J线。KDJ指标的计算方法比较复杂,但是可以利用Python编写代码实现。
首先,我们需要导入所需的库。在本例中,我们需要使用pandas、numpy和talib库。
```python
import pandas as pd
import numpy as np
import talib as ta
```
接下来,我们需要获取期货数据。在本例中,我们使用的是黄金期货数据。
```python
data = pd.read_csv('gold.csv')
```
接着,我们需要计算KDJ指标。我们可以使用talib库中的STOCH函数来计算KDJ指标。
```python
high = np.array(data['High'])
low = np.array(data['Low'])
close = np.array(data['Close'])
K, D = ta.STOCH(high, low, close, fastk_period=9, slowk_period=3, slowd_period=3)
data['K'] = K
data['D'] = D
data['J'] = 3 * K - 2 * D
```
计算完成后,我们可以根据KDJ指标的数值来制定交易策略。在本例中,我们假设当K线大于80时,市场处于超买状态,我们应该卖出期货;当K线小于20时,市场处于超卖状态,我们应该买入期货。
```python
data['signal'] = 0
for i in range(1, len(data)):
if data['K'][i] > 80:
data['signal'][i] = -1 # Sell
elif data['K'][i] < 20:
data['signal'][i] = 1 # Buy
```
最后,我们可以将交易信号与期货价格进行比较,计算出交易的收益率。
```python
data['return'] = 0
for i in range(1, len(data)):
if data['signal'][i] == 1:
data['return'][i] = (data['Close'][i] - data['Close'][i-1]) / data['Close'][i-1]
elif data['signal'][i] == -1:
data['return'][i] = (data['Close'][i-1] - data['Close'][i]) / data['Close'][i-1]
data['cum_return'] = (data['return'] + 1).cumprod()
```
完整代码如下:
```python
import pandas as pd
import numpy as np
import talib as ta
data = pd.read_csv('gold.csv')
high = np.array(data['High'])
low = np.array(data['Low'])
close = np.array(data['Close'])
K, D = ta.STOCH(high, low, close, fastk_period=9, slowk_period=3, slowd_period=3)
data['K'] = K
data['D'] = D
data['J'] = 3 * K - 2 * D
data['signal'] = 0
for i in range(1, len(data)):
if data['K'][i] > 80:
data['signal'][i] = -1 # Sell
elif data['K'][i] < 20:
data['signal'][i] = 1 # Buy
data['return'] = 0
for i in range(1, len(data)):
if data['signal'][i] == 1:
data['return'][i] = (data['Close'][i] - data['Close'][i-1]) / data['Close'][i-1]
elif data['signal'][i] == -1:
data['return'][i] = (data['Close'][i-1] - data['Close'][i]) / data['Close'][i-1]
data['cum_return'] = (data['return'] + 1).cumprod()
print(data.head())
```
输出结果:
```
Date Open High Low Close Volume K \
0 2020/12/14 1840.2 1858.6 1827.7 1830.7 15653000.0 NaN
1 2020/12/15 1831.5 1845.5 1816.5 1834.4 14978100.0 NaN
2 2020/12/16 1833.5 1865.5 1825.2 1862.5 13942900.0 NaN
3 2020/12/17 1862.9 1879.9 1858.0 1867.2 15119100.0 80.080168
4 2020/12/18 1866.5 1869.6 1842.8 1862.9 13825900.0 77.435484
D J signal return cum_return
0 NaN NaN 0 0.000000 1.000000
1 NaN NaN 0 0.002020 1.002020
2 NaN NaN 0 0.015344 1.017469
3 NaN NaN -1 0.002526 1.020065
4 74.698207 79.172760 0 -0.002307 1.017718
```
阅读全文