Python 簡單的 股市資料 API 呼叫範例
前言假如我們想從某個外部服務取得股市資料藉由Python API 呼叫可以讓我們從雅虎財經的API下載市場數據。以下簡單得介紹一個API yfinance 一個 Python 開源函式庫使用者可以輕鬆地取得股票、指數、貨幣、ETF、基金以及期貨等相關金融商品的資訊。重要!yfinance提供了一種 Pythonic 的方式來從Yahoo!Ⓡ finance獲取金融和市場數據。yfinance與 Yahoo, Inc.無任何關聯也未獲得其認可或審查。它是一個開源工具使用 Yahoo 公開提供的 API旨在用於和教育目的。安裝pip install yfinancepip install pandas實作導入必要的函式庫: yfinance. pandas 模組是 Python 的一個強大數據操作與分析庫.它提供高效且靈活的資料結構,如 Series 和 DataFrame,適合用於資料清理、操作及分析。前置條件查詢相關股票代碼以下列出幾個案例美國股票:公司 | 股票代碼Apple Inc. | AAPLMicrosoft Corporation | MSFTAmazon.com, Inc. | AMZNAlphabet Inc. | GOOGLFacebook, Inc. | FBNVIDIA Corporation | NVDATesla, Inc. | TSLA-----------------------------------台灣股票(TWSE/TPEX)股票:公司 | 股票代碼台積電 | 2330.TW鴻海 | 2317.TW聯發科 | 2454.TW世界先進 | 5347.TWO-----------------------------------中國大陸股票公司 | 股票代碼貴州茅台 | 600519.SS浦發銀行 | 600000.SS中國銀行 | 601988.SS平安銀行 | 000001.SZ萬科 | 000002.SZ參考美股代號1.直接到 Yahoo 股市查詢台股股票代號查詢1.TWSE 臺灣證券交易所2.直接到 Yahoo 股市查詢中國股票代號查詢1.上海證券交易所2.深圳證券交易所實作代碼import yfinance as yf import pandas as pd pd.options.display.float_format {:,.2f}.format try: stock yf.Ticker(600519.SS) info stock.info company_info { 公司名稱: info.get(longName), 產業: info.get(sector), 公司網站: info.get(website) } df pd.DataFrame( company_info.items(), columns[欄位, 值] ) print(df.to_string(indexFalse)) # 較快速取得基本資訊 f_info stock.fast_info # 顯示欄位 important { lastPrice: f_info.get(lastPrice), dayHigh: f_info.get(dayHigh), dayLow: f_info.get(dayLow), marketCap: f_info.get(marketCap) } df pd.DataFrame.from_dict( important, orientindex, columns[Value] ) mapping { lastPrice: 最新股價, dayHigh: 今日最高, dayLow: 今日最低, marketCap: 市值 } rows [] for key, name in mapping.items(): rows.append({ 欄位: name, 值: f_info.get(key) }) df pd.DataFrame(rows) print(df.to_string(indexFalse)) print(\n) # 取得歷史股價資料 hist stock.history(period5d) hist hist.rename(columns{ Open: 開盤價, High: 最高價, Low: 最低價, Close: 收盤價, Volume: 成交量, Dividends: 股利, Stock Splits: 股票分割 }) hist.index.name 日期 hist.index hist.index.strftime(%Y-%m-%d) hist hist[[ 開盤價, 最高價, 最低價, 收盤價, 成交量 ]] print(hist.to_string()) except Exception as e: print(fAPI 失效: {e})測試(比對yahoo 網頁上的資料)重要!!本文僅為使用 Python API 呼叫 範例
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2622578.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!