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

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

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

2、實(shí)時(shí)數(shù)據(jù),當(dāng)日的成交數(shù)據(jù)
單次返回所有滬深京 A 股上市公司的實(shí)時(shí)行情數(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ù)
限量: 單次獲取指定市場(chǎng)和股票的近 100 個(gè)交易日的資金流數(shù)據(jù)
ak.stock_individual_fund_flow(stock="000651", market="sz")

5、行情報(bào)價(jià),買(mǎi)賣(mài)各5檔
ak.stock_bid_ask_em(symbol="000651")

根據(jù)數(shù)據(jù)生成摘要
函數(shù)如下,注意參數(shù)和后面的函數(shù)要對(duì)應(yīng)。這里的代碼稍顯麻煩,主要是在描述同比漲跌幅時(shí)公司有要求,具體生成的格式大家可按自己的要求進(jìn)行更改。
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 = "虧損擴(kuò)大"
elif abs(profit) < abs(pre_profit):
profit_decs = "虧損減少"
else:
profit_decs = "同比持平"
# 轉(zhuǎn)化為億元、萬(wàn)元的單位
revenue = get_unit(revenue)
profit = get_unit(profit)
summary = f"【{name}】{period_desc}實(shí)現(xiàn)營(yíng)業(yè)總收入{revenue},{revenue_desc};" \
f"歸母凈利潤(rùn){profit},{profit_decs}。"
return summary獲取摘要
需要輸入報(bào)告期和股票代碼。(這里只獲取營(yíng)收和利潤(rùn)數(shù)據(jù),注意同花順上這個(gè)凈利潤(rùn)實(shí)際上是指歸母凈利潤(rùn))
date_mapping_1 = {
"03-31": "季度報(bào)告:",
"06-30": "半年度報(bào)告:",
"09-30": "季度報(bào)告:",
"12-31": "年度報(bào)告:"
}
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:], "未知") # 摘要標(biāo)題
if title == "未知":
messagebox.showerror("報(bào)告期錯(cuò)誤")
return # 結(jié)束函數(shù)的運(yùn)行
quarter = date_mapping_2.get(period[5:], "未知") # 季度描述
# 獲取去年同期的報(bào)告期字符串
year = period[:4] # 獲取前四個(gè)字符
int_year = int(year) - 1 # 將前四個(gè)字符轉(zhuǎn)換為數(shù)字并減去1
last_year = str(int_year).zfill(4) # 將得到的數(shù)字轉(zhuǎn)換為字符串,補(bǔ)齊至四位
yoy_period = period.replace(year, last_year, 1) # 替換字符串的前四個(gè)字符,得到去年同期的報(bào)告期
period_desc = f"{title}公司{year}{quarter}"
# 對(duì)每個(gè)輸入的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]:無(wú)法匹配\n")
continue
# 從同花順獲取關(guān)鍵財(cái)務(wù)指標(biāo)
try:
data = ak.stock_financial_abstract_ths(symbol=code, indicator="按報(bào)告期")
data = data.set_index(data.columns[0])
except KeyError:
results.append(f"[code]:{name}獲取財(cái)報(bào)數(shù)據(jù)失敗\n")
continue
# 判斷是否存在數(shù)據(jù)
try:
revenue = remove_unit(data.loc[period, "營(yíng)業(yè)總收入"])
revenue_change = str2percentage(data.loc[period, "營(yíng)業(yè)總收入同比增長(zhǎng)率"])
profit = remove_unit(data.loc[period, "凈利潤(rùn)"])
profit_change = str2percentage(data.loc[period, "凈利潤(rùn)同比增長(zhǎng)率"])
# 獲取去年歸母凈利潤(rùn)數(shù)據(jù)
pre_profit = remove_unit(data.loc[yoy_period, "凈利潤(rùn)"])
except KeyError:
results.append(f"[code]:{name}報(bào)告未更新\n")
continue
# 調(diào)用函數(shù)獲取財(cái)報(bào)摘要,并保存在輸出列表中
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"獲取摘要時(shí)出錯(cuò):{str(e)}")
# 創(chuàng)建主窗口
root = tk.Tk()
root.title("日?qǐng)?bào)-財(cái)務(wù)報(bào)告摘要akshare")
# 添加標(biāo)簽和輸入框
period_label = tk.Label(root, text="請(qǐng)輸入報(bào)告期(如2023-06-30)")
period_label.pack()
period_entry = tk.Entry(root)
period_entry.pack()
code_list_label = tk.Label(root, text="請(qǐng)輸入公司code(多個(gè)則以英文逗號(hào)分隔)")
code_list_label.pack()
code_list_entry = tk.Entry(root, width=100)
code_list_entry.pack()
# 添加按鈕
run_button = tk.Button(root, text="運(yùn)行", command=get_summary)
run_button.pack()
# 添加結(jié)果顯示區(qū)域
result_text = tk.Text(root, height=30, width=120, state='disabled')
result_text.pack()
# 啟動(dòng) GUI 循環(huán)
root.mainloop()
每日特定股票數(shù)據(jù)匯總案例
下面展示每日獲取特定股票數(shù)據(jù),可以做成定時(shí)任務(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,
"前一日收盤(pán)價(jià)": df2['昨收'].to_list()[0],
"開(kāi)盤(pán)": df2['今開(kāi)'].to_list()[0],
"收盤(pán)": df2['最新價(jià)'].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],
"市盈率-動(dòng)態(tài)": df2['市盈率-動(dòng)態(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': '萬(wàn)達(dá)電影',
'600956': '新天綠能',
'600031': '三一重工',
'600703': '三安光電',
'002027': '分眾傳媒',
'600030': '中信證券',
'002939': '長(zhǎng)城證券',
} #小編買(mǎi)過(guò)的股票
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("運(yùn)行中出錯(cuò)",e)
sys.exit(-1)
pd.DataFrame.from_dict(results).to_excel(f'./data/{dt}.xlsx', index=False)到此這篇關(guān)于Python股票開(kāi)源庫(kù)akshare的具體使用的文章就介紹到這了,更多相關(guān)Python akshare內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中requests庫(kù)的基本概念與具體使用方法
requests庫(kù)是用python編寫(xiě)的基于urllib,requests唯一的一個(gè)非轉(zhuǎn)基因的Python HTTP庫(kù),下面這篇文章主要給大家介紹了關(guān)于Python中requests庫(kù)的基本概念與具體使用方法,需要的朋友可以參考下2022-08-08
python使用Turtle庫(kù)繪制動(dòng)態(tài)鐘表
這篇文章主要為大家詳細(xì)介紹了python使用Turtle庫(kù)繪制動(dòng)態(tài)鐘表,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
Python多模塊引用由此引發(fā)的相對(duì)路徑混亂問(wèn)題
這篇文章主要介紹了Python多模塊引用由此引發(fā)的相對(duì)路徑混亂問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Python學(xué)習(xí)之路安裝pycharm的教程詳解
pycharm 是一款功能強(qiáng)大的 Python 編輯器,具有跨平臺(tái)性。這篇文章主要介紹了Python學(xué)習(xí)之路安裝pycharm的教程,本文分步驟通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
詳解在Python中使用OpenCV進(jìn)行直線檢測(cè)
在圖像處理中,直線檢測(cè)是一種常見(jiàn)的算法,它通常獲取n個(gè)邊緣點(diǎn)的集合,并找到通過(guò)這些邊緣點(diǎn)的直線。本文將介紹如何在Python中利用OpenCV進(jìn)行直線檢測(cè),需要的可以參考一下2022-03-03

