<jupyter_start><jupyter_text>Code along with this notebookhttps://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.11-Working-with-Time-Series.ipynb Working with Time Series<jupyter_code>from datetime import datetime
datetime(year=2015, month=7, day=4)
from dateutil import parser
date = parser.parse("4th of July, 2015")
date
date.strftime('%A')
import numpy as np
date = np.array('2015-07-04', dtype=np.datetime64)
date<jupyter_output><empty_output><jupyter_text>Once we have this date formatted, however, we can quickly do vectorized operations on it:<jupyter_code>date + np.arange(12)
# Date based datetime
np.datetime64('2015-07-04')
# Minute based datetime
np.datetime64('2015-07-04 12:00')
# nano second based datetime
np.datetime64('2015-07-04 12:59:59.50', 'ns')<jupyter_output><empty_output><jupyter_text>Dates and times in pandas: best of both worlds<jupyter_code>import pandas as pd
date = pd.to_datetime("4th of July, 2015")
date
date.strftime('%A')<jupyter_output><empty_output><jupyter_text>Additionally, we can do NumPy-style vectorized operations directly on this same object:<jupyter_code>date + pd.to_timedelta(np.arange(12), 'D')
index = pd.DatetimeIndex(['2014-07-04', '2014-08-04',
                          '2015-07-04', '2015-08-04'])
data = pd.Series([0, 1, 2, 3], index=index)
data
data['2014-07-04':'2015-07-04']
data['2015']<jupyter_output><empty_output><jupyter_text>Pandas Time Series Data Structures<jupyter_code>dates = pd.to_datetime([datetime(2015, 7, 3), '4th of July, 2015',
                       '2015-Jul-6', '07-07-2015', '20150708'])
dates
dates.to_period('D')
dates - dates[0]<jupyter_output><empty_output><jupyter_text>Regular sequences: pd.date_range()<jupyter_code>pd.date_range('2015-07-03', '2015-07-10')
pd.date_range('2015-07-03', periods=8)
pd.date_range('2015-07-03', periods=8, freq='H')
pd.period_range('2015-07', periods=8, freq='M')
pd.timedelta_range(0, periods=10, freq='H')<jupyter_output><empty_output><jupyter_text>Frequencies and Offsets On top of this, codes can be combined with numbers to specify other frequencies. For example, for a frequency of 2 hours 30 minutes, we can combine the hour (H) and minute (T) codes as follows:<jupyter_code>pd.timedelta_range(0, periods=9, freq="2H30T")
from pandas.tseries.offsets import BDay
pd.date_range('2015-07-01', periods=5, freq=BDay())<jupyter_output><empty_output><jupyter_text>Resampling, Shifting, and Windowing<jupyter_code>from pandas_datareader import data

goog = data.DataReader('GOOG', start='2004', end='2016',
                       data_source='google')
goog.head()
goog = goog['Close']
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn; seaborn.set()
goog.plot();
goog.plot(alpha=0.5, style='-')
goog.resample('BA').mean().plot(style=':')
goog.asfreq('BA').plot(style='--');
plt.legend(['input', 'resample', 'asfreq'],
           loc='upper left');
fig, ax = plt.subplots(2, sharex=True)
data = goog.iloc[:10]

data.asfreq('D').plot(ax=ax[0], marker='o')

data.asfreq('D', method='bfill').plot(ax=ax[1], style='-o')
data.asfreq('D', method='ffill').plot(ax=ax[1], style='--o')
ax[1].legend(["back-fill", "forward-fill"]);
fig, ax = plt.subplots(3, sharey=True)

# apply a frequency to the data
goog = goog.asfreq('D', method='pad')

goog.plot(ax=ax[0])
goog.shift(900).plot(ax=ax[1])
goog.tshift(900).plot(ax=ax[2])

# legends and annotations
local_max = pd.to_datetime('2007-11-05')
offset = pd.Timedelta(900, 'D')

ax[0].legend(['input'], loc=2)
ax[0].get_xticklabels()[2].set(weight='heavy', color='red')
ax[0].axvline(local_max, alpha=0.3, color='red')

ax[1].legend(['shift(900)'], loc=2)
ax[1].get_xticklabels()[2].set(weight='heavy', color='red')
ax[1].axvline(local_max + offset, alpha=0.3, color='red')

ax[2].legend(['tshift(900)'], loc=2)
ax[2].get_xticklabels()[1].set(weight='heavy', color='red')
ax[2].axvline(local_max + offset, alpha=0.3, color='red');
ROI = 100 * (goog.tshift(-365) / goog - 1)
ROI.plot()
plt.ylabel('% Return on Investment');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1822429906542056, 'fraction_numerical': 0.07329070339399901, 'mean_word_length': 6.275491949910554, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '567935', 'license': 'Apache-2.0', 'n_tokens_mistral': 1735, 'n_tokens_neox': 1526, 'n_words': 295, 'path': 'unit-5.4/Unit-5.4.3-TimeSeriesData.ipynb', 'repo_name': 'weboctave/ml-bootcamp', 'size': '4066'}