Python股票開源庫akshare的具體使用
背景
從小編真實接觸股票已經(jīng)有10年之久了,因為大學(xué)的專業(yè)就是數(shù)據(jù)與應(yīng)用數(shù)據(jù)(金融學(xué)方向),大三、大四學(xué)期時學(xué)習(xí)了很多涉及金融相關(guān)的課程,特別是在大四時,老師還專門給每位同學(xué)開通了模擬炒股的賬戶,讓全班同學(xué)一起模擬炒股,但小編用真金白銀炒股的時間大概是2018年,距現(xiàn)在也有5年時間,一直是韭菜中
最近大家也看到了曾任《環(huán)球時報》總編輯的胡錫進,也開始入市炒股,并且每天都會發(fā)博文,分享當(dāng)天的炒股感受
于是小編就試著獲取股票的數(shù)據(jù)來研究一下,經(jīng)過查找與對比,小編決定用akshare這個庫,因為該庫一直有更新,并且文檔是中文,而且比較詳細,

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

AKShare是一個開源財經(jīng)數(shù)據(jù)接口庫,所采集的數(shù)據(jù)皆來自公開的數(shù)據(jù)源,本文目的是當(dāng)上市公司發(fā)布財報時,在同花順上獲取其關(guān)鍵指標并輸出摘要,可以用來寫行研的日報等。
選擇AKShare的原因:免費且能迅速獲得數(shù)據(jù),tushare、baostock等庫一般不能獲得當(dāng)天發(fā)的財報數(shù)據(jù),而AKShare可以獲得各大權(quán)威財經(jīng)網(wǎng)站的數(shù)據(jù)。
股票各種數(shù)據(jù)獲取方法
導(dǎo)入akshare庫
import akshare as ak import pandas as pd
1、股票的基本信息數(shù)據(jù)
ak.stock_individual_info_em(symbol="000651")

2、實時數(shù)據(jù),當(dāng)日的成交數(shù)據(jù)
單次返回所有滬深京 A 股上市公司的實時行情數(shù)據(jù)
ak.stock_zh_a_spot_em()

3、歷史數(shù)據(jù),歷史的成交數(shù)據(jù)
ak.stock_zh_a_hist(symbol="000651",
period="daily",
start_date="20230701",
end_date='20230725',
adjust="" #不復(fù)權(quán)
)

4、資金流向數(shù)據(jù)
限量: 單次獲取指定市場和股票的近 100 個交易日的資金流數(shù)據(jù)
ak.stock_individual_fund_flow(stock="000651", market="sz")

5、行情報價,買賣各5檔
ak.stock_bid_ask_em(symbol="000651")

