海龟策略python代码
时间: 2023-07-02 17:15:42 浏览: 116
以下是一个简单的海龟策略的 Python 代码示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 计算移动平均线
def MA(df, window):
ma = df.rolling(window=window).mean()
return ma
# 计算真实波动幅度
def ATR(df, window):
high = df['High']
low = df['Low']
close = df['Close']
tr = pd.DataFrame(np.zeros(len(df)), columns=['TR'])
for i in range(1, len(df)):
tr.loc[i] = max(high[i] - low[i], abs(high[i] - close[i-1]), abs(low[i] - close[i-1]))
atr = MA(tr, window)
return atr
# 计算海龟策略的入场点和离场点
def turtle_signal(df, n1, n2):
atr = ATR(df, n1)
df['MA1'] = MA(df['Close'], n1)
df['MA2'] = MA(df['Close'], n2)
df['Signal'] = np.where(df['Close'] > df['MA1'] + 0.5 * atr, 1, 0)
df['Signal'] = np.where(df['Close'] < df['MA2'], -1, df['Signal'])
return df['Signal']
# 测试代码
data = pd.read_csv('data.csv')
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
signal = turtle_signal(data, 20, 55)
data['Signal'] = signal
data['Return'] = np.log(data['Close'].shift(-1) / data['Close']) * data['Signal'].shift(1)
data['Cumulative Return'] = data['Return'].cumsum()
data[['Close', 'MA1', 'MA2']].plot(figsize=(10, 6))
plt.plot(data.loc[data['Signal'] == 1].index, data['MA1'][data['Signal'] == 1], '^', markersize=10, color='g')
plt.plot(data.loc[data['Signal'] == -1].index, data['MA2'][data['Signal'] == -1], 'v', markersize=10, color='r')
plt.show()
```
这段代码实现了海龟策略的核心部分,包括计算移动平均线、真实波动幅度、海龟策略的入场点和离场点,并且将策略的信号标记在了数据中。最后,代码还画出了收益曲线和入场、离场点的标记。
阅读全文