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

 

 

原网站

版权声明
本文为[Artificial intelligence Zeng Xiaojian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261028260628.html