当前位置:网站首页>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 pd
stock_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
边栏推荐
猜你喜欢
4、 Stacks and queues
统计遗传学:第二章,统计分析概念
02 linked list of redis data structure
3、 Linked list exercise
This paper introduces the simple operation of realizing linear quadratic moving average of time series prediction that may be used in modeling and excel
Qixia housing and Urban Rural Development Bureau and fire rescue brigade carried out fire safety training
[deep learning theory] (7) long and short term memory network LSTM
ISO 26262 - 2 functional safety concept
PC QQ大廳 上傳更新 修改versionInfo
深度学习中的FLOPs和Params如何计算
随机推荐
机器学习SVM——实验报告
3、 Linked list exercise
目前为止最全的Kubernetes最新版核心命令
redux相关用法
SolidWorks rendering tips how not to display edges -- display style settings
JWT (SSO scheme) + three ways of identity authentication
(typora picture bed) Alibaba cloud OSS building picture bed +picgo uploading picture detailed tutorial
Openresty overview
nacos2.x.x启动报错信息Error creating bean with name ‘grpcClusterServer‘;
【深度学习理论】(6) 循环神经网络 RNN
机器学习LDA——实验报告
Svn installation configuration
Recent work report
Wangeditor uploading local video modification
dd命令测试华为鲲鹏&宏衫固态存储磁盘读写速度
Machine learning SVM - Experimental Report
CEPH operation and maintenance common instructions
In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]
互联网对抗神器之漏洞扫描与反渗透
4、 Stacks and queues