Python 量化投资原来这么简单(2) —MACD策略(+26.9%)

Python 量化投资原来这么简单(3) —A股回测MACD策略

https://github.com/Ckend/pythondict-quant

## 1.准备

Windows环境下打开Cmd(开始—运行—CMD)，苹果系统环境下请打开Terminal(command+空格输入Terminal)，准备开始输入命令安装依赖。

`pip install backtrader`

## 2.改造策略

```def run_cerebro(stock_file, result):
"""
运行策略
:param stock_file: 股票数据文件位置
:param result: 回测结果存储变量
"""

cerebro = bt.Cerebro()

# 加载数据到模型中
data = bt.feeds.GenericCSVData(
dataname=stock_file,
fromdate=datetime.datetime(2010, 1, 1),
todate=datetime.datetime(2020, 4, 25),
dtformat='%Y%m%d',
datetime=2,
open=3,
high=4,
low=5,
close=6,
volume=10,
reverse=True
)

# 本金10000，每次交易100股
cerebro.broker.setcash(10000)

# 万五佣金
cerebro.broker.setcommission(commission=0.0005)

# 运行策略
cerebro.run()

# 剩余本金
money_left = cerebro.broker.getvalue()

# 获取股票名字
stock_name = stock_file.split('\\')[-1].split('.csv')[0]

# 将最终回报率以百分比的形式返回
result[stock_name] = float(money_left - 10000) / 10000```

```files_path = 'stocks\\'
result = []

# 遍历所有股票数据
for stock in os.listdir(files_path):
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, files_path + stock)
print(datapath)
try:
run_cerebro(datapath, result)
except Exception as e:
print(e)```

```f = open('./batch_macd_result.txt', 'wb')
pickle.dump(result, f)
f.close()```

## 3.结果分析

```import pickle

# 加载保存的结果
f = open('./batch_macd_result.txt', 'rb')
f.close()

# 计算
pos = []
neg = []
ten_pos = []
ten_neg = []
for result in data:
res = data[result]
if res > 0:
pos.append(res)
else:
neg.append(res)

if res > 0.1:
ten_pos.append(result)
elif res < -0.1:
ten_neg.append(result)

max_stock = max(data, key=data.get)

print(f'最高收益的股票： {max_stock}, 达到 {data[max_stock]}')
print(f'正收益数量: {len(pos)}, 负收益数量:{len(neg)}')
print(f'+10%数量: {len(ten_pos)}, -10%数量:{len(ten_neg)}')
print(f'收益10%以上的股票: {ten_pos}')```

```D:\CODE\stock\backtrader&gt;python analysis.py

+10%数量: 30, -10%数量:29

​Python实用宝典 ( pythondict.com )