<jupyter_start><jupyter_text>Let Moving Average to be defined as below:$MA_n = \frac{1}{n}\sum_{i=1}^{n}X_i$,where n is the number of observations in the time frame to be averaged, and X is the observation in the dataset.Based on this equation, complete  the `movAvg` function below.For your reference, please read [this page](https://www.investopedia.com/terms/m/movingaverage.asp) for better understanding of moving average.<jupyter_code># movAvg takes 'l', which is pandas Series, and 'n', an integer, as two parameters.
# Returns: A moving averaged list of 'l'
# For index < n - 1, l[index] = average from l[0] to l[index]
# Else, l[index] = average from l[index - n + 1] to l[index]
# Note that for colon operator, end is non-inclusive! 
# TODO: Make the cell print 'True' for all test cases

# Your code goes below here!
def movAvg(l: pd.Series, n: int) -> list:
    l = l.to_list()
    ret = []
    for i in range(len(l)):
        if i < n - 1:
            ret.append(sum(l[:i+1])/len(l[:i+1]))
        else: ret.append(sum(l[i - n + 1 : i + 1])/len(l[i - n + 1 : i + 1]))
    return ret




# Do not modify below!
ret = movAvg(apple['Close'], 7)
print(ret[5] == sum(apple['Close'].iloc[:6])/6)
print(ret[7] == apple['Close'].rolling(7).mean().iloc[7])
# Using the 'movAvg' written above, create a 30-days moving averaged data of apple['Close']
# Based on the returned data, create a new column in apple titled 'CloseMovAvg'
# TODO: Make the cell print 'True' for all test cases

# Your code goes below here!
apple['CloseMovAvg'] = movAvg(apple['Close'], 30)






# Do not modify below!
print(round(apple['CloseMovAvg'].iloc[100], 5) == round(apple['Close'].rolling(30).mean().iloc[100], 5))
# If you have not installed 'ipympl' before, this cell will restart your kernel.
# If so, please run all the cells above again

try:
    import ipympl
except:
    !pip install ipympl
    try:
        !pip3 install ipympl
    except: pass
    import os
    os._exit(00)
# Set the figsize as (10, 5)
# Create a plot with x = 'Date' and y = 'CloseMovAvg', and label it as 'MovAvg'
# Create a plot with x = 'Date' and y = 'Close', and label it as 'Close'
# Set x label, y label and title of the graph accordingly
# Show legend
# TODO: Create a grapth with two plots and axes, graph titles
%matplotlib widget

# Your code goes below here!



plt.figure(figsize = (10, 5))
plt.plot(apple['Date'], apple['CloseMovAvg'], label = 'MovAvg')
plt.plot(apple['Date'], apple['Close'], label = 'Close')
plt.title('Apple Stock Daily Price Range')
plt.xlabel("Date")
plt.ylabel("Range")
plt.legend()
# Create a function that takes two pandas Series, 'date' and 'data', as inputs
# And returns a dictionary thats keys are months and values are average data for each months
# for 'date' and 'data', same index refers to the data from the same date
# i.e. if date.iloc[0] is 2000-01-01, data.iloc[0] is the data in 2000-01-01
# TODO: Make the cell print 'True' for all test cases
# Hint: to retrieve a month from pd.Timestamp object, use '.month'
# i.e. apple['Date'].iloc[0].month returns 10

# Your code goes below here!
def monthAvgDict(date: pd.Series, data: pd.Series) -> dict:
    date = date.to_list()
    data = data.to_list()
    date = [i.month for i in date]
    ret = {}
    for i in range(len(date)):
        if date[i] not in ret:
            ret.update({date[i]:[]})
        ret[date[i]].append(data[i])
    
    ret = {i:sum(ret[i])/len(ret[i]) for i in ret}
    return ret







# Do not modify below!
print(monthAvgDict(pd.Series([pd.Timestamp(2000, 1, 1) if i % 2 == 0 else pd.Timestamp(2000, 2, 1) for i in range(10)]), pd.Series([i for i in range(1,11)]))[1] == 5)
print(len(monthAvgDict(apple['Date'], apple['Close'])) == 12)<jupyter_output>True
True<jupyter_text>Now, based on the `monthAvgDict` we have created above, lets observe how the average stock price of Apple differ by month.Based on the data returned from `monthAvgDict`, we will create a bar chart.To read more about the bar chart in matplotlib, please refer to [this page](https://pythonbasics.org/matplotlib-bar-chart/).<jupyter_code># pass 'apple['Date']' and 'apple['Close'] to 'monthAvgDict' created above, 
# and create two lists, 'month' and 'avg_close' based on the returned dictionary
# Using two lists, graph a bar plot of the average closing price of Apple by month.
# Set the figsize as (10, 5)
# Set x label, y label and title of the graph accordingly
# TODO: Create a bar plot with axes, graph titles

# Your code goes below here!
ret = monthAvgDict(apple['Date'], apple['Close'])
month, avg_close = list(ret.keys()), list(ret.values())
plt.figure(figsize = (10, 5))
plt.bar(month, avg_close)
plt.xlabel("Month")
plt.ylabel("Average Close price ($)")
plt.title("Apple Average Close Price by Month")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1374792013311148, 'fraction_numerical': 0.01913477537437604, 'mean_word_length': 4.056782334384858, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 2, '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': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '103771', 'license': 'MIT', 'n_tokens_mistral': 1699, 'n_tokens_neox': 1583, 'n_words': 610, 'path': 'Week 6/Week 6 Tasks Answer.ipynb', 'repo_name': 'jihoonkang0829/Codable_FA20', 'size': '4808'}