当前位置:网站首页>Quantitative elementary -- akshare obtains stock code, the simplest strategy
Quantitative elementary -- akshare obtains stock code, the simplest strategy
2022-06-26 11:16:00 【Artificial intelligence Zeng Xiaojian】
import akshare as ak
import pandas as pdstock_code =ak.stock_zh_a_spot_em() # Function to get all stock codes
stock_code
fuxing_code = stock_code[stock_code[' name '] == ' Fosun medicine ']
fuxing_code
from datetime import datetime
import backtrader as bt # Upgrade to the latest version
import matplotlib.pyplot as plt # because Backtrader The problem of , This requires pip install matplotlib==3.2.2
import akshare as ak # Upgrade to the latest version
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 Corresponding to width and height respectively
plt.rcParams['figure.figsize'] = (13,13/(16/9)) #6,8 Corresponding to width and height respectively
# utilize AKShare Get the post reversion data of the stock , Here only get the front 6 Column
stock_hfq_df = ak.stock_zh_a_hist(symbol="600196", adjust="hfq").iloc[:, :6]
# Process field naming , To conform to Backtrader The requirements of
stock_hfq_df.columns = [
'date',
'open',
'close',
'high',
'low',
'volume',
]
# hold date As a date index , To conform to Backtrader The requirements of
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])
class MyStrategy(bt.Strategy):
"""
Main policy program
"""
params = (("maperiod", 20),) # Set the parameters of the transaction strategy globally
def __init__(self):
"""
Initialization function
"""
self.data_close = self.datas[0].close # Specify the price sequence
# Initialize transaction instructions 、 Buying and selling price and handling fee
self.order = None
self.buy_price = None
self.buy_comm = None
# Add moving average indicator
self.sma = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod
)
def next(self):
"""
Perform logical
"""
if self.order: # Check whether there are instructions waiting to be executed ,
return
# Check whether the position is
if not self.position: # No position
if self.data_close[0] > self.sma[0]: # Judge the execution conditions of the purchase : The closing price rose above 20 ma
self.order = self.buy(size=100) # Executive buy
else:
if self.data_close[0] < self.sma[0]: # Execute sell condition judgment : The closing price fell below 20 ma
self.order = self.sell(size=100) # Execute sell
cerebro = bt.Cerebro() # Initialize the back test system
start_date = datetime(1991, 4, 3) # Back test start time
end_date = datetime(2020, 6, 16) # End of test
data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date) # Load data
cerebro.adddata(data) # Transfer the data to the back test system
cerebro.addstrategy(MyStrategy) # Load the trading strategy into the back test system
start_cash = 1000000
cerebro.broker.setcash(start_cash) # Set the initial capital to 100000
cerebro.broker.setcommission(commission=0.002) # Set the transaction fee to 0.2%
cerebro.run() # Run the back test system
port_value = cerebro.broker.getvalue() # Obtain the total funds after the back test
pnl = port_value - start_cash # Profit and loss statistics
print(f" Initial funding : {start_cash}\n During the back test :{start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}")
print(f" Total funds : {round(port_value, 2)}")
print(f" Net profit : {round(pnl, 2)}")
#
cerebro.plot(style='candlestick') # drawing Initial funding : 1000000 During the back test :19910403:20200616 Total funds : 1038230.14 Net profit : 38230.14

边栏推荐
- Huawei secoclient reports an error "accept return code timeout" [svn adapter v1.0 exclamation point]
- 手机注册股票开户 开户安全吗
- express在nodejs中的基本使用
- Implementing MySQL master-slave replication in docker
- 最强swarm集群一键部署+氢弹级容器管理工具介绍
- nacos2.x.x启动报错信息Error creating bean with name ‘grpcClusterServer‘;
- QT连接MySql数据查询失败
- C language -- operators and expressions
- 【北邮果园微处理器设计】10 Serial Communication 串口通信笔记
- 哈希表的前置知识---二叉搜索树
猜你喜欢

PC QQ大厅 上传更新 修改versionInfo

Svn installation configuration

Machine learning deep neural network -- Experimental Report

nacos2.x.x启动报错信息Error creating bean with name ‘grpcClusterServer‘;

19: Chapter 3: develop pass service: 2: get through Alibaba cloud SMS service in the program; (it only connects with Alibaba cloud SMS server, and does not involve specific business development)

FastRCNN

深度理解STM32的串口实验(寄存器)【保姆级教程】

QT连接MySql数据查询失败
![[work details] March 18, 2020](/img/24/a72230daac08e7ec5bd57df08071f8.jpg)
[work details] March 18, 2020

Redis best practices? If I don't feel excited after reading it, I will lose!!
随机推荐
18: Chapter 3: development of pass service: 1: SMS login & registration process, introduction; (SMS verification code is used here)
【深度学习理论】(6) 循环神经网络 RNN
Compréhension approfondie de l'expérience de port série stm32 (registre) [Tutoriel de niveau nounou]
[Beiyou orchard microprocessor design] 10 serial communication serial communication notes
CEPH operation and maintenance common instructions
laravel-admin 非自增ID获取, 及提交隐藏表单
再获认可!知道创宇入选“业务安全推进计划”首批成员单位
Consumer microservice Governance Center stepping on the pit
修改calico网络模式为host-gw
sliding window
我想知道同花顺是炒股的么?手机开户安全么?
Nacos2.x.x start error creating bean with name 'grpcclusterserver';
Splicing full paths and uploading multiple pictures of laravel admin when laravel uses OSS
Uncaught reflectionexception: class view does not exist
QT connection MySQL data query failed
SolidWorks rendering tips how not to display edges -- display style settings
手机注册股票开户 开户安全吗
Redis knowledge mind map
laravel 使用 OSS时拼接 完整路径 及 laravel-admin 的多图片上传
深度学习中的FLOPs和Params如何计算