基于python的数据分解-趋势-季节性-波动变化

系列文章目录


前言

时间序列数据的分解,一般分为趋势项,季节变化项和随机波动项。可以基于加法或者乘法模型。季节变化呈现出周期变化,因此也叫季节效应(周期)。

一、数据分解步骤

(1)估计时间序列的长期趋势,一种是通过数据平滑方式进行估计;一种是通过模拟回归方程进行估计;
(2)去掉时间序列数据的长期趋势。 加法模型则减去,乘法模型即除去;
(3)去掉长期趋势的时间序列数据,估计时间序列的季节变化;
(4)剩下的即为随机波动项;

二、使用步骤

1.数据分解方法

import os
#移动平均法
os.chdir("D:/Pythonmatlab学习资料/") 
#改变工作目录
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
import numpy as np

from statsmodels.tsa.seasonal import seasonal_decompose

traveller_df = pd.read_csv("NZTravellersDestination.csv", usecols=['Date','China'], parse_dates=['Date'], index_col='Date')

deco_muti = seasonal_decompose(traveller_df, model='mutiplicative', extrapolate_trend='freq')

new,(ax1,ax2,ax3,ax4) = plt.subplots(4, 1, sharex=True, figsize=(12,8), dpi=150)
ax1.plot(deco_muti.observed, color='r')
ax1.set_ylabel(ylabel="Observed", fontsize=15)
ax2.plot(deco_muti.trend, color='b')
ax2.set_ylabel(ylabel="Trend", fontsize=15)
ax3.plot(deco_muti.seasonal, color='g')
ax3.set_ylabel(ylabel="Seasonal", fontsize=15)
ax4.plot(deco_muti.resid, color='b')
ax4.set_ylabel(ylabel="Resid", fontsize=15)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
plt.tight_layout(); plt.savefig(fname='fig/4_1.png')

deco_value = pd.concat([deco_muti.trend, deco_muti.seasonal, deco_muti.resid, deco_muti.observed], axis=1)
deco_value.columns = ['trend', 'season', 'resid', 'actual_values']
deco_value.head()
##%

2.分解项计算方法


import statsmodels.formula.api as smf
#表示线性拟合计算趋势
df = np.loadtxt("elec_prod.txt")
t = np.arange(1,397)

df_t = np.vstack((df,t)).swapaxes(0,1).astype(int)
model_data = pd.DataFrame(df_t,columns=['df','t'])

results_f = smf.ols('df~t',data=model_data).fit()
print(results_f.summary().tables[1])
print('std = ',np.std(results_f.resid))

fig = plt.figure(figsize=(12,4), dpi=150)
ax = fig.add_subplot(111)
ax.plot(model_data, linestyle="-", color='red')
ax.plot(t,1.423e+05 + 499.2576*t, color='blue')
ax.set_ylim((130000, 410000))
ax.set_ylabel(ylabel="Electricity", fontsize=17)
ax.set_xlabel(xlabel="Time", fontsize=17)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_2.png')

##%表示曲线拟合计算趋势
df = pd.read_excel('ningxiaGDP.xlsx').rename(columns={'t':'t1'})
df = pd.DataFrame(df['t1'].values**2,columns=['t2']).join(df)

results_f = smf.ols('gdp~ 0 + t1+ t2', data=df).fit()
print(results_f.summary().tables[1])
print('std = ', np.std(results_f.resid))

from scipy.optimize import curve_fit

df = pd.read_excel('ningxiaGDP.xlsx')
t = df['t'].values
gdp = df['gdp'].values

def func(x, b,c):
   return b*x + c*x**2

popt, pcov = curve_fit(func,t,gdp,p0=(1.0,1.0))
print(popt)

b = popt[0]
c = popt[1]
residuals = gdp - func(t, b, c)
print(np.std(residuals))

t = np.arange(1996, 2016)

fig = plt.figure(figsize=(12,4),dpi=150)
ax = fig.add_subplot(111)
ax.scatter(y=gdp, x=t, color='blue')
ax.plot(t, results_f.predict())
ax.xaxis.set_major_locator(ticker.MultipleLocator(3))
ax.set_ylabel(ylabel="宁夏地区生产总值",fontsize=17)
ax.set_xlabel(xlabel="时间", fontsize=17)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_3.png')

