python回测股市策略
时间: 2023-11-20 10:58:31 浏览: 169
为了回测股市策略,我们可以使用Python中的pandas和numpy库。具体步骤如下:
1.首先,我们需要获取股票数据。可以使用pandas-datareader库从Yahoo Finance获取数据。例如,我们可以获取苹果公司(AAPL)的股票数据:
```python
import pandas_datareader as pdr
import datetime
start_date = datetime.datetime(2010, 1, 1)
end_date = datetime.datetime(2021, 1, 1)
aapl = pdr.get_data_yahoo('AAPL', start_date, end_date)
```
2.接下来,我们可以定义一个策略函数。例如,我们可以定义一个简单的双均线策略,即当短期均线(如5天均线)上穿长期均线(如20天均线)时买入,当短期均线下穿长期均线时卖出。代码如下:
```python
def double_moving_average(data, short_window=5, long_window=20):
signals = pd.DataFrame(index=data.index)
signals['signal'] = 0.0
signals['short_mavg'] = data['Close'].rolling(window=short_window, min_periods=1, center=False).mean()
signals['long_mavg'] = data['Close'].rolling(window=long_window, min_periods=1, center=False).mean()
signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:] > signals['long_mavg'][short_window:], 1.0, 0.0)
signals['positions'] = signals['signal'].diff()
return signals
```
3.然后,我们可以使用backtrader库来回测我们的策略。backtrader是一个功能强大的Python框架,用于开发和回测交易策略。以下是一个简单的backtrader策略示例:
```python
import backtrader as bt
class DoubleMovingAverage(bt.Strategy):
params = (('short', 5), ('long', 20))
def __init__(self):
self.short_mavg = bt.indicators.SimpleMovingAverage(
self.data.close, period=self.params.short)
self.long_mavg = bt.indicators.SimpleMovingAverage(
self.data.close, period=self.params.long)
self.crossover = bt.indicators.CrossOver(self.short_mavg, self.long_mavg)
def next(self):
if not self.position:
if self.crossover > 0:
self.buy()
elif self.crossover < 0:
self.close()
```
4.最后,我们可以运行回测并绘制结果。以下是一个简单的回测和绘图示例:
```python
cerebro = bt.Cerebro()
cerebro.addstrategy(DoubleMovingAverage)
data = bt.feeds.PandasData(dataname=aapl)
cerebro.adddata(data)
cerebro.broker.setcash(100000.0)
cerebro.broker.setcommission(commission=0.001)
cerebro.addsizer(bt.sizers.PercentSizer, percents=10)
cerebro.run()
cerebro.plot()
```
阅读全文