计量经济与时间序列_自协方差(AutoCovariance)算法解析(Python)
Posted 时海涛 | Thomas.Shih
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计量经济与时间序列_自协方差(AutoCovariance)算法解析(Python)相关的知识,希望对你有一定的参考价值。
1 样本的自协方差函数的通式如下:
2 其实,后面要计算的自相关函数也可以用自协方差来表示:
1 # @author: "Thomas.Shih" 2 # @date: 2018/3/5 0005 3 # !/usr/bin/python3 4 # -*- coding:utf-8 -*- 5 TimeSeries = [11.67602657, 5.637492979, 1.375516942, 0.618705492, -0.152047234, -0.508555434, -6.065288121, -9.417602801, \\ 6 -10.47205437, -8.018063902, 0.523277554, 4.86893283, 4.23977562, -10.2344375, -3.463362573, 36.51326577, \\ 7 -8.518370963, -15.37474905, -7.687911176, 4.818978874, 7.876681639, 1.763788865] 8 Zt = [] 9 LZt = [] 10 AutoCovariance = [] 11 # 自协方差存为列表形式,显示格式如下: 12 # [γ0,γ1,γ2,γ3,....] 13 # [γk,....] k = 0,1,2,3.... 14 total = 0 15 i = 1 16 while i < len(TimeSeries): 17 L = TimeSeries[i::] 18 LL = TimeSeries[:-i:] 19 total = total + TimeSeries[i - 1] 20 Zt.append(L) 21 LZt.append(LL) 22 i += 1 23 total = total + TimeSeries[-1] 24 avg = total / len(TimeSeries) 25 26 k = 0 27 result_temp0 = 0 28 # 首先求γ0的值 29 while k < len(TimeSeries): 30 result_temp0 = result_temp0 + pow((TimeSeries[k] - avg), 2) 31 k += 1 32 AutoCovariance.append(result_temp0/len(TimeSeries)) 33 # print(AutoCovariance) 34 # 显示结果: 35 #[2418.4380925669107] 36 37 # 然后计算分子 38 p = 0 39 q = 0 40 length = 0 41 while p < len(Zt): 42 q = 0 43 result_temp1 = 0 44 while q < len(Zt[p]): 45 result_temp1 = result_temp1 + (Zt[p][q] - avg) * (LZt[p][q] - avg) 46 q += 1 47 # print(result_temp1) 48 # print(len(Zt)-p) 49 AutoCovariance.append(result_temp1/len(TimeSeries)) 50 p += 1 51 print(AutoCovariance) 52 # print(len(AutoCovariance)) 53 # print(len(Zt)) 54 55 # 显示结果: 56 # [109.92900420758684, 7.033249208759847, -41.331023616868386, -9.818640497993421, 17.321104958520728, 11.540453909308482, 57 # -20.71675731505552, -23.35193308926872, -10.671711257152637, 2.3511837591142006, 12.09337228027552, 5.284907080510467, 58 # -3.4833058404578527, -9.53177380894126, 3.568570997073478, 15.31665885468035, -8.901077316598432, -9.619216801963882, 59 # -2.303250941136475, 4.686244739096256, 4.632349610445184, 0.9360929838586473]
以上是关于计量经济与时间序列_自协方差(AutoCovariance)算法解析(Python)的主要内容,如果未能解决你的问题,请参考以下文章
计量经济与时间序列_时间序列分析的几个基本概念(自相关函数,偏自相关函数等)