##%表示5期移动平均拟合,移动平均法计算趋势
from statsmodels.tsa.seasonal import seasonal_decompose
nile_ar = np.loadtxt("Nile.txt"); Date = np.arange(1871, 1971)
nile_df = pd.DataFrame({"Date":Date, "Nile":nile_ar})
nile_df.index = nile_df["Date"]

nile_df['5-period Moving Avg'] = nile_df['Nile'].rolling(5).mean()

fig = plt.figure(figsize=(12,4), dpi=150)
ax = fig.add_subplot(111)
nile_df['Nile'].plot(ax=ax, color='b', marker="o", linestyle='--')
nile_df['5-period Moving Avg'].plot(ax=ax, color='r')
ax.legend(loc=1,labels=['Index','Moving average'], fontsize=13)
ax.set_ylabel(ylabel="Index", fontsize=17)
ax.set_xlabel(xlabel="Time", fontsize=17)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_4.png')

#%%二次移动平均法计算趋势
gdp_df = pd.read_csv('JDGDP.csv')

gdp_df['Moving_Avg_1'] = gdp_df['JDGDP'].rolling(4).mean()
gdp_df['Moving_Avg_2'] = gdp_df['Moving_Avg_1'].rolling(4).mean()

gdp_df['at'] = 2*gdp_df['Moving_Avg_1'] - gdp_df['Moving_Avg_2']

fig = plt.figure(figsize=(12,4),dpi=150)
ax = fig.add_subplot(111)
gdp_df['JDGDP'].plot(ax=ax, color='b',marker="o",linestyle='--')
gdp_df['at'].plot(ax=ax, color='r')
ax.xaxis.set_major_locator(ticker.MultipleLocator(3))
ax.legend(loc=2,labels=['季度GDP','两次移动平均'], fontsize=13)
ax.set_ylabel(ylabel="中国季度国内生产总值", fontsize=17)
ax.set_xlabel(xlabel="时间", fontsize=17)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_5.png')

##%指数平滑法,考虑近期变化对现在影响较大,而远期的变化对现在影响要小一些
from statsmodels.tsa.api import SimpleExpSmoothing
df = np.loadtxt("retail_price_index.txt")
index = pd.date_range(start="1990", end="2021", freq="A")
retail_df = pd.Series(df, index)

fit1 = SimpleExpSmoothing(retail_df, initialization_method="heuristic").fit(smoothing_level=0.2, optimized=False)
fcast1 = fit1.forecast(3).rename(r"α=0.2")

fit2 = SimpleExpSmoothing(retail_df, initialization_method="heuristic").fit(smoothing_level=0.6, optimized=False)
fcast2 = fit2.forecast(3).rename(r"α=0.6")

