banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

akshare is a useful open-source library for stocks in Python.

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.

image
akshare documentation address: https://www.akshare.xyz/

7538ad090168ea082b8e1a961345ffc9
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")

7776dd5e1362e50450dcb6504b3836cf

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.

f10f4f3f9dce838cea73df9a7f104747

3. Historical data, historical transaction data#

 ak.stock_zh_a_hist(symbol="000651", 
                    period="daily", 
                    start_date="20230701", 
                    end_date='20230725',
                    adjust=""
                 ) #unadjusted

640c7a929e8da5a1580881ff55622142

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")

fdafbe268b2bac6eba1386136529ede3

5. Market quotation, buy and sell 5 levels#

ak.stock_bid_ask_em(symbol="000651")

2160d3d4d75105d61ef3243e6d6f276d

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

Result#

image

Visualization#

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.