用python写一段量化交易回测系统
时间: 2023-07-18 16:31:45 浏览: 162
量化交易回测系统是一个比较复杂的系统,需要考虑很多因素,包括数据获取、数据处理、策略回测、交易执行等。以下是一个简单的量化交易回测系统的示例代码,用Python实现:
```
import pandas as pd
import yfinance as yf
# 获取股票数据
def get_stock_data(ticker, start_date, end_date):
data = yf.download(ticker, start=start_date, end=end_date)
return data
# 计算技术指标
def calculate_indicator(data):
data['MA10'] = data['Adj Close'].rolling(window=10).mean()
data['MA60'] = data['Adj Close'].rolling(window=60).mean()
data['MACD'] = data['Adj Close'].ewm(span=12).mean() - data['Adj Close'].ewm(span=26).mean()
data['Signal'] = data['MACD'].ewm(span=9).mean()
return data
# 回测交易策略
def backtest_strategy(data):
data['Position'] = 0
data['Position'][data['MA10'] > data['MA60']] = 1
data['Position'][data['MA10'] < data['MA60']] = -1
data['Position'][data['MACD'] < data['Signal']] = -1
data['Position'][data['MACD'] > data['Signal']] = 1
data['Returns'] = data['Adj Close'].pct_change() * data['Position'].shift(1)
data['Cumulative Returns'] = (1 + data['Returns']).cumprod()
return data
# 执行交易
def execute_trade(data, capital):
data['Shares'] = (capital * data['Position']) // data['Adj Close']
data['Cash'] = capital - (data['Shares'] * data['Adj Close']).cumsum()
data['Total'] = data['Cash'] + (data['Shares'] * data['Adj Close']).cumsum()
return data
# 测试
ticker = 'AAPL'
start_date = '2015-01-01'
end_date = '2021-01-01'
capital = 100000
data = get_stock_data(ticker, start_date, end_date)
data = calculate_indicator(data)
data = backtest_strategy(data)
data = execute_trade(data, capital)
print(data.tail())
```
以上代码实现了一个简单的交易策略,即根据股票的10日移动平均线和60日移动平均线的交叉以及MACD指标的金叉和死叉来确定交易信号,然后根据信号执行交易并计算收益。这个交易策略非常简单,只是为了演示如何实现一个量化交易回测系统。在实际应用中,需要根据具体的需求设计更加复杂的交易策略,并考虑更多的因素,如手续费、滑点等。
阅读全文