簡體   English   中英

yfinance api 返回多個代碼數據

[英]yfinance api return multiple ticker data

我正在嘗試從 yfinance API 中提取多個代碼數據並將其保存到 csv 文件(我總共有 1000 個代碼需要獲取數據,該數據是整個日期表,開盤價,高價,低價,收盤價、交易量等),到目前為止,我能夠使用以下 Python 代碼成功獲取 1 個代碼的數據:

import yfinance as yf

def yfinance(ticker_symbol):
    ticker_data = yf.Ticker(ticker_symbol)
    tickerDF = ticker_data.history(period='1d', start='2020-09-30', end='2020-10-31')
    
    print(tickerDF)

yfinance('000001.SS')

但是,如果我嘗試使用多個代碼,這是行不通的。 按照 yfinance 文檔說多個代碼使用:

tickers = yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects

# access each ticker using (example)
tickers.tickers.MSFT.info
tickers.tickers.AAPL.history(period="1mo")
tickers.tickers.GOOG.actions

我這里有幾個問題,文檔使用諸如“aapl”之類的字符串,我的代碼都是數字格式,如“000001.SS”,“.SS”部分在將其傳遞到代碼中時被證明是一個問題:

tickers.tickers.000001.SS.history(period="1mo")
# Clearly this wont for for a start

我遇到的下一個問題是,即使我像這樣將 3 個代碼傳遞給我的 function:

yfinance('000001.SS 000050.KS 00006.KS')
# similar to yfinance docs of tickers = yf.Tickers('msft aapl goog')

我收到如下錯誤:

AttributeError: 'Tickers' object has no attribute '000001.SS'

(我也嘗試將它們運行到一個 for 循環中並將每個傳遞給 Tickers object 但得到相同的錯誤。)

我現在卡住了,我不知道如何將多個代碼傳遞給 yfinance 並取回我想要的數據,而且文檔也不是很有幫助。

有人能幫我嗎?

您能否將它們存儲在指定類型為 dtype object 的數組中,然后使用它從中提取數據。

import yfinance as yf
import numpy as np

tickers = ['msft', 'aapl', 'goog']

totalPortfolio = np.empty([len(tickers)], dtype=object)

num = 0
for ticker in tickers:
    totalPortfolio[num] = yf.download(ticker, start='2020-09-30', end='2020-10-31', interval="1d")
    num = num + 1

看看下面的代碼:

test = yf.Tickers("A B C") 
# creates test as a yf.tickers object

test_dict = test.tickers 
# creates a dict object containing the individual tickers. Can be checked with type()

您正在嘗試使用“tickers.tickers.MSFT.info”從字典“tickers.tickers”中檢索代碼數據,但就像您的錯誤消息所說的那樣,dict object 沒有以您的特定代碼名稱命名的屬性。 這通常不是您訪問字典中元素的方式。 相反,您應該使用如下代碼(與所有 dict 對象一樣):

#old code from above
test = yf.Tickers("A B C") 
test_dict = test.tickers 
#new code accessing the dict correctly
a_data = test_dict["A"]
a_data = test.tickers["A"] #does the same as the line above
b_data = test.tickers["B"] #and so on for the other tickers

在一個循環中,這看起來像這樣:

ticker_list = ["A", "B", "C"] #add tickers as needed
tickers_data = {}
tickers_history = {}
for ticker in ticker_list:
    tickers_data[ticker] = yf.Ticker(ticker)
    tickers_history = tickers_data[ticker].history(period='1d', start='2020-09-30', end='2020-10-31')
#access the dicts as needed using tickers_data[" your ticker name "]

或者,您也可以使用“yf.Tickers”function 一次檢索多個代碼,但因為您單獨保存歷史記錄,所以我認為這不一定會大大改進您的代碼。

但是您應該注意,“yf.Ticker()”和“yf.Tickers()”是具有不同語法的不同函數,不能互換。 當您嘗試使用您的自定義“yfinance()”function 訪問多個代碼時,您確實混淆了它,該代碼先前已使用“yf.Ticker()”function 定義,因此一次只接受一個符號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM