当前位置:网站首页>量化初级 -- akshare获得股票代码,最简策略
量化初级 -- akshare获得股票代码,最简策略
2022-07-29 15:58:00 【人工智能曾小健】
import akshare as ak
import pandas as pdstock_code =ak.stock_zh_a_spot_em() #获得股票所有代码的函数
stock_code
fuxing_code = stock_code[stock_code['名称'] == '复星医药']
fuxing_codefrom datetime import datetime
import backtrader as bt # 升级到最新版
import matplotlib.pyplot as plt # 由于 Backtrader 的问题,此处要求 pip install matplotlib==3.2.2
import akshare as ak # 升级到最新版
import pandas as pd
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
#plt.figure().set_size_inches(6,8)#6,8分别对应宽和高
plt.rcParams['figure.figsize'] = (13,13/(16/9)) #6,8分别对应宽和高
# 利用 AKShare 获取股票的后复权数据,这里只获取前 6 列
stock_hfq_df = ak.stock_zh_a_hist(symbol="600196", adjust="hfq").iloc[:, :6]
# 处理字段命名,以符合 Backtrader 的要求
stock_hfq_df.columns = [
'date',
'open',
'close',
'high',
'low',
'volume',
]
# 把 date 作为日期索引,以符合 Backtrader 的要求
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])
class MyStrategy(bt.Strategy):
"""
主策略程序
"""
params = (("maperiod", 20),) # 全局设定交易策略的参数
def __init__(self):
"""
初始化函数
"""
self.data_close = self.datas[0].close # 指定价格序列
# 初始化交易指令、买卖价格和手续费
self.order = None
self.buy_price = None
self.buy_comm = None
# 添加移动均线指标
self.sma = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod
)
def next(self):
"""
执行逻辑
"""
if self.order: # 检查是否有指令等待执行,
return
# 检查是否持仓
if not self.position: # 没有持仓
if self.data_close[0] > self.sma[0]: # 执行买入条件判断:收盘价格上涨突破20日均线
self.order = self.buy(size=100) # 执行买入
else:
if self.data_close[0] < self.sma[0]: # 执行卖出条件判断:收盘价格跌破20日均线
self.order = self.sell(size=100) # 执行卖出
cerebro = bt.Cerebro() # 初始化回测系统
start_date = datetime(1991, 4, 3) # 回测开始时间
end_date = datetime(2020, 6, 16) # 回测结束时间
data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date) # 加载数据
cerebro.adddata(data) # 将数据传入回测系统
cerebro.addstrategy(MyStrategy) # 将交易策略加载到回测系统中
start_cash = 1000000
cerebro.broker.setcash(start_cash) # 设置初始资本为 100000
cerebro.broker.setcommission(commission=0.002) # 设置交易手续费为 0.2%
cerebro.run() # 运行回测系统
port_value = cerebro.broker.getvalue() # 获取回测结束后的总资金
pnl = port_value - start_cash # 盈亏统计
print(f"初始资金: {start_cash}\n回测期间:{start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}")
print(f"总资金: {round(port_value, 2)}")
print(f"净收益: {round(pnl, 2)}")
#
cerebro.plot(style='candlestick') # 画图初始资金: 1000000 回测期间:19910403:20200616 总资金: 1038230.14 净收益: 38230.14

边栏推荐
- 最新!多交的税可以退,同学,你今天退税了吗?
- [Designers must learn] Lighting skills of Enscape in SketchUp
- 可行性研究报告模板
- 【翻译】设备管理器—英特尔网卡属性设置高级选项的功能
- 一文参透分布式存储系统Ceph的架构设计、集群搭建(手把手)
- Practice of Weibo Advertising Operation and Maintenance Technology Supporting Ten Billions of Requests
- 错排问题详解
- 1802. 有界数组中指定下标处的最大值【贪心 +二分】
- 打卡广汽本田喜悦安全驾驶中心,体验最刁钻的场地训练
- ByteArrayOutputStream 类源码分析
猜你喜欢

稳步向前不忘初心,沃尔沃的安全感来自公众的认可
![[PCL study notes] Commonly used libraries and APIs for point cloud processing (PCL library Eigen)](/img/b6/0f6113109aef776c777cb25a0ffb95.png)
[PCL study notes] Commonly used libraries and APIs for point cloud processing (PCL library Eigen)

Practice of Weibo Advertising Operation and Maintenance Technology Supporting Ten Billions of Requests

leetcode:1901. 寻找峰值 II【二分找矩阵局部最大】

浅谈程序的内存布局

This article penetrates the architecture design and cluster construction of the distributed storage system Ceph (hands-on)

How should small and medium-sized financial enterprises carry out disaster recovery construction?

CAS原理以及ABA问题解决Demo-代码

分布式前修课:MySQL实现分布式锁

节省70%的显存,训练速度提高2倍!浙大&阿里提出在线卷积重新参数化OREPA,代码已开源!(CVPR 2022 )...
随机推荐
Staggered question explanation
【翻译】设备管理器—英特尔网卡属性设置高级选项的功能
中小型金融企业该如何进行灾备建设?
[极客大挑战 2019]LoveSQL 1
MQTT over QUIC:下一代物联网标准协议为消息传输场景注入新动力
【服务器存储数据恢复】华为OceanStor某型号存储raid5硬盘故障离线,热备盘同步数据失败导致raid崩溃的数据恢复案例
货比三家 tb1.3
一文看懂分布式存储架构
【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)
(笔记)Build was configured to prefer settings repositories over project repositories but 解决方法
pjax无法生效解决办法,butterfly主题维护你的pjax
【Swoole系列3.2】Swoole 异步进程服务系统
MySQL数据库安装配置保姆级教程(以8.0.29为例)有手就行
数字孪生万物可视 | 联接现实世界与数字空间
揭秘 | 2019 To B 年度盛宴那些人和那些事
异步请求池的实现
干货!如何使用仪表构造SRv6-TE性能测试环境
如何在C语言中定义自己的数据类型?
Alibaba 开源内网高并发编程手册
线程中的常见方法