ATR选股策略买卖代码
时间: 2023-08-24 08:10:06 浏览: 103
ATR马丁网格Fluid Blue 3.3_ea_网格atr_多策略EA_趋势EA_网格EA_
5星 · 资源好评率100%
ATR选股策略是一种基于股票的波动性来进行买卖决策的策略。其代码实现如下:
```
# 导入必要的库
import pandas as pd
import numpy as np
import yfinance as yf
# 获取股票数据
stock_data = yf.download('AAPL', start='2010-01-01', end='2021-01-01')
# 计算ATR指标
stock_data['H-L'] = abs(stock_data['High'] - stock_data['Low'])
stock_data['H-PC'] = abs(stock_data['High'] - stock_data['Adj Close'].shift(1))
stock_data['L-PC'] = abs(stock_data['Low'] - stock_data['Adj Close'].shift(1))
stock_data['TR'] = stock_data[['H-L', 'H-PC', 'L-PC']].max(axis=1)
stock_data['ATR'] = stock_data['TR'].rolling(window=14).mean()
# 选股
stock_data['Signal'] = 0
stock_data['Position'] = np.nan
for i in range(1, len(stock_data)):
if stock_data['Adj Close'][i] > stock_data['Adj Close'][i-1] and stock_data['Adj Close'][i] > stock_data['Adj Close'][i-2]:
stock_data['Signal'][i] = 1
elif stock_data['Adj Close'][i] < stock_data['Adj Close'][i-1] and stock_data['Adj Close'][i] < stock_data['Adj Close'][i-2]:
stock_data['Signal'][i] = -1
else:
stock_data['Signal'][i] = 0
if stock_data['Signal'][i] == 1:
stock_data['Position'][i] = 1
elif stock_data['Signal'][i] == -1:
stock_data['Position'][i] = 0
else:
stock_data['Position'][i] = stock_data['Position'][i-1]
# 计算收益率
stock_data['Returns'] = np.log(stock_data['Adj Close']/stock_data['Adj Close'].shift(1))
stock_data['Strategy'] = stock_data['Position'].shift(1) * stock_data['Returns']
stock_data['Cumulative Returns'] = np.cumsum(stock_data['Strategy'])
```
在这段代码中,我们首先导入了必要的库,然后使用yfinance获取了AAPL公司的股票数据。接着,我们计算了股票的ATR指标,并在此基础上进行选股。具体来说,如果股票的收盘价连续两天上涨,则我们认为它是一个买入信号;如果股票的收盘价连续两天下跌,则我们认为它是一个卖出信号。如果没有出现这样的信号,则我们保持之前的持仓。最后,我们计算了股票的收益率和策略的收益率,并将其累积起来得到了最终的累计收益率。
阅读全文