Im using pandas datareader to get stock data.
import pandas as pd
import pandas_datareader.data as web
ABB = web.DataReader(name='ABB.ST',
data_source='yahoo',
start='2000-1-1')
However by default freq is not set on the resulting dataframe. I need freq to be able to navigate using the index like this:
for index, row in ABB.iterrows():
ABB.loc[[index + 1]]
If freq is not set on DatetimeIndex im not able to use +1
etc to navigate.
What I have found are two functions astype
and resample
. Since I already know to freq resample
looks like overkill, I just want to set freq to daily.
Now my question is how can i use astype on ABB to set freq to daily?
To create a PeriodIndex, use the pandas. PeriodIndex() method. To set the frequency, use the freq parameter.
date attribute outputs an Index object containing the date values present in each of the entries of the DatetimeIndex object. Example #1: Use DatetimeIndex. date attribute to find the date part of the DatetimeIndex object.
To reset the index in pandas, you simply need to chain the function . reset_index() with the dataframe object. On applying the . reset_index() function, the index gets shifted to the dataframe as a separate column.
class pandas. DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.
Try:
ABB = ABB.asfreq('d')
This should change the frequency to daily with NaN
for days without data.
Also, you should rewrite your for-loop
as follows:
for index, row in ABB.iterrows(): print(ABB.loc[[index + pd.Timedelta(days = 1)]])
Thanks!
ABB is pandas DataFrame, whose index type is DatetimeIndex.
DatetimeIndex has freq attribute which can be set as below
ABB.index.freq = 'd'
Check out the change
ABB.index
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With