import pandas as pd import numpy as np import matplotlib.pyplot as plt from binance.client import Client from datetime import datetime 设置API密钥 api_key = 'your_api_key' api_secret = 'your_api_secret' 创建Binance API客户端 client = Client(api_key, api_secret) 读取K线数据 klines = client.futures_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1DAY) 将数据转换为DataFrame格式 data = pd.DataFrame(klines, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore']) 转换时间戳格式 data['Open time'] = pd.to_datetime(data['Open time'], unit='ms') data['Close time'] = pd.to_datetime(data['Close time'], unit='ms') data.set_index('Open time', inplace=True) 计算收益率 data['return'] = np.log(data['Close']) - np.log(data['Close'].shift(1)) 计算移动平均线 data['MA5'] = data['Close'].rolling(window=5).mean() data['MA10'] = data['Close'].rolling(window=10).mean() 判断市场趋势 if data['MA5'].iloc[-1] > data['MA10'].iloc[-1]: trend = 'up' else: trend = 'down' 趋势跟踪策略 if trend == 'up': position = 1 # 买入 else: position = 0 # 空仓 设置止损点和止盈点 stop_loss = 0.05 # 止损点为5% take_profit = 0.1 # 止盈点为10% 循环进行交易 for i in range(1, len(data)): # 如果市场处于上涨趋势中,买入资产 if trend == 'up': # 如果收益率小于止损点,触发止损点,平仓并且空仓对冲 if data['return'].iloc[i] < -stop_loss: position = 0 trend = 'down' # 如果收益率大于止盈点,触发止盈点,平仓并且空仓对冲 elif data['return'].iloc[i] > take_profit: position = 0 trend = 'down' # 如果收益率在止损点和止盈点之间,继续持有多头仓位 else: position = 1 # 如果市场处于下跌趋势中,空仓对冲 else: position = 0 # 计算资产净值 data['net_value'].iloc[i] = data['net_value'].iloc[i-1] * (1 + data['return'].iloc[i] * position) 绘制净值曲线 plt.plot(data.index, data['net_value']) plt.xlabel('Date') plt.ylabel('Net Value') plt.title('Trend Following Strategy') plt.show()将以上代码整理成PY格式
时间: 2023-08-08 22:04:52 浏览: 172
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from binance.client import Client
from datetime import datetime
# 设置API密钥
api_key = 'your_api_key'
api_secret = 'your_api_secret'
# 创建Binance API客户端
client = Client(api_key, api_secret)
# 读取K线数据
klines = client.futures_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1DAY)
# 将数据转换为DataFrame格式
data = pd.DataFrame(klines, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'])
# 转换时间戳格式
data['Open time'] = pd.to_datetime(data['Open time'], unit='ms')
data['Close time'] = pd.to_datetime(data['Close time'], unit='ms')
data.set_index('Open time', inplace=True)
# 计算收益率
data['return'] = np.log(data['Close']) - np.log(data['Close'].shift(1))
# 计算移动平均线
data['MA5'] = data['Close'].rolling(window=5).mean()
data['MA10'] = data['Close'].rolling(window=10).mean()
# 判断市场趋势
if data['MA5'].iloc[-1] > data['MA10'].iloc[-1]:
trend = 'up'
else:
trend = 'down'
# 趋势跟踪策略
if trend == 'up':
position = 1 # 买入
else:
position = 0 # 空仓
# 设置止损点和止盈点
stop_loss = 0.05 # 止损点为5%
take_profit = 0.1 # 止盈点为10%
# 循环进行交易
for i in range(1, len(data)):
# 如果市场处于上涨趋势中,买入资产
if trend == 'up':
# 如果收益率小于止损点,触发止损点,平仓并且空仓对冲
if data['return'].iloc[i] < -stop_loss:
position = 0
trend = 'down'
# 如果收益率大于止盈点,触发止盈点,平仓并且空仓对冲
elif data['return'].iloc[i] > take_profit:
position = 0
trend = 'down'
# 如果收益率在止损点和止盈点之间,继续持有多头仓位
else:
position = 1
# 如果市场处于下跌趋势中,空仓对冲
else:
position = 0
# 计算资产净值
data['net_value'].iloc[i] = data['net_value'].iloc[i-1] * (1 + data['return'].iloc[i] * position)
# 绘制净值曲线
plt.plot(data.index, data['net_value'])
plt.xlabel('Date')
plt.ylabel('Net Value')
plt.title('Trend Following Strategy')
plt.show()
```
阅读全文