• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python stattools.pacf函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中statsmodels.tsa.stattools.pacf函数的典型用法代码示例。如果您正苦于以下问题:Python pacf函数的具体用法?Python pacf怎么用?Python pacf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了pacf函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_ld

    def test_ld(self):
        pacfyw = pacf_yw(self.x, nlags=40, method="mle")
        pacfld = pacf(self.x, nlags=40, method="ldb")
        assert_almost_equal(pacfyw, pacfld, DECIMAL_8)

        pacfyw = pacf(self.x, nlags=40, method="yw")
        pacfld = pacf(self.x, nlags=40, method="ldu")
        assert_almost_equal(pacfyw, pacfld, DECIMAL_8)
开发者ID:joesnacks,项目名称:statsmodels,代码行数:8,代码来源:test_stattools.py


示例2: get_acf_pacf

 def get_acf_pacf(self, inputDataSeries, lag = 15):
     # Copy the data in input data
     outputData = pandas.DataFrame(inputDataSeries)
     
     if min(inputDataSeries.index) == inputDataSeries.index[0]:
         # Ascending
         multiplier = 1
         lag = multiplier*lag
     elif max(inputDataSeries.index) == inputDataSeries.index[0]:
         # Descending
         multiplier = -1
         lag = multiplier*lag
     else:
         print('Cannot determine the order put the lag value manually')
         print('Syntax: calc_returns(inputData, columnName, lag = lag_value)')
     
     n_iter = lag
     columnName = outputData.columns[0]
     i = 1
     
     
     # Calculate ACF
     acf_values = []
     acf_values.append(outputData[columnName].corr(outputData[columnName]))
     
     while i <= abs(n_iter):
         col_name = 'lag_' + str(i)
         outputData[col_name] = ''
         outputData[col_name] = outputData[columnName].shift(multiplier*i)
         
         i += 1
         
         acf_values.append(outputData[columnName].corr(outputData[col_name]))
     
     # Define an emplty figure
     fig = plt.figure()
     
     # Define 2 subplots
     ax1 = fig.add_subplot(211) # 2 by 1 by 1 - 1st plot in 2 plots
     ax2 = fig.add_subplot(212) # 2 by 1 by 2 - 2nd plot in 2 plots
     
     ax1.plot(range(len(acf_values)), acf(inputDataSeries, nlags = n_iter), \
              range(len(acf_values)), acf_values, 'ro')
     ax2.plot(range(len(acf_values)), pacf(inputDataSeries, nlags = n_iter), 'g*-')
     
     # Plot horizontal lines    
     ax1.axhline(y = 0.0, color = 'black')
     ax2.axhline(y = 0.0, color = 'black')
         
     # Axis labels    
     plt.xlabel = 'Lags'
     plt.ylabel = 'Correlation Coefficient'
     return {'acf' : list(acf_values), \
             'pacf': pacf(inputDataSeries, nlags = n_iter)} 
开发者ID:kshiitijee,项目名称:Time_Series,代码行数:54,代码来源:pandas_data_download.py


示例3: test_ols

 def test_ols(self):
     pacfols, confint = pacf(self.x, nlags=40, alpha=.05, method="ols")
     assert_almost_equal(pacfols[1:], self.pacfols, DECIMAL_6)
     centered = confint - confint.mean(1)[:,None]
     # from edited Stata ado file
     res = [[-.1375625, .1375625]] * 40
     assert_almost_equal(centered[1:41], res, DECIMAL_6)
开发者ID:joesnacks,项目名称:statsmodels,代码行数:7,代码来源:test_stattools.py


