<jupyter_start><jupyter_text>______Copyright <NAME>For more information, visit us at www.pieriandata.com  Rolling and ExpandingA common process with time series is to create data based off of a rolling mean. The idea is to divide the data into "windows" of time, and then calculate an aggregate function for each window. In this way we obtain a simple moving average. Let's show how to do this easily with pandas!<jupyter_code>import pandas as pd
%matplotlib inline
# Import the data:
df = pd.read_csv('../Data/starbucks.csv', index_col='Date', parse_dates=True)
df.head()
df['Close'].plot(figsize=(12,5)).autoscale(axis='x',tight=True);<jupyter_output><empty_output><jupyter_text>Now let's add in a rolling mean! This rolling method provides row entries, where every entry is then representative of the window.<jupyter_code># 7 day rolling mean
df.rolling(window=7).mean().head(15)
df['Close'].plot(figsize=(12,5)).autoscale(axis='x',tight=True)
df.rolling(window=30).mean()['Close'].plot();<jupyter_output><empty_output><jupyter_text>The easiest way to add a legend is to make the rolling value a new column, then pandas does it automatically!<jupyter_code>df['Close: 30 Day Mean'] = df['Close'].rolling(window=30).mean()
df[['Close','Close: 30 Day Mean']].plot(figsize=(12,5)).autoscale(axis='x',tight=True);<jupyter_output><empty_output><jupyter_text>ExpandingInstead of calculating values for a rolling window of dates, what if you wanted to take into account everything from the start of the time series up to each point in time? For example, instead of considering the average over the last 7 days, we would consider all prior data in our expanding set of averages.<jupyter_code># df['Close'].plot(figsize=(12,5)).autoscale(axis='x',tight=True)

# Optional: specify a minimum number of periods to start from
df['Close'].expanding(min_periods=30).mean().plot(figsize=(12,5));<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12035583464154893, 'fraction_numerical': 0.015698587127158554, 'mean_word_length': 6.966666666666667, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, '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': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '83072', 'license': 'Apache-2.0', 'n_tokens_mistral': 605, 'n_tokens_neox': 574, 'n_words': 201, 'path': 'tsa/jose/UDEMY_TSA_FINAL (1)/04-Time-Series-with-Pandas/03-Rolling-and-Expanding.ipynb', 'repo_name': 'juspreet51/ml_templates', 'size': '1917'}