如何迭代 YFinance 数据
我正在尝试获取单个股票的一些数据并将这些数据保存在数据库中。我正在使用 YFinance,它从雅虎财经获取数据。
ticker = yf.Ticker("BBAS3.SA")
data = ticker.history(period="1y")
print(data[['High', 'Low', 'Open', 'Close']]
此输出:
High Low Open Close
Date
2021-02-25 29.291426 27.632709 28.688257 27.764652
2021-02-26 28.122788 26.303854 27.906024 26.435797
2021-03-01 27.133212 26.124786 27.001268 26.256731
2021-03-02 27.698679 25.465068 25.870323 27.265152
2021-03-03 27.971992 26.398096 27.142633 27.321699
... ... ... ... ...
2022-02-21 36.230000 34.970001 36.139999 35.279999
2022-02-22 36.110001 35.369999 35.400002 35.610001
2022-02-23 36.119999 35.610001 35.799999 35.790001
2022-02-24 35.099998 34.090000 34.630001 34.650002
2022-02-25 35.169998 34.529999 34.709999 34.860001
[252 rows x 4 columns]
对于每一行,我需要在数据库中保存日期、最高/最低/开盘价和收盘价。
我找不到一种方法来迭代这些行并使其工作。
到目前为止,我最好的尝试是在 data[['High', 'Low', 'Open', 'Close']] 上使用 for 循环,但我无法访问“日期”字段。
如何迭代股票历史记录并获取所有这些字段?
I'm trying to get some data for a single stock and save this data on database. I'm using YFinance, which gets data from Yahoo Finance.
ticker = yf.Ticker("BBAS3.SA")
data = ticker.history(period="1y")
print(data[['High', 'Low', 'Open', 'Close']]
This outputs:
High Low Open Close
Date
2021-02-25 29.291426 27.632709 28.688257 27.764652
2021-02-26 28.122788 26.303854 27.906024 26.435797
2021-03-01 27.133212 26.124786 27.001268 26.256731
2021-03-02 27.698679 25.465068 25.870323 27.265152
2021-03-03 27.971992 26.398096 27.142633 27.321699
... ... ... ... ...
2022-02-21 36.230000 34.970001 36.139999 35.279999
2022-02-22 36.110001 35.369999 35.400002 35.610001
2022-02-23 36.119999 35.610001 35.799999 35.790001
2022-02-24 35.099998 34.090000 34.630001 34.650002
2022-02-25 35.169998 34.529999 34.709999 34.860001
[252 rows x 4 columns]
For each row, I need to save the date, high/low/open and close price on the database.
I can't find a way to iterate over this rows and make this work.
So far my best attempt was using a for loop on data[['High', 'Low', 'Open', 'Close']], but I can't access the "date" field.
How can I iterate the stock history and get all these fields?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于日期被视为索引,因此您只需将它们引用为
data.index
输出即可迭代它们:
例如:
输出:
Since dates are treated as index, you can iterate over them simply by referring to them as
data.index
output:
For instance:
Output: