Python for Finance: Analyze Big Financial Data

(Elle) #1

Using the DatetimeIndex constructor also allows the opposite operation:


In  [ 74 ]: pd.DatetimeIndex(pdi)
Out[74]: <class ‘pandas.tseries.index.DatetimeIndex’>
[2016-01-31, ..., 2016-12-31]
Length: 12, Freq: None, Timezone: None

In the case of NumPy datetime64 objects, the astype method has to be used:


In  [ 75 ]: pd.DatetimeIndex(dtl.astype(pd.datetime))
Out[75]: <class ‘pandas.tseries.index.DatetimeIndex’>
[2015-12-31 23:00:00, ..., 2016-01-01 22:00:00]
Length: 24, Freq: None, Timezone: None

pandas takes care of proper plotting of date-time information (see Figure C-2 and also


Chapter 6):


In  [ 76 ]: rnd =   np.random.standard_normal(len(dti)).cumsum()    **   2
In [ 77 ]: df = pd.DataFrame(rnd, columns=[‘data’], index=dti)
In [ 78 ]: df.plot()

Figure C-2. pandas plot with Timestamp x-ticks autoformatted

pandas also integrates well with the pytz module to manage time zones:


In  [ 79 ]: pd.date_range(‘2016/01/01’, freq=‘M’,   periods= 12 ,
tz=pytz.timezone(‘CET’))
Out[79]: <class ‘pandas.tseries.index.DatetimeIndex’>
[2016-01-31 00:00:00+01:00, ..., 2016-12-31 00:00:00+01:00]
Length: 12, Freq: M, Timezone: CET
In [ 80 ]: dti = pd.date_range(‘2016/01/01’, freq=‘M’, periods= 12 , tz=‘US/Eastern’)
dti
Out[80]: <class ‘pandas.tseries.index.DatetimeIndex’>
[2016-01-31 00:00:00-05:00, ..., 2016-12-31 00:00:00-05:00]
Length: 12, Freq: M, Timezone: US/Eastern

Using the tz_convert method, DatetimeIndex objects can be transformed from one time


zone to another:


In  [ 81 ]: dti.tz_convert(‘GMT’)
Out[81]: <class ‘pandas.tseries.index.DatetimeIndex’>
[2016-01-31 05:00:00+00:00, ..., 2016-12-31 05:00:00+00:00]
Length: 12, Freq: M, Timezone: GMT

[ 85 ]

For more information on this module, see the online documentation.
Free download pdf