示例4: ACF_PACF_plot

 def ACF_PACF_plot(self):
     #plot ACF and PACF to find the number of terms needed for the AR and MA in ARIMA
     # ACF finds MA(q): cut off after x lags 
     # and PACF finds AR (p): cut off after y lags 
     # in ARIMA(p,d,q) 
     lag_acf = acf(self.ts_log_diff, nlags=20)
     lag_pacf = pacf(self.ts_log_diff, nlags=20, method='ols')
     
     #Plot ACF:
     ax=plt.subplot(121)
     plt.plot(lag_acf)
     ax.set_xlim([0,5])
     plt.axhline(y=0,linestyle='--',color='gray')
     plt.axhline(y= -1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
     plt.axhline(y= 1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
     plt.title('Autocorrelation Function')
     
     #Plot PACF:
     plt.subplot(122)
     plt.plot(lag_pacf)
     plt.axhline(y=0,linestyle='--',color='gray')
     plt.axhline(y= -1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
     plt.axhline(y=1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
     plt.title('Partial Autocorrelation Function')
     plt.tight_layout()
开发者ID:greatObelix,项目名称:datatoolbox,代码行数:25,代码来源:timeseries.py


示例5: partial_autocorrelation

def partial_autocorrelation(x, *args, nlags=None, method='ldb', **kwargs):
    """
    Return partial autocorrelation function (PACF) of signal `x`.

    Parameters
    ----------
    x: array_like
        A 1D signal.
    nlags: int
        The number of lags to calculate the correlation for
        (default: min(600, len(x)))
    args, kwargs
        As accepted by `statsmodels.tsa.stattools.pacf`.

    Returns
    -------
    acf: array
        Partioal autocorrelation function.
    confint : optional
        As returned by `statsmodels.tsa.stattools.pacf`.
    """
    from statsmodels.tsa.stattools import pacf
    if nlags is None:
        nlags = min(1000, len(x) - 1)
    corr = pacf(x, *args, nlags=nlags, method=method, **kwargs)
    return _significant_acf(corr, kwargs.get('alpha'))
开发者ID:e-hu,项目名称:orange3-timeseries,代码行数:26,代码来源:functions.py


示例6: plotPACF

def plotPACF(timeSeries):
    lag_pacf = pacf(timeSeries, nlags=20, method='ols')
    plt.subplot(122)
    plt.plot(lag_pacf)
    plt.axhline(y=0,linestyle='--',color='gray')
    plt.axhline(y=-1.96/np.sqrt(len(timeSeries)),linestyle='--',color='gray')
    plt.axhline(y=1.96/np.sqrt(len(timeSeries)),linestyle='--',color='gray')
    plt.title('Partial Autocorrelation Function')
    plt.tight_layout()
开发者ID:sunny123123,项目名称:hadoop,代码行数:9,代码来源:ARIMA_predict002.py


示例7: ARIMA_fun

def ARIMA_fun( data ):
    lag_pacf = pacf( data, nlags=20, method='ols' )
    lag_acf, ci2, Q  = acf( data, nlags=20 , qstat=True, unbiased=True)

    model = ARIMA(orig_data, order=(1, 1, int(ci2[0]) ) )  
    results_ARIMA = model.fit(disp=-1)
    plt.subplot(121)
    plt.plot( data )
    plt.plot(results_ARIMA.fittedvalues)
    #plt.show()
    return results_ARIMA.fittedvalues
开发者ID:s4hackathons,项目名称:singularity,代码行数:11,代码来源:arima.py


示例8: FE

    def FE(self, serie_atual):
        '''
        Método para fazer a diferenciacao de uma serie_atual
        :param serie_atual: serie_atual real
        '''  
        
        #serie_df = pd.DataFrame(serie_atual)
        serie_diff = pd.Series(serie_atual)
        serie_diff = serie_diff - serie_diff.shift()
        serie_diff = serie_diff[1:]
        
        
        features = []
        
        #feature 1:
        auto_correlacao = acf(serie_diff, nlags=5)
        for i in auto_correlacao:
            features.append(i)
        
        #feature 2:
        parcial_atcorr = pacf(serie_diff, nlags=5)
        for i in parcial_atcorr:
            features.append(i)
        
        #feature 3:
        variancia = serie_diff.std()
        features.append(variancia)
        
        #feature 4:
        serie_skew = serie_diff.skew()
        features.append(serie_skew)

        #feature 5:
        serie_kurtosis = serie_diff.kurtosis()
        features.append(serie_kurtosis)
        
        #feature 6:
        turning_p = self.turningpoints(serie_diff)
        features.append(turning_p)
        
        #feature 7:
        
        #feature 8:
        
        
        return features
开发者ID:GustavoHFMO,项目名称:Framework_drift,代码行数:46,代码来源:FEDD.py


示例9: global_analysis

def global_analysis(csv_fname, trajectory_df):
    # catch small trajectory_dfs
    if len(trajectory_df.index) < MIN_TRAJECTORY_LEN:
        return None
    else:
        
        # for each trajectory, loop through segments
        acf_data = np.zeros((len(INTERESTED_VALS), 1, LAGS+1))
        pacf_data = np.zeros((len(INTERESTED_VALS), 1, LAGS+1))
        
            
        # do analysis variable by variable
        count = -1
        for var_name, var_values in trajectory_df.iteritems():
            count += 1
            # make matrices
            
            
            
            # make dictionary for column indices
            var_index = trajectory_df.columns.get_loc(var_name)
#                {'velo_x':0, 'velo_y':1, 'velo_z':2, 'curve':3, 'log_curve':4}[var_name]
            
#            # run ACF and PACF for the column
            col_acf, acf_confint = acf(var_values, nlags=LAGS, alpha=.05)#,  qstat= True)
#            
#            # store data
            acf_data[var_index, 0, :] = col_acf
##            super_data_confint_lower[var_index, segment_i, :] = acf_confint[:,0]
##            super_data_confint_upper[var_index, segment_i, :] = acf_confint[:,1]
            
            
#            ## , acf_confint, acf_qstats, acf_pvals
            col_pacf, pacf_confint = pacf(var_values, nlags=LAGS, method='ywmle', alpha=.05)
            pacf_data[var_index, 0, :] = col_pacf
#            # TODO: check for PACF values above or below +-1
#            super_data[var_index+len(INTERESTED_VALS), segment_i, :] = col_pacf
#            super_data_confint_lower[var_index+len(INTERESTED_VALS), segment_i, :] = pacf_confint[:,0]
#            super_data_confint_upper[var_index+len(INTERESTED_VALS), segment_i, :] = pacf_confint[:,1]

                
                
            
        
        return acf_data, pacf_data
开发者ID:isomerase,项目名称:RoboSkeeter,代码行数:45,代码来源:correlation_matrices.py


示例10: get_acf_pacf

 def get_acf_pacf(self, inputDataSeries, lag = 15):
     # Copy the data in input data
     outputData = pandas.DataFrame(inputDataSeries)
     
     if min(inputDataSeries.index) == inputDataSeries.index[0]:
         # Ascending
         multiplier = 1
         lag = multiplier*lag
     elif max(inputDataSeries.index) == inputDataSeries.index[0]:
         # Descending
         multiplier = -1
         lag = multiplier*lag
     else:
         print('Cannot determine the order put the lag value manually')
         print('Syntax: calc_returns(inputData, columnName, lag = lag_value)')
     
     n_iter = lag
     
     return {'acf' : acf(inputDataSeries, nlags = n_iter), \
             'pacf': pacf(inputDataSeries, nlags = n_iter)} 
开发者ID:kshiitijee,项目名称:Time_Series,代码行数:20,代码来源:pandas_data_download.py


示例11: corrfunc

def corrfunc(timeseries):
	diff_ts = timeseries - timeseries.shift()
	diff_ts.dropna(inplace=True)
	ts_acf = acf(diff_ts, nlags=20)
	ts_pacf = pacf(diff_ts, nlags=20, method='ols')
	#Plot ACF and PACF:
	fig = plt.figure(figsize=(12,8))
	ax1 = fig.add_subplot(211)
	plt.tick_params(axis="both", which="both", bottom="on", top="off",    
		                labelbottom="on", left="on", right="off", labelleft="on")
	fig = sm.graphics.tsa.plot_acf(timeseries.values.squeeze(), lags=20, ax=ax1)
	plt.title('ACF', fontsize=15)
	ax2 = fig.add_subplot(212)
	fig = sm.graphics.tsa.plot_pacf(timeseries, lags=20, ax=ax2)
	plt.tick_params(axis="both", which="both", bottom="on", top="off",    
		                labelbottom="on", left="on", right="off", labelleft="on")
	plt.xlabel("Lags", fontsize=14) 
	plt.title('PACF', fontsize=15)
	plt.tight_layout()
	fig.savefig('corrfunc.png', bbox_inches="tight")
开发者ID:mkgunasinghe,项目名称:examples,代码行数:20,代码来源:timeseries.py


示例12: plot_acf_and_pacf

def plot_acf_and_pacf(y):
    lag_acf = acf(y, nlags=20)
    lag_pacf = pacf(y, nlags=20, method='ols')
    
    plt.subplot(121) 
    plt.plot(lag_acf)
    plt.axhline(y=0,linestyle='--',color='gray')
    plt.axhline(y=-1.96/np.sqrt(len(y)),linestyle='--',color='gray')
    plt.axhline(y=1.96/np.sqrt(len(y)),linestyle='--',color='gray')
    plt.title('Autocorrelation Function')
    
    #Plot PACF:
    plt.subplot(122)
    plt.plot(lag_pacf)
    plt.axhline(y=0,linestyle='--',color='gray')
    plt.axhline(y=-1.96/np.sqrt(len(y)),linestyle='--',color='gray')
    plt.axhline(y=1.96/np.sqrt(len(y)),linestyle='--',color='gray')
    plt.title('Partial Autocorrelation Function')
    plt.tight_layout()
    plt.show()
    plt.close()
开发者ID:MBleeker,项目名称:Data-Mining,代码行数:21,代码来源:exploration-liam.py


示例13: acf_pacf

def acf_pacf(ts):
	ts_log, ts_log_diff = trend(ts)
	lag_acf = acf(ts_log_diff, nlags = 20)
	lag_pacf = pacf(ts_log_diff, nlags = 20, method = 'ols')

	#plot acf
	plt.subplot(121)
	plt.plot(lag_acf)
	plt.axhline(y=0, linestyle = '--', color = 'gray')
	plt.axhline(y = -1.96/np.sqrt(len(ts_log_diff)), linestyle = '--', color = 'gray')
	plt.axhline(y = 1.96/np.sqrt(len(ts_log_diff)), linestyle = '--', color = 'gray')
	plt.title('Autocorrelation Function')

	#plot pacf
	plt.subplot(122)
	plt.plot(lag_pacf)
	plt.axhline(y=0, linestyle = '--', color = 'gray')
	plt.axhline(y = -1.96/np.sqrt(len(ts_log_diff)), linestyle = '--', color = 'gray')
	plt.axhline(y = 1.96/np.sqrt(len(ts_log_diff)), linestyle = '--', color = 'gray')
	plt.title('Partial Autocorrelation Function')

	plt.tight_layout()
	plt.show()
开发者ID:pthaike,项目名称:comp,代码行数:23,代码来源:process.py


示例14: print

print(arma_res.summary())


# In[3]:


arma_res.resid.iloc[1:].plot(figsize=(6,4),color='seagreen')
plt.ylabel('$\hat{z_t}$')


# In[4]:


from statsmodels.tsa import stattools
acf,q,pvalue = stattools.acf(arma_res.resid,nlags=5,qstat=True)
pacf,confint = stattools.pacf(arma_res.resid,nlags=5,alpha=0.05)
print("自己相関係数:",acf)
print("p値:",pvalue)
print("偏自己相関:",pacf)
print("95%信頼区間:",confint)


# In[5]:


p=sm.tsa.adfuller(arma_res.resid,regression='nc')[1] #[1]はp値の検定結果
p1=sm.tsa.adfuller(arma_res.resid,regression='c')[1] #[1]はp値の検定結果
print("ドリフト無しランダムウォーク p値:",p)
print("ドリフト付きランダムウォーク p値:",p1)

开发者ID:jettom,项目名称:SoftArsenal,代码行数:29,代码来源:pan8.py


示例15: Series

# -*- coding: utf-8 -*-

import numpy as np
from pandas import *
from statsmodels.tsa import stattools
import matplotlib.pyplot as plt

randn = np.random.randn

ts = Series(randn(1000), index=DateRange('2000/1/1', periods=1000))
ts = ts.cumsum()

ts.plot(style='<--')
rolling_mean(ts, 60).plot(style='--', c='r')
rolling_mean(ts, 180).plot(style='--', c='b')

acf = stattools.acf(np.array(ts), 50)
plt.bar(range(len(acf)), acf, width=0.01)
plt.savefig("image.png")

pcf = stattools.pacf(np.array(ts), 50)
plt.bar(range(len(pcf)), pcf, width=0.01)
plt.show()
plt.savefig("image2.png")
开发者ID:id774,项目名称:sandbox,代码行数:24,代码来源:random-walk.py


示例16: acf

# Checking out a scatter plot , probably we can try out different lags and check data
#sb.jointplot('Logged First Difference','Lag 20',stock_data, kind ='reg', size = 10)
#pylab.show ()

# Probably we can use stat models and check out the lagged data for all and see
#if any correlation exits

from statsmodels.tsa.stattools import acf
from statsmodels.tsa.stattools import pacf

#acf is auto correlation fucntion and pacf is partial acf (works only for 1 d array)
#iloc is integer location, check pandas

lag_corr = acf (stock_data ['Logged First Difference'].iloc [1:])
lag_partial_corr = pacf (stock_data ['Logged First Difference'].iloc [1:])

#fig, ax = plt.subplots (figsize = (16,12))
#ax.plot (lag_corr)
#pylab.show ()

# To extract trends and seasonal patterns for TS analysis

from statsmodels.tsa.seasonal import seasonal_decompose

#set the frequency value right for monthly set freq = 30
decomposition = seasonal_decompose(stock_data['Natural Log'], model='additive', freq=30)  
#fig = decomposition.plot()  
#pylab.show ()

#lets fit some ARIMA, keep indicator as 1 and rest as zero ie (p,q,r) = (1,0,0)
开发者ID:varun10221,项目名称:ARIMA-model,代码行数:30,代码来源:s_and_p.py


示例17: acf

# In[13]:

#ACF and PACF plots:
from statsmodels.tsa.stattools import acf, pacf


# In[14]:

from statsmodels.tsa.arima_model import ARIMA


# In[15]:

lag_acf = acf(ts_log_diff, nlags=20)
lag_pacf = pacf(ts_log_diff, nlags=20, method='ols')

#Plot ACF:    
plt.subplot(121)    
plt.plot(lag_acf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
plt.title('Autocorrelation Function')

#Plot PACF:
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_log_diff)),linestyle='--',color='gray')
开发者ID:shubhanshu-gupta,项目名称:2015lab1,代码行数:30,代码来源:TimeSeriesAnalysis_Dataglen_Dataset_SG.py


示例18: forecast

def forecast(ts, log_series):
    """
    make model on the TS after differencing. Having performed the trend and seasonality estimation techniques,
    there can be two situations:
    A strictly stationary series with no dependence among the values. This is the easy case wherein we can model the
    residuals as white noise. But this is very rare.
    A series with significant dependence among values. In this case we need to use some statistical models like ARIMA to
    forecast the data.

    The predictors depend on the parameters (p,d,q) of the ARIMA model:
    Number of AR (Auto-Regressive) terms (p): AR terms are just lags of dependent variable. For instance if p is 5,
    the predictors for x(t) will be x(t-1)...x(t-5).
    Number of MA (Moving Average) terms (q): MA terms are lagged forecast errors in prediction equation. For instance
    if q is 5, the predictors for x(t) will be e(t-1)...e(t-5) where e(i) is the difference between the moving average
    at ith instant and actual value.
    Number of Differences (d): These are the number of nonseasonal differences, i.e. in this case we took the first
    order difference. So either we can pass that variable and put d=0 or pass the original variable and put d=1.
    Both will generate same results.

    We use two plots to determine these numbers. Lets discuss them first.

    Autocorrelation Function (ACF): It is a measure of the correlation between the the TS with a lagged version of itself.
    For instance at lag 5, ACF would compare series at time instant 't1'...'t2' with series at instant 't1-5'...'t2-5'
    (t1-5 and t2 being end points).
    Partial Autocorrelation Function (PACF): This measures the correlation between the TS with a lagged version of itself
    but after eliminating the variations already explained by the intervening comparisons. Eg at lag 5, it will check
    the correlation but remove the effects already explained by lags 1 to 4.

    :param log_series:
    :return:
    """
    #ACF and PACF plots
    ts_log_diff = ts_log - ts_log.shift()
    ts_log_diff = ts_log_diff.dropna()
    lag_acf = acf(ts_log_diff, nlags = 20)
    lag_pacf = pacf(ts_log_diff, nlags = 20, method = "ols")
    #plot ACF
    plt.subplot(221)
    plt.plot(lag_acf)
    plt.axhline(y=0, linestyle="--", color="gray")
    plt.axhline(y=-1.96 / np.sqrt(len(ts_log_diff)), linestyle="--", color="gray") #lower line of confidence interval
    plt.axhline(y=1.96 / np.sqrt(len(ts_log_diff)), linestyle="--", color="gray") #upper line of confidence interval
    plt.title('Autocorrelation Function')

    # Plot PACF:
    plt.subplot(222)
    plt.plot(lag_pacf)
    plt.axhline(y=0, linestyle="--", color="gray")
    plt.axhline(y=-1.96 / np.sqrt(len(ts_log_diff)), linestyle="--", color="gray")
    plt.axhline(y=1.96 / np.sqrt(len(ts_log_diff)), linestyle="--", color="gray")
    plt.title('Partial Autocorrelation Function')
    plt.tight_layout()

    #from these plots, we get p and q:
    #p - The lag value where the PACF chart crosses the upper confidence interval for the first time. If you notice
    # closely, in this case p=2.
    #q - The lag value where the ACF chart crosses the upper confidence interval for the first time. If you notice
    # closely, in this case q=2.

    #AR model
    res_arima = arima_models(ts_log, 2, 1, 0)
    # print pd.Series(res_arima.fittedvalues)
    plt.subplot(223)
    plt.plot(ts_log_diff)
    plt.plot(res_arima.fittedvalues, color='red')
    # plt.title('AR model--RSS: %.4f' % sum((pd.Series(res_arima.fittedvalues) - ts_log_diff) ** 2))

    #MA model
    res_ma = arima_models(ts_log, 0, 1, 2)
    plt.subplot(224)
    plt.plot(ts_log_diff)
    plt.plot(res_ma.fittedvalues, color='red')
    # plt.title('MA model--RSS: %.4f' % sum((res_ma.fittedvalues - ts_log_diff) ** 2))
    plt.plot()

    ##Combined model
    res = arima_models(ts_log, 2, 1, 2)
    plt.plot(ts_log_diff)
    plt.plot(res.fittedvalues, color='red')
    # plt.title('RSS: %.4f' % sum((res.fittedvalues - ts_log_diff) ** 2))
    plt.show()
    #Here we can see that the AR and MA models have almost the same RSS but combined is significantly better.

    #predicting
    predictions_diff = pd.Series(res.fittedvalues, copy=True)
    print predictions_diff.head()
    #Notice that these start from '1949-02-01' and not the first month; because we took a lag by 1 and first element
    # doesn't have anything before it to subtract from. The way to convert the differencing to log scale is to add these
    # differences consecutively to the base number. An easy way to do it is to first determine the cumulative sum at
    # index and then add it to the base number. The cumulative sum can be found as:
    predictions_diff_cumsum = predictions_diff.cumsum()
    #now add them to the base number

    predictions_arima_log = pd.Series(ts_log.ix[0], index = ts_log.index)
    predictions_arima_log = predictions_arima_log.add(predictions_diff_cumsum, fill_value = 0)
    #now let us take the exponential to regain original form of series
    predictions_ARIMA = np.exp(predictions_arima_log)
    plt.plot(ts)
    plt.plot(predictions_ARIMA)
    # plt.title('RMSE: %.4f' % np.sqrt(sum((predictions_ARIMA - ts) ** 2) / len(ts)))
#.........这里部分代码省略.........
开发者ID:gaurikatyagi,项目名称:Machine-Learning,代码行数:101,代码来源:analyze_stationary.py


示例19: pacf

def pacf(timeSeries,nlags = 40, alpha = 0.05,   method = 'ywunbiased'):
    results  = stattools.pacf(timeSeries, nlags = nlags, 
                            alpha = alpha, 
                            method = method)

    return results
开发者ID:manuwhs,项目名称:Trapyng,代码行数:6,代码来源:VARMA.py


示例20: plot_pacf

def plot_pacf(x, ax=None, lags=None, alpha=.05, method='ywm',
                use_vlines=True, **kwargs):
    """Plot the partial autocorrelation function

    Plots lags on the horizontal and the correlations on vertical axis.

    Parameters
    ----------
    x : array_like
        Array of time-series values
    ax : Matplotlib AxesSubplot instance, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    lags : array_like, optional
        Array of lag values, used on horizontal axis.
        If not given, ``lags=np.arange(len(corr))`` is used.
    alpha : scalar, optional
        If a number is given, the confidence intervals for the given level are
        returned. For instance if alpha=.05, 95 % confidence intervals are
        returned where the standard deviation is computed according to
        1/sqrt(len(x))
    method : 'ywunbiased' (default) or 'ywmle' or 'ols'
        specifies which method for the calculations to use:

        - yw or ywunbiased : yule walker with bias correction in denominator
          for acovf
        - ywm or ywmle : yule walker without bias correction
        - ols - regression of time series on lags of it and on constant
        - ld or ldunbiased : Levinson-Durbin recursion with bias correction
        - ldb or ldbiased : Levinson-Durbin recursion without bias correction

    use_vlines : bool, optional
        If True, vertical lines and markers are plotted.
        If False, only markers are plotted.  The default marker is 'o'; it can
        be overridden with a ``marker`` kwarg.
    **kwargs : kwargs, optional
        Optional keyword arguments that are directly passed on to the
        Matplotlib ``plot`` and ``axhline`` functions.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    See Also
    --------
    matplotlib.pyplot.xcorr
    matplotlib.pyplot.acorr
    mpl_examples/pylab_examples/xcorr_demo.py

    Notes
    -----
    Adapted from matplotlib's `xcorr`.

    Data are plotted as ``plot(lags, corr, **kwargs)``

    """
    fig, ax = utils.create_mpl_ax(ax)

    if lags is None:
        lags = np.arange(len(x))
        nlags = len(lags) - 1
    else:
        nlags = lags
        lags = np.arange(lags + 1) # +1 for zero lag

    acf_x, confint = pacf(x, nlags=nlags, alpha=alpha, method=method)

    if use_vlines:
        ax.vlines(lags, [0], acf_x, **kwargs)
        ax.axhline(**kwargs)

    # center the confidence interval TODO: do in acf?
    confint = confint - confint.mean(1)[:,None]
    kwargs.setdefault('marker', 'o')
    kwargs.setdefault('markersize', 5)
    kwargs.setdefault('linestyle', 'None')
    ax.margins(.05)
    ax.plot(lags, acf_x, **kwargs)
    ax.fill_between(lags, confint[:,0], confint[:,1], alpha=.25)
    ax.set_title("Partial Autocorrelation")

    return fig
开发者ID:B-Rich,项目名称:statsmodels,代码行数:84,代码来源:tsaplots.py



注:本文中的statsmodels.tsa.stattools.pacf函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tsatools.add_trend函数代码示例发布时间:2022-05-27
下一篇:
Python stattools.adfuller函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap