繁体   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