根據(jù)數(shù)據(jù)生成摘要
函數(shù)如下,注意參數(shù)和后面的函數(shù)要對應(yīng)。這里的代碼稍顯麻煩,主要是在描述同比漲跌幅時公司有要求,具體生成的格式大家可按自己的要求進行更改。
def generate_summary(name, period_desc, revenue, revenue_change, profit, profit_change, pre_profit):
if revenue_change > 0:
revenue_desc = f"同比上升{revenue_change:.2f}%"
elif revenue_change < 0:
revenue_desc = f"同比下降{abs(revenue_change):.2f}%"
else:
revenue_desc = "同比持平"
if profit >= 0 and pre_profit >= 0:
if profit > pre_profit:
profit_decs = f"同比上升{profit_change:.2f}%"
elif profit < pre_profit:
profit_decs = f"同比下降{abs(profit_change):.2f}%"
else:
profit_decs = "同比持平"
elif profit > 0 > pre_profit:
profit_decs = "扭虧為盈"
elif profit < 0 < pre_profit:
profit_decs = "轉(zhuǎn)盈為虧"
else: # 連年虧損
if abs(profit) > abs(pre_profit):
profit_decs = "虧損擴大"
elif abs(profit) < abs(pre_profit):
profit_decs = "虧損減少"
else:
profit_decs = "同比持平"
# 轉(zhuǎn)化為億元、萬元的單位
revenue = get_unit(revenue)
profit = get_unit(profit)
summary = f"【{name}】{period_desc}實現(xiàn)營業(yè)總收入{revenue},{revenue_desc};" \
f"歸母凈利潤{profit},{profit_decs}。"
return summary獲取摘要
需要輸入報告期和股票代碼。(這里只獲取營收和利潤數(shù)據(jù),注意同花順上這個凈利潤實際上是指歸母凈利潤)
date_mapping_1 = {
"03-31": "季度報告:",
"06-30": "半年度報告:",
"09-30": "季度報告:",
"12-31": "年度報告:"
}
date_mapping_2 = {
"03-31": "Q1",
"06-30": "H1",
"09-30": "前三季度",
"12-31": "年"
}
def get_summary():
period = period_entry.get()
code_list = code_list_entry.get().split(',')
try:
results = [] # 輸出結(jié)果
title = date_mapping_1.get(period[5:], "未知") # 摘要標題
if title == "未知":
messagebox.showerror("報告期錯誤")
return # 結(jié)束函數(shù)的運行
quarter = date_mapping_2.get(period[5:], "未知") # 季度描述
# 獲取去年同期的報告期字符串
year = period[:4] # 獲取前四個字符
int_year = int(year) - 1 # 將前四個字符轉(zhuǎn)換為數(shù)字并減去1
last_year = str(int_year).zfill(4) # 將得到的數(shù)字轉(zhuǎn)換為字符串,補齊至四位
yoy_period = period.replace(year, last_year, 1) # 替換字符串的前四個字符,得到去年同期的報告期
period_desc = f"{title}公司{year}{quarter}"
# 對每個輸入的code取數(shù)據(jù)
for code in code_list:
# 檢查code能否匹配公司
try:
company = ak.stock_individual_info_em(symbol=code)
name = company.iloc[5][1]
except KeyError:
results.append(f"[code]:無法匹配\n")
continue
# 從同花順獲取關(guān)鍵財務(wù)指標
try:
data = ak.stock_financial_abstract_ths(symbol=code, indicator="按報告期")
data = data.set_index(data.columns[0])
except KeyError:
results.append(f"[code]:{name}獲取財報數(shù)據(jù)失敗\n")
continue
# 判斷是否存在數(shù)據(jù)
try:
revenue = remove_unit(data.loc[period, "營業(yè)總收入"])
revenue_change = str2percentage(data.loc[period, "營業(yè)總收入同比增長率"])
profit = remove_unit(data.loc[period, "凈利潤"])
profit_change = str2percentage(data.loc[period, "凈利潤同比增長率"])
# 獲取去年歸母凈利潤數(shù)據(jù)
pre_profit = remove_unit(data.loc[yoy_period, "凈利潤"])
except KeyError:
results.append(f"[code]:{name}報告未更新\n")
continue
# 調(diào)用函數(shù)獲取財報摘要,并保存在輸出列表中
summary = generate_summary(name, period_desc, revenue, revenue_change, profit, profit_change, pre_profit)
results.append(f"{summary}\n")
result_text.config(state='normal') # 將輸出區(qū)域狀態(tài)更改為可編輯
result_text.delete('1.0', tk.END) # 清空區(qū)域
result_text.insert(tk.END, "\n".join(results)) # 將輸出列表中的內(nèi)容以換行符分隔,添加到輸出區(qū)域中
result_text.config(state='disabled') # 將輸出區(qū)域狀態(tài)更改為不可編輯
except Exception as e:
messagebox.showerror("Error", f"獲取摘要時出錯:{str(e)}")
# 創(chuàng)建主窗口
root = tk.Tk()
root.title("日報-財務(wù)報告摘要akshare")
# 添加標簽和輸入框
period_label = tk.Label(root, text="請輸入報告期(如2023-06-30)")
period_label.pack()
period_entry = tk.Entry(root)
period_entry.pack()
code_list_label = tk.Label(root, text="請輸入公司code(多個則以英文逗號分隔)")
code_list_label.pack()
code_list_entry = tk.Entry(root, width=100)
code_list_entry.pack()
# 添加按鈕
run_button = tk.Button(root, text="運行", command=get_summary)
run_button.pack()
# 添加結(jié)果顯示區(qū)域
result_text = tk.Text(root, height=30, width=120, state='disabled')
result_text.pack()
# 啟動 GUI 循環(huán)
root.mainloop()
每日特定股票數(shù)據(jù)匯總案例
下面展示每日獲取特定股票數(shù)據(jù),可以做成定時任務(wù),在15:00閉市后獲取
"""
===========================
@Time : 2023/7/26 20:13
@File : stock_day
@Software: PyCharm
@Platform: Win10
@Author : DataShare
===========================
"""
import akshare as ak
import pandas as pd
import datetime
import sys
def stock_to_excel(stock_code, stock_name):
if stock_code[0] == '6':
market = 'sh'
elif stock_code[0] == '0':
market = 'sz'
df1 = ak.stock_zh_a_spot_em()
df2 = df1[df1['代碼'] == stock_code]
dt = str(datetime.date.today()) #當(dāng)日
df3 = ak.stock_individual_fund_flow(stock=stock_code, market=market) #在15:00之后獲取
df4 = df3[df3['日期'] == dt]
result = {
"日期": dt,
"股票代碼": stock_code,
"股票名稱": stock_name,
"前一日收盤價": df2['昨收'].to_list()[0],
"開盤": df2['今開'].to_list()[0],
"收盤": df2['最新價'].to_list()[0],
"最高": df2['最高'].to_list()[0],
"最低": df2['最低'].to_list()[0],
"成交量": df2['成交量'].to_list()[0],
"成交額": df2['成交額'].to_list()[0],
"振幅": df2['振幅'].to_list()[0],
"漲跌幅": df2['漲跌幅'].to_list()[0],
"漲跌額": df2['漲跌額'].to_list()[0],
"換手率": df2['換手率'].to_list()[0],
"量比": df2['量比'].to_list()[0],
"市盈率-動態(tài)": df2['市盈率-動態(tài)'].to_list()[0],
"市凈率": df2['市凈率'].to_list()[0],
"60日漲跌幅": df2['60日漲跌幅'].to_list()[0],
"主力凈流入-凈額": df4['主力凈流入-凈額'].to_list()[0],
"主力凈流入-凈占比": df4['主力凈流入-凈占比'].to_list()[0],
"超大單凈流入-凈額": df4['超大單凈流入-凈額'].to_list()[0],
"超大單凈流入-凈占比": df4['超大單凈流入-凈占比'].to_list()[0],
"大單凈流入-凈額": df4['大單凈流入-凈額'].to_list()[0],
"大單凈流入-凈占比": df4['大單凈流入-凈占比'].to_list()[0],
"中單凈流入-凈額": df4['中單凈流入-凈額'].to_list()[0],
"中單凈流入-凈占比": df4['中單凈流入-凈占比'].to_list()[0],
"小單凈流入-凈額": df4['小單凈流入-凈額'].to_list()[0],
"小單凈流入-凈占比": df4['小單凈流入-凈占比'].to_list()[0]
}
return result
if __name__ == '__main__':
stocks_code = {'000651': '格力電器',
'002241': '歌爾股份',
'002739': '萬達電影',
'600956': '新天綠能',
'600031': '三一重工',
'600703': '三安光電',
'002027': '分眾傳媒',
'600030': '中信證券',
'002939': '長城證券',
} #小編買過的股票
dt = str(datetime.date.today())
results=[]
for stock_code, stock_name in stocks_code.items():
print(f'{stock_name}:{stock_code}')
try:
results.append(stock_to_excel(stock_code, stock_name))
except Exception as e:
print("運行中出錯",e)
sys.exit(-1)
pd.DataFrame.from_dict(results).to_excel(f'./data/{dt}.xlsx', index=False)到此這篇關(guān)于Python股票開源庫akshare的具體使用的文章就介紹到這了,更多相關(guān)Python akshare內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python學(xué)習(xí)之路安裝pycharm的教程詳解
pycharm 是一款功能強大的 Python 編輯器,具有跨平臺性。這篇文章主要介紹了Python學(xué)習(xí)之路安裝pycharm的教程,本文分步驟通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06

