1.债性 — 安全保本

2.股性（可转换） — 存在套利空间

## 1.准备

(可选1) 如果你用Python的目的是数据分析，可以直接安装Anaconda：Python数据分析与挖掘好帮手—Anaconda，它内置了Python和pip.

(可选2) 此外，推荐大家用VSCode编辑器来编写小型Python项目：Python 编程的最好搭档—VSCode 详细指南

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

```pip install backtrader

1.下载并安装tesseract

2.配置环境变量

3.判断是否安装成功

`tesseract --version`

## 2.回测

### 2.1 基于分钟K线的Sma金叉策略

```    def golden(self, a, b):
if a[-1] - b[-1] < 0 and a[0] - b[0] > 0:
return True
else:
return False

def next(self):
if self.order:
return

if not self.position:
if self.golden(self.sma5, self.sma10):

else:
condition = (self.dataclose[0] - self.bar_executed_close) / self.bar_executed_close
if condition > 0.005:
self.order = self.sell()
self.params.selldays.append(self.datas[0].datetime.date(0))
for day in days:
self.params.hold_count[day] += 1```

### 2.2 基于分钟K线的EMA金叉的策略

```    def golden(self, a, b):
if a[-1] - b[-1] < 0 and a[0] - b[0] > 0:
return True
else:
return False

def next(self):
if self.order:
return

if not self.position:
if self.golden(self.exp1, self.exp2):

else:
condition = (self.dataclose[0] - self.bar_executed_close) / self.bar_executed_close
if condition > 0.005:
self.order = self.sell()
self.params.selldays.append(self.datas[0].datetime.date(0))
for day in days:
self.params.hold_count[day] += 1```

### 3.自动交易

1.读取今日需检测的股票

```def start():
account = Account()
logger.info(f"总股票数 {len(codes)}")
last_ping_time = datetime.datetime.now().timestamp()```

2.巡检

```    while True:
# 是否在交易时间
if not check_time():
continue
for code in codes:
now = int(datetime.datetime.now().timestamp())
logger.info(f"{now} - {code}")
try:
# TODO: 异步执行算法
continue

if abs(int(buy_time.timestamp()) - now) < 300:

except Exception as e:
traceback.print_exc()
logger.info(e)
# send_mail(f"算法解析失败: {traceback.print_exc()}", "WRONG", code)```

3.卖单兜底

```        now = datetime.datetime.now()
new_ping_time = now.timestamp()
if new_ping_time - last_ping_time > 15:
# 大于15秒，检测持仓，把未委托卖出的单子委托卖出
account.every_day_sell()
last_ping_time = new_ping_time
logger.info(f"{datetime.datetime.strftime(now, '%Y-%m-%d %H:%M:%S')} ping")```

​Python实用宝典 (pythondict.com)