fit3 = SimpleExpSmoothing(retail_df, initialization_method="estimated").fit()
fcast3 = fit3.forecast(3).rename(r"α=
"% fit3.model.params["smoothing_level"] )
fig = plt.figure(figsize=(12,4), dpi=150)
ax = fig.add_subplot(111)
ax.plot(retail_df, marker="o", color="black")
ax.plot(fit1.fittedvalues, marker="8", color="green",linestyle="-.")
(line1,) = ax.plot(fcast1, marker="8", color="green",linestyle="-.")
ax.plot(fit2.fittedvalues, marker="s", color="red",linestyle=":")
(line2,) = ax.plot(fcast2, marker="s", color="red",linestyle=":")
ax.plot(fit3.fittedvalues, marker="p", color="blue",linestyle="--")
(line3,) = ax.plot(fcast3, marker="p", color="blue",linestyle="--")
plt.legend([line1, line2, line3], [fcast1.name, fcast2.name, fcast3.name], fontsize=15)
ax.set_ylabel(ylabel="商品零售价格指数", fontsize=17)
ax.set_xlabel(xlabel="时间", fontsize=17)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_6.png')

##%对于含有季节变动部分的时间序列为Holt-Winters指数平滑法
from statsmodels.tsa.api import ExponentialSmoothing
df = np.loadtxt("QGDP.txt")
index = pd.date_range(start="2000", end="2021", freq="Q")
QGDP_df = pd.Series(df, index)

fit = ExponentialSmoothing(QGDP_df, seasonal_periods=4, trend="add", seasonal="mul",initialization_method="estimated").fit()
simulations = fit.simulate(8, repetitions=1000, error="mul")

fig = plt.figure(figsize=(12,4), dpi=150)
ax = fig.add_subplot(111)
ax.plot(QGDP_df, marker="o", color="black")
ax.plot(fit.fittedvalues, marker="o", color="blue", linestyle=":")
ax.plot(simulations, marker="o", color="blue", linestyle=":")
ax.set_ylabel(ylabel="国内季度生产总值累计值", fontsize=17)
ax.set_xlabel(xlabel="时间",fontsize=17)
plt.xticks(fontsize=15); plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_8.png')

##%季节效应,季节指数,用简单平均法计算的周期内各时期季节性影响的相对数。
df = np.loadtxt("tempdub.txt")
index = pd.date_range(start="1964", end="1976", freq="M")
tempdub_df = pd.Series(df, index)

fig = plt.figure(figsize=(12,4), dpi=150)
ax = fig.add_subplot(111)
ax.plot(tempdub_df, marker="o", color="blue")
ax.set_ylabel(ylabel="杜比克市月平均气温",fontsize=17)
ax.set_xlabel(xlabel="时间",fontsize=17)
plt.xticks(fontsize=15);plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_9.png')

t = np.arange(1,13)
SI = np.array([0.36,0.45,0.7,1.00,1.26,1.46,1.55,1.50,1.32,1.10,0.79,0.51])
Season_index = pd.Series(SI, t)

fig = plt.figure(figsize=(12,4), dpi=150)
ax = fig.add_subplot(111)
ax.plot(Season_index, marker="o", color="blue")
ax.set_ylabel(ylabel="季节指数",fontsize=17)
ax.set_xlabel(xlabel="时间",fontsize=17)
plt.xticks(fontsize=15);plt.yticks(fontsize=15)
fig.tight_layout(); plt.savefig(fname='fig/4_10.png')


出图

分解效果在这里插入图片描述在这里插入图片描述
在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述参考书籍
基于Python的时间序列分析

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/779977.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

拓扑排序,PageRank(markov),实对称矩阵等

拓扑排序 多件事情有先后顺序,如何判断哪个先哪个后 拓扑排序算法: 1.读入图时,需要记录每个顶点的入度,以及相邻的所有顶点 2.将入度为0的顶点入队(先进先出) 3.取出队首元素a,&#xf…

rocketmq-console可视化界面功能说明

rocketmq-console可视化界面功能说明 登录界面OPS(运维)Dashboard(驾驶舱)Cluster(集群)Topic(主题)Consumer(消费者)Producer(生产者)Message(消息)MessageTrace(消息轨迹) rocketmq-console是rocketmq的一款可视化工具,提供了mq的使用详情等功能。 本章针对于rock…

基于springboot+vue+uniapp的高校宿舍信息管理系统小程序

开发语言:Java框架:springbootuniappJDK版本:JDK1.8服务器:tomcat7数据库:mysql 5.7(一定要5.7版本)数据库工具:Navicat11开发软件:eclipse/myeclipse/ideaMaven包&#…

springboot + mybatis 多数据源切换

参考的b站博主写的 配置文件: spring:datasource:db1:jdbc-url: jdbc:mysql://localhost:3306/interview_database?useUnicodetrue&characterEncodingutf-8&useSSLfalseusername: rootpassword: 12345driver-class-name: com.mysql.cj.jdbc.Driverdb2:jdbc-url: jdbc…

rancher管理多个集群

一、rancher部署 单独部署到一台机器上,及独立于k8s集群之外: 删除所有yum源,重新建yum源: # 建centos7.9的yum源 # cat CentOS-Base.repo # CentOS-Base.repo # # The mirror system uses the connecting IP address of the …

花所Flower非小号排名20名下载花所Flower

1、Flower花所介绍 Flower花所是一家新兴的数字货币交易平台,致力于为全球用户提供安全、便捷的交易体验。平台以其强大的技术支持和丰富的交易产品闻名,为用户提供多样化的数字资产交易服务,涵盖了主流和新兴数字货币的交易需求。 2. Flowe…

wordpress企业网站模板免费下载

大气上档次的wordpress企业模板,可以直接免费下载,连注册都不需要,网盘就可以直接下载,是不是嘎嘎给力呢 演示 https://www.jianzhanpress.com/?p5857 下载 链接: https://pan.baidu.com/s/1et7uMYd6--NJEWx-srMG1Q 提取码:…

【Python】已解决:nltk.download(‘stopwords‘) 报错问题

文章目录 一、分析问题背景二、可能出错的原因三、错误代码示例四、正确代码示例五、注意事项 已解决:nltk.download(‘stopwords’) 报错问题 一、分析问题背景 在使用Python的自然语言处理库NLTK(Natural Language Toolkit)时&#xff0c…

《向量数据库指南》——Milvus Cloud检索器增强的深度探讨:句子窗口检索与元数据过滤

检索器增强的深度探讨:句子窗口检索与元数据过滤 在信息爆炸的时代,高效的检索系统成为了连接用户与海量数据的关键桥梁。为了进一步提升检索的准确性和用户满意度,检索器增强技术应运而生,其中句子窗口检索与元数据过滤作为两大…

每日一题~oj(贪心)

对于位置 i来说,如果 不选她,那她的贡献是 vali-1 *2,如果选他 ,那么她的贡献是 ai. 每一个数的贡献 是基于前一个数的贡献 来计算的。只要保证这个数的前一个数的贡献是最优的,那么以此类推下去,整体的val…

基于自编码器的时间序列异常检测方法(以传感器数据为例,MATLAB R2021b)

尽管近年来研究者对自编码器及其改进算法进行了深入研究,但现阶段仍存在以下问题亟须解决。 1) 无监督学习模式对特征提取能力的限制与有监督学习相比,无监督学习模式摆脱了对样本标签的依赖、避免了人工标注的困难,但也因此失去了样本标签的…

