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

Python 中一個好用的股票開源庫akshare

嘗試著獲取股票的數據來研究一下,經過查找與對比,決定使用 akshare 這個庫,因為該庫一直有更新,並且文檔是中文,而且比較詳細,

圖片
akshare 文檔地址:https://www.akshare.xyz/

7538ad090168ea082b8e1a961345ffc9
股票各種數據獲取方法
導入 akshare 庫

1import akshare as ak
2import pandas as pd

1、股票的基本信息數據#

1ak.stock_individual_info_em(symbol="000651")

7776dd5e1362e50450dcb6504b3836cf

2、實時數據,當日的成交數據#

單次返回所有滬深京 A 股上市公司的實時行情數據

f10f4f3f9dce838cea73df9a7f104747

3、歷史數據,歷史的成交數據#

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

640c7a929e8da5a1580881ff55622142

4、資金流向數據#

限量:單次獲取指定市場和股票的近 100 個交易日的資金流數據

1ak.stock_individual_fund_flow(stock="000651", market="sz")

fdafbe268b2bac6eba1386136529ede3

5、行情報價,買賣各 5 檔#

ak.stock_bid_ask_em(symbol="000651")

2160d3d4d75105d61ef3243e6d6f276d

範例#

from datetime import datetime

import backtrader as bt  # 升級到最新版
import matplotlib.pyplot as plt  # 由於 Backtrader 的問題,此處要求 pip install matplotlib==3.2.2
import akshare as ak  # 升級到最新版
import pandas as pd

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

# 利用 AKShare 獲取股票的後復權數據,這裡只獲取前 6 列
stock_hfq_df = ak.stock_zh_a_hist(symbol="000001", adjust="hfq").iloc[:, :6]
# 處理字段命名,以符合 Backtrader 的要求
stock_hfq_df.columns = [
    'date',
    'open',
    'close',
    'high',
    'low',
    'volume',
]
# 把 date 作為日期索引,以符合 Backtrader 的要求
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])


class MyStrategy(bt.Strategy):
    """
    主策略程序
    """
    params = (("maperiod", 20),)  # 全局設定交易策略的參數

    def __init__(self):
        """
        初始化函數
        """
        self.data_close = self.datas[0].close  # 指定價格序列
        # 初始化交易指令、買賣價格和手續費
        self.order = None
        self.buy_price = None
        self.buy_comm = None
        # 添加移動均線指標
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod
        )

    def next(self):
        """
        執行邏輯
        """
        if self.order:  # 檢查是否有指令等待執行,
            return
        # 檢查是否持倉
        if not self.position:  # 沒有持倉
            if self.data_close[0] > self.sma[0]:  # 執行買入條件判斷:收盤價格上漲突破20日均線
                self.order = self.buy(size=100)  # 執行買入
        else:
            if self.data_close[0] < self.sma[0]:  # 執行賣出條件判斷:收盤價格跌破20日均線
                self.order = self.sell(size=100)  # 執行賣出


cerebro = bt.Cerebro()  # 初始化回測系統
start_date = datetime(1991, 4, 3)  # 回測開始時間
end_date = datetime(2020, 6, 16)  # 回測結束時間
data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date)  # 加載數據
cerebro.adddata(data)  # 將數據傳入回測系統
cerebro.addstrategy(MyStrategy)  # 將交易策略加載到回測系統中
start_cash = 1000000
cerebro.broker.setcash(start_cash)  # 設置初始資本為 100000
cerebro.broker.setcommission(commission=0.002)  # 設置交易手續費為 0.2%
cerebro.run()  # 運行回測系統

port_value = cerebro.broker.getvalue()  # 獲取回測結束後的總資金
pnl = port_value - start_cash  # 盈虧統計

print(f"初始資金: {start_cash}\n回測期間:{start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}")
print(f"總資金: {round(port_value, 2)}")
print(f"淨收益: {round(pnl, 2)}")

cerebro.plot(style='candlestick')  # 畫圖

結果#

圖片

可視化#

圖片

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。