You are on page 1of 2

Time series example

Example1-Plotting daily sales


import pandas as pd
import numpy as np
import seaborn as sns#install seaborn before run
import matplotlib.pyplot as plt
Sales=pd.read_excel('D:/Ruwan/Courses/Python/Handouts/DataAnalysis/TimeSeries/SalesData.xlsx',
parse_dates=True,index_col='Date')
sns.lineplot(data=Sales, x='Date', y='Sales', label='Sales', color='blue')
plt.title('Daily Sales')
plt.show()

Because in above example daily data are plotted it is difficult to clearly understand the trend. Therefore
lets resample the dataset in a way that it shows monthly sales.

Example2-Resample and plotting monthly sales


import pandas as pd
import numpy as np
import seaborn as sns#install seaborn before run
import matplotlib.pyplot as plt
Sales=pd.read_excel('D:/Ruwan/Courses/Python/Handouts/DataAnalysis/TimeSeries/SalesData.xlsx',
parse_dates=True,index_col='Date')
resampled_Sales = Sales.resample('M').mean()#resample by calculating mean values of months
print(resampled_Sales.head(10))#print first 10 records
sns.lineplot(data=resampled_Sales, x=resampled_Sales.index, y='Sales',
label='Monthly Sales', color='blue')#plot monthly sales
plt.title('Monthly Sales')
plt.show()

To smooth the line more lets calculate moving average and plot moving average sales and monthly
sales.

Example3-Daily sales vs moving average sales


import pandas as pd
import numpy as np
import seaborn as sns#install seaborn before run
import matplotlib.pyplot as plt
Sales=pd.read_excel('D:/Ruwan/Courses/Python/Handouts/DataAnalysis/TimeSeries/SalesData.xlsx',
parse_dates=True,index_col='Date')
resampled_Sales = Sales.resample('M').mean()#resamply by calculating mean values of months
Sales['smoothedSales'] = Sales['Sales'].rolling(window=120).mean()#Calculate moving average and store
them in a new column
sns.lineplot(data=Sales, x=Sales.index, y='Sales',label='Daily Sales', color='blue')#plot daily sales
sns.lineplot(data=Sales, x=Sales.index, y='smoothedSales',label='Moving average Sales', color='red')#plot
moving sales#plt.title('Monthly Sales')
plt.title('Daily Sales vs Moving Average')
plt.show()

You might also like