当前位置:网站首页>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

边栏推荐
- Unity使用SteamVRPlugin时如何不让其他Camera位置和旋转收到SteamVRPlugin控制
- Qixia housing and Urban Rural Development Bureau and fire rescue brigade carried out fire safety training
- 3、 Linked list exercise
- MySQL performance monitoring and SQL statements
- Docker中实现MySQL主从复制
- LeetCode 710 黑名单中的随机数[随机数] HERODING的LeetCode之路
- Flannel's host GW and calico
- Redux related usage
- Code specification & explain in detail the functions and uses of husky, prettier, eslint and lint staged
- [deep learning theory] (7) long and short term memory network LSTM
猜你喜欢
随机推荐
APICloud 实现文档下载和预览功能
Laravel admin obtains non auto increment ID and submits hidden forms
Change calico network mode to host GW
Laravel admin login add graphic verification code
有手就行的移动平均法、指数平滑法的Excel操作,用来时间序列预测
Is it safe to open an account in the top ten securities app rankings in China
10年程序员职业生涯感悟—写给正在迷茫的你
Uncaught reflectionexception: class view does not exist
wangEditor 上传本地视频修改
FastRCNN
Consumer microservice Governance Center stepping on the pit
QT连接MySql数据查询失败
Splicing full paths and uploading multiple pictures of laravel admin when laravel uses OSS
. Net, the usage of log components NLog, seriallog, log4net
JS take the date of the previous month 【 pit filling 】
Laravel admin hidden button, and set button display, default sequence, form form form non modifiable value
Work report (3)
18:第三章:开发通行证服务:1:短信登录&注册流程,简介;(这儿使用短信验证码)
深圳市福田区支持文化创意产业发展若干措施
mysql性能監控和sql語句









