用Python學分析 - 時間序列:線性趨勢及分析

對於平穩時間序列,能夠創建趨勢模型。當有理由相信這種趨勢可以延伸到將來時,賦予變量t所須要的值,能夠獲得相應時刻的時間序列將來值,這就是趨勢外推法ide

【分析實例】spa

根據1992-2005年的人口出生率的數據,使用最小二乘法肯定直線趨勢方程,code

1) 並計算各期的預測值和預測偏差
2) 預測2007年的人口出生率orm

 1 import numpy as np
 2 import pandas as pd
 3 import matplotlib.pyplot as plt
 4 
 5 def Line_Trend_Model( s, ):
 6     '''
 7     使用最小二乘法肯定直線趨勢方程
 8     輸入值:s - pd.Series,index爲連續型日期的Series
 9     返回值類型:字典
10     返回值:a - 截距,b - 斜率, sigma - 估計標準偏差
11     '''
12     res = {}
13     n = len(s)
14     m = 2 # 用於計算估計標準偏差,線性趨勢方程對應的值爲 2
15     res['t'] = [ i+1 for i in range(n)] #對t進行序號化處理
16     avg_t = np.mean(res['t'])
17     avg_y = np.mean(s)
18     ly = sum( map(lambda x,y:x * y, res['t'], s )) - n * avg_t * avg_y
19     lt = sum( map(lambda x:x**2, res['t'])) - n * avg_t ** 2
20     res['b'] = ly/lt #斜率
21     res['a'] = avg_y - res['b'] * avg_t # 截距
22     pre_y = res['a'] + res['b'] * np.array(res['t']) # 直線趨勢線
23     res['sigma'] = np.sqrt(sum(map(lambda x,y:(x - y)**2, s, pre_y ))/(n-m)) # 估計的標準偏差
24     return res
25 
26 # 引入數據
27 data = [ 18.24, 18.09, 17.70, 17.12, 16.98, 16.57, 15.64, 14.64, 14.03, 13.38, 12.86, 12.41, 12.29, 12.40,]
28 dates = pd.date_range('1992-1-1', periods = len(data), freq = 'A') #'A'參數爲每一年的最後一天
29 y = pd.Series( data, index = dates )
30 # 計算值
31 param = Line_Trend_Model( y )
32 pre_y = param['a']+ param['b']* np.array(param['t']) # 趨勢值
33 residual = y - pre_y #殘差
34 db = pd.DataFrame( [ param['t'], data, list(pre_y), list(residual),  list(residual**2)],
35                     index = [ 't','Y(‰)','Trend','Residual','R sqare'],
36                     columns = dates ).T
37 # 輸出結果
38 print('線性趨勢方程擬合過程與結果')
39 print('='*60)
40 print(db)
41 print('='*60)
42 # 計算預測值
43 t = 16
44 yt = param['a']+ param['b']* t
45 print('2007年人口出生率預測值爲 {:.2f}‰'.format(yt))
46 # 畫圖
47 fig = plt.figure( figsize = ( 6, 3 ), facecolor='grey' ) #設置畫布背景色
48 ax=plt.subplot(111,axisbg = '#A9A9A9') # 設置子圖背景色
49 db['Y(‰)'].plot( style = 'bd-',  label = 'Y' )
50 db['Trend'].plot( style = 'ro-', label = 'Trend')
51 legend = ax.legend(loc = 'best',frameon=False ) #雲掉圖例邊框
52 #legend.get_frame().set_facecolor('#A9A9A9')#設置圖例背景色
53 #legend.get_frame().set_edgecolor('#A9A9A9')#設置圖例邊框顏色
54 plt.grid( axis = 'y' )
55 plt.title('1992-2005年人口出生率線性趨勢')
56 
57 plt.show()
View Code

計算結果:blog

 

 

資料來源:劉春英《應用統計學》--中國金融出版社get

相關文章
相關標籤/搜索