vue3+vite搭建第一个cesium项目详细步骤及环境配置(附源码)

文章目录 1.创建vuevite项目2.安装 Cesium2.1 安装cesium2.2 安装vite-plugin-cesium插件(非必选)2.3 新建组件页面map.vue2.4 加载地图 3.完成效果图 1.创建vuevite项目 打开cmd窗口执行以下命令:cesium-vue-app是你的项目名称 npm create…

Zkeys三方登录模块支持QQ、支付宝登录

1,覆盖到根目录,并导入update.sql数据库文件到Zkeys数据库里 2. 后台系统权限管理,配置管理员权限-系统类别-找到云外科技,全部打勾 3,后台系统设置找到云外快捷登录模块填写相应的插件授权配置和登录权限配置&#x…

【wordpress教程】wordpress博客网站添加非法关键词拦截

有的网站经常被恶意搜索,站长们不胜其烦。那我们如何屏蔽恶意搜索关键词呢?下面就随小编一起来解决这个问题吧。 后台设置预览图: 设置教程: 1、把以下代码添加至当前主题的 functions.php 文件中: add_action(admi…

Arcgis Api 三维聚合支持最新版API

Arcgis Api 三维聚合支持最新版API 最近有同学问我Arcgis api 三维聚合,官方还不支持三维聚合API,二维可以。所以依旧是通过GraphicLayers 类来实现,可支持最新Arcgis Api版本 效果图:

简单且循序渐进地查找软件中Bug的实用方法

“Bug”这个词常常让许多开发者感到头疼。即使是经验丰富、技术娴熟的开发人员在开发过程中也难以避免遭遇到 Bug。 软件中的故障会让程序员感到挫败。我相信在你的软件开发生涯中,也曾遇到过一些难以排查的问题。软件中的错误可能会导致项目无法按时交付。因此&…

初识STM32:芯片基本信息

STM32简介 STM32是ST公司基于ARM公司的Cortex-M内核开发的32位微控制器。 ARM公司是全球领先的半导体知识产权(IP)提供商,全世界超过95%的智能手机和平板电脑都采用ARM架构。 ST公司于1987年由意大利的SGS微电子与法国的Thomson半导体合并…

linux软链接和硬链接的区别

1 创建软链接和硬链接 如下图所示,一开始有两个文件soft和hard。使用 ln -s soft soft1创建软链接,soft1是soft的软链接;使用ln hard hard1创建硬链接,hard1是hard的硬链接。可以看到软链接的文件类型和其它3个文件的文件类型是不…

从“移花接木”到“提质增效”——详解嫁接打印技术

嫁接打印,是融合了3D打印与传统制造精髓的创新技术,其核心在于,通过巧妙地将传统模具加工与先进的3D打印技术相结合,实现了模具制造的“提质、增效、降本”。 嫁接打印的定义 简而言之,嫁接打印是一种增减材混合制造的…

uniapp报错--app.json: 在项目根目录未找到 app.json

【问题】 刚创建好的uni-app项目,运行微信小程序控制台报错如下: 【解决方案】 1. 程序根目录打开project.config.json文件 2. 配置miniprogramRoot,指定小程序代码的根目录 我的小程序代码编译后的工程文件目录为:dist/dev/mp…