starbolt
starbolt

Reputation: 467

How to iterate over YFinance data

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?

Upvotes: 2

Views: 1524

Answers (1)

P. Pinho
P. Pinho

Reputation: 404

Since dates are treated as index, you can iterate over them simply by referring to them as data.index

data.index

output:

DatetimeIndex(['2021-03-03', '2021-03-04', '2021-03-05', '2021-03-08',
               '2021-03-09', '2021-03-10', '2021-03-11', '2021-03-12',
               '2021-03-15', '2021-03-16',
               ...
               '2022-02-16', '2022-02-17', '2022-02-18', '2022-02-21',
               '2022-02-22', '2022-02-23', '2022-02-24', '2022-02-25',
               '2022-03-02', '2022-03-03'],
              dtype='datetime64[ns]', name='Date', length=250, freq=None)

For instance:

for date in data.index:
    print(date)

Output:

2021-03-03 00:00:00
2021-03-04 00:00:00
2021-03-05 00:00:00
2021-03-08 00:00:00
2021-03-09 00:00:00
...
2022-02-23 00:00:00
2022-02-24 00:00:00
2022-02-25 00:00:00
2022-03-02 00:00:00
2022-03-03 00:00:00

Upvotes: 1

Related Questions