Try to get the data of stocks for research. After searching and comparing, decide to use the akshare library because it is constantly updated, the documentation is in Chinese, and it is more detailed.
akshare documentation address: https://www.akshare.xyz/
Various methods to obtain stock data
Import akshare library
1import akshare as ak
2import pandas as pd
1. Basic information data of stocks#
1ak.stock_individual_info_em(symbol="000651")
2. Real-time data, intraday transaction data#
Return all real-time market data of A-shares listed companies in Shanghai, Shenzhen, and Beijing in one go.
3. Historical data, historical transaction data#
ak.stock_zh_a_hist(symbol="000651",
period="daily",
start_date="20230701",
end_date='20230725',
adjust=""
) #unadjusted
4. Fund flow data#
Limit: Get the fund flow data of the specified market and stock for the past 100 trading days at one time.
1ak.stock_individual_fund_flow(stock="000651", market="sz")
5. Market quotation, buy and sell 5 levels#
ak.stock_bid_ask_em(symbol="000651")
Example#
from datetime import datetime
import backtrader as bt # Upgrade to the latest version
import matplotlib.pyplot as plt # Due to the problem of Backtrader, here 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
# Use AKShare to get the stock's adjusted data, only get the first 6 columns here
stock_hfq_df = ak.stock_zh_a_hist(symbol="000001", adjust="hfq").iloc[:, :6]
# Rename the fields to meet the requirements of Backtrader
stock_hfq_df.columns = [
'date',
'open',
'close',
'high',
'low',
'volume',
]
# Set the date as the date index to meet the requirements of Backtrader
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])
class MyStrategy(bt.Strategy):
"""
Main strategy program
"""
params = (("maperiod", 20),) # Set the parameters of the trading strategy globally
def __init__(self):
"""
Initialization function
"""
self.data_close = self.datas[0].close # Specify the price series
# Initialize trading instructions, buying and selling prices, and commissions
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):
"""
Execute logic
"""
if self.order: # Check if there is an instruction waiting to be executed
return
# Check if there is a position
if not self.position: # No position
if self.data_close[0] > self.sma[0]: # Execute buy condition judgment: closing price rises above the 20-day moving average
self.order = self.buy(size=100) # Execute buy
else:
if self.data_close[0] < self.sma[0]: # Execute sell condition judgment: closing price falls below the 20-day moving average
self.order = self.sell(size=100) # Execute sell
cerebro = bt.Cerebro() # Initialize the backtesting system
start_date = datetime(1991, 4, 3) # Start date of backtesting
end_date = datetime(2020, 6, 16) # End date of backtesting
data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date) # Load data
cerebro.adddata(data) # Add data to the backtesting system
cerebro.addstrategy(MyStrategy) # Load the trading strategy into the backtesting 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 backtesting system
port_value = cerebro.broker.getvalue() # Get the total capital after the backtest
pnl = port_value - start_cash # Profit and loss statistics
print(f"Initial capital: {start_cash}\nBacktesting period: {start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}")
print(f"Total capital: {round(port_value, 2)}")
print(f"Net profit: {round(pnl, 2)}")
cerebro.plot(style='candlestick') # Plot