1. Trang chủ
  2. » Thể loại khác

Hướng dẫn phân tích time series trong Stata

26 77 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • LÝ THUYẾT TIME SERIES

  • TẠO BIẾN NGÀY THÁNG DÙNG CHO TIME SERIES

  • THIẾT LẬP BIẾN THỜI GIAN DÙNG CHO PHÂN TÍCH TIME SERIES

  • VẼ BIỂU ĐỒ BIẾN THEO THỜI GIAN

  • TẠO LAG, LEAD, VÀ SEASONAL CHO BIẾN TIME SERIES

  • SMOOTHING A TREND

  • KIỂM TRA XEM TIME SERIES CÓ CẦN DIFFERENCE HAY KHÔNG?

  • TIÊN ĐOÁN BẰNG CÁC MÔ HÌNH

Nội dung

LÝ THUYẾT TIME SERIES TS xem chuỗi biến liên tục x1; x2; x3; x1 giá trị chuỗi thời điểm đầu tiên, x2 thời điểm thứ hai v.v TS coi stochastic process (quá trình ngẫu nhiên) nghĩa giá trị chuỗi xuất ngẫu nhiên White noise gì? White noise TS dùng để mơ hình hóa tiếng ồn kỹ thuật White noise bao gồm tập hợp giá trị tiếng ồn nhiều thời điểm tiếng ồn khơng tương quan với White noise gọi white independent noise iid (identically distributed) noise hay Gaussian white noise Nếu tất TS white noise dùng phương pháp thơng kê truyền thống để xử lý chúng phương pháp thống kê truyền thống có giả định giá trị biến số không tương quan với Tuy nhiên tất TS có giá trị tương quan với Mục đích time series analysis (TSA) tìm dạng liệu từ tiên đốn liệu tương lai TSA giả định liệu chuỗi thời gian (TS) có dạng hệ thống định (time series pattern) (gồm thành phần) cộng với phần random noise white noise error (sai lệch) làm cho khó xác định dạng liệu Do TS cho theo mơ hình cộng thêm (additive model) Hầu hết kỹ thuật TSA cố gắng khử random noise để dạng liệu xác định dễ Dạng hệ thống TS gồm có thành phần, thành phần hàm số  Thành phần xu hướng (trend) Trend có dạng hàm số với hệ số số hạng ước lượng từ phương pháp tổng bình phương tối thiểu (OLS-least square estimates) Các dạng hàm số phổ biến trend bao gồm: hàm logistic (logistic function), hàm Mitscherlich, đường cong The Gompertz Curve, hàm Allometric Để kiểm tra độ tương thích mơ hình cho trend sử dụng giá trị R2 gọi squared multiple correlation coefficient (SMCC)  Thành phần theo mùa (seasonality)  Thành phần chu kỳ (cycle) TÍNH CHẤT TIME SERIES Để mô tả TS người ta dùng hàm phân bố kết hợp (joint distribution function) Hàm có tham số cần quan tâm sau để mô tả cho time series  Mean function: trung bình hàm  Autocovariance function: tự đồng phương sai Để phân tích TS cách xác TS phải stationary Stationary gì? Stationary tính ổn định dạng TS Một TS có tính ổn định khi: Một strictly stationary TS TS cực ổn định mà xác suất giá trị thời điểm giống với xác suất giá trị thời điểm khác Ví dụ, giá trị x thời điểm 10 giá trị x thời điểm 100 10 Trong thực tế hầu hết TS không ổn định ảnh hưởng trend seasonality  TS có trend khơng gọi TS ổn định xu hướng (trend stationary TS)  TS có trend seasonality gọi TS theo mùa bội (multiplicative seasonality) Hầu hết TS có dạng LỌC TIME SERIES Mục đích lọc TS (filtering TS) làm mềm phần white noise để từ phát thành phần trend season TS Có nhiều filter khác nhau, bao gồm:  Linear filter hay gọi moving average (MA): filter đặc biệt nhóm simple moving averages bậc 2s + and 2s Sau lọc với MA, TS bộc lộ dạng Y = T + S + white noise Nếu dùng thêm filter diffrence TS dạng Y = S + white noise  The Census X–11 Program: giúp lọc TS cịn mùa Cách làm sau: 1) tính MA để lọc cịn TS có trend, 2) tính hiệu số để cịn TS có mùa white noise, 3) tính MA cho tháng để lọc cịn TS có mùa mà thơi Mục đích chương trình để lọc TS có tính theo mùa Sau chạy chương trình TS bộc lộ dạng Y = S mà  Best Local Polynomial Fit : dùng cho TS ban đầu có hình vặn xoắn khơng giống đường thẳng Khi phải dùng filter để đưa TS dạng thẳng từ dùng MA  Diffrence filter: Sau lọc diffrence TS bộc lộ tính mùa Y = S Nếu diffrence hai lần làm TS bộc lộ phần T đa thức (không theo đường thẳng)  Exponential Smoother : chủ yếu dùng để tiên đoán HỒI QUY CHO TIME SERIES Trong mơ hình hồi quy tuyến tính truyền thống noise (error) white nghĩa error khơng tương quan Trong mơ hình hồi quy cho TS noise lại có tương quan DISTRIBUTED-LAG MODEL This methodology allows the effect of a single exposure event to be distributed over a specific period of time, using several parameters to explain the contributions at different lags, thus providing a comprehensive picture of the time-course of the exposure-response relationship Conventional DLMs rely on the assumption of a linear effect between the exposure and the outcome More recently, a general approach has been proposed to further relax the linearity assumption, and flexibly describe simultaneously non-linear and delayed effects This step has lead to the generation of the new modeling framework of distributed lag non-linear models (DLNMs) Phải xác định mối quan hệ effect of x lên y Có dạng     Permanent effect of x tạo permanent effect of y Permanent effect of x tạo temporary effect of y Temporary effect (short term effect) of x tạo temporary effect of y Temporary effect of x tạo permanent effect of y: mối lien quan không giải distributed-lag model; phải chuyển đổi temporary effect of x thành permanent effect of x chuyển permanent effect of y thành temporary effect of y  the finite distributed lag model is most suitable to estimating dynamic relationships when lag weights decline to zero relatively quickly, when the regressor is not highly autocorrelated, and when the sample is long relative to the length of the lag distribution The simplest model is the Koyck lag, which has one lag of y on the right-hand side with only the current value of x Given the autoregressive lag relationship in equation (3.13), a logical extension is to allow lags of x on the right-hand side The general autoregressive distributed lag (ARDL) model is written In all of the models we have studied, we must specify the length of the lag prior to estimation An obvious way to choose the length of a lag is to start with a long lag test the statistical significance of the coefficient at the longest lag—the “trailing lag”—and shorten the lag by one period it if we cannot reject the null hypothesis that the effect at the longest lag is zero We continue shortening the lag until the trailing lag coefficient is statistically significant Information criteria are designed to measure the amount of information about the dependent variable contained in a set of regressors They are goodness-of-fit measures of the same type as R2 or R2 , but without the convenient interpretation as share of variance explained that we give to R2 in an OLS regression with an intercept term The two most commonly used criteria are the Akaike information criterion (AIC) and the Schwartz/Bayesian information criterion (SBIC) As discussed above, adding lags of x and/or y to the right-hand side of a distributed-lag regression usually lessens the degree of autocorrelation in the error term Estimators of some models (especially those with lagged dependent variables) are sensitive to autocorrelated errors, so another criterion that is sometimes used for choosing lag length is autocorrelation the in elimination the of residuals When using residual autocorrelation to determine lag length, one adds lags until the residuals appear to be white noise After running the distributed-lag regression, one extracts the residuals and uses a Breusch-Godfrey LM test or a Box-Ljung Q test to test the null hypothesis that the residuals are white noise Rejecting the white-noise null hypothesis means that more lags should be added to the regression according to this criterion Mơ hình ARDL In order to run ARDL some preconditions needed to be checked  Dependent must be non stationary in order for the model to behave better  None of the variable should be I(2) in normal conditions (ADF test)  none of the variable should be I(2) in structural break (Zivot Andrews test) First of all we require the ARDL module for STATA, for this write following command“findit ARDL” in STATA command window it will show the link for the ARDL module, click it and install in your STATA Following is the command “ardl depvar indepvar1 indepvar2 … , aic” here aic is used to automatic lag selection using Akike Information Criterion Method Following are the results have matched the results with the ARDL of eviews, they are about 90% similar the slight difference is because the fact that both software packages use a different method to calculate standard errors Following is the command “ardl, noctable btest” this will show the ARDL bound test and critical values As expected the critical values are same as what is shown in the eviews but the bound test is slightly larger in eviews it is 5.43 here it is 5.62 hence we can say that there are more chances that you will find cointegration in STATA Now you need the long run and short run coefficients it can be estimated through “ardl depvar indepvar1 indepvar2 … , aic ec regstore(ecreg)” Here ec will be used to generate the error correction version of the model with aic as the criterion for the lag order The important thing is the use of restore(name) command, it will be explained later Here you can see the LR is the long run estimates, SR is the short run estimates and ADJ is the adjustment coefficient or the error correction coefficients Now for the case to generate the post estimation diagnostics you need to convert the ardl estimated results to the reg format so that we can apply post estimations For this write the command “estimates restore ecreg” it will bring the result of the ardl ecm model into the memory of the computer And when you write the “regress” command it will show the ecm results under regress command like below Here you can use following commands “estat dwatson” for the Durbin – Watson D statistics for 1st order autocorrelation “estat archlm” for the ARCH LM test for higher order autocorrelation “estat bgodfrey” for the Breusch Godfrey LM test for higher order autocorrelation “estat hettest” for Breusch Pagan Heteroscedasticity test “estat ovtest” for Ramsey RESET test “estat vif” for VIF test of Multicollinearity For all these tests the decision criterion is available in the form of null or alternative hypothesis Up-til now I am looking how to check the stability of the coefficient (CUSUM) test in STATA Any one who knows how to it please share Hope this helps MƠ HÌNH NON-LINEAR AUTOREGRESSIVE DISTRIBUTED LAG MODEL (NARDL) This blog is illustrating the Non-linear ARDL cointegrating bounds which is also called Asymmetric Effects ARDL (NARDL) proposed by (Shin, Yu & GreenwoodNimmo, 2014) The idea behind this model is questioning the standard assumption of symmetric estimates, by which the effect of increasing of a variable is equal and opposite to the decreasing of the same variable There are few cases mentioned in the above study like creation and destruction of jobs in boom and recession In the example below the nardl_data is unemployment (dependent variable) and industrial production index (independent variable) You can import this data into Stata by simply copying and pasting in data editor (tutorial) Once imported, you have to indicate Stata that data is time series for this following command is used tsset time This way all the time series command will become functional In order to estimate the NARDL following files must be downloaded, uncompressed, and paste Stata/ado/base/n folder where ever it is installed, it will then work in Stata Following is the command In the command below p() and q() are the number of lags of dependent and independent variable used You can identify optimal lag by using ‘varsoc’ command in Stata, illustrated here nardl un ip, p(2) q(2) The long run asymmetry and short run asymmetry is tested using F test Since only long run F test is significant so there is only long run asymmetry After estimating the model, there are four types of diagnostics reported, since all of them are insignificant, so there is no autocorrelation, heteroscedasticity, misspecification and non-normality respectively We can also generate the graph by adding the ‘plot’ option in command and further confidence interval by using bootstrap and level option The horizon option will identify how many years the graph will be constructed nardl un ip, p(2) q(4) plot horizon(40) bootstrap(100) level(95) in the above figure, we can see that decrease in IP(industrial production) has a positive effect on UN(unemployment) shown by red line While increasing IP has a temporary negative effect on UN shown by the green line And the blue line showing the increasing trend of asymmetry with time MƠ HÌNH DLNM Chạy R Ví dụ: tìm mơ hình cho biến tử vong tim mạch pm10 nhiệt độ  tạo cross basis cho pm10 nhiệt độ Các giá trị câu lệnh Argvar: tạo basis cho var Arglag: tạo basis cho lag Fun: function hàm cho var lag Có loại fun sau: o o o o lin: linear hàm tuyến tính poly: polynominal hàm đa thức strata: stratafied hàm phân nhóm ns: hàm natural cubic spline hàm bật với df=5 internal knot: khoảng biểu thị biểu đồ, không liệt kê nghĩa mặc định boundary knot: nút biên khoảng nhiệt độ lag = 15: có 15 lag cho biến pm10 lag=3: có lag cho biến nhiệt độ lag strata: 1-3, break = nghĩa biên strata 1-3 Xây dựng mơ hình tử vong = cross basis pm10 + cross basis nhiệt độ + hàm smooth bậc cho thời gian + ngày tuần (dow) Ước lượng mối tương quan với mức pm định lên tử vong (hay nói cách khác ước lượng tham số biến pm hay RR-nguy tương đối) At = 0: 20: tính tham số tiên đốn cho giá trị pm10 từ 0-20 µgr Bylag=0.2: giá trị tiên đốn tính khơng gian lag với gia số 0.2 cumul (default to FALSE) indicates that also incremental cumulative associations along lags must be included The function includes the pred1.pm object with the stored results, and the argument "slices" defines that we want to graph relationship corresponding to specific values of predictor and lag in the related dimensions With var=10 I display the lag-response relationship for a specific value of PM 10, i.e 10 µgr/m3 This association is defined using the reference value of µgr/m3, thus providing the predictor-specific association for a 10-unit increase I also chose a different colour for the first plot The argument cumul indicates if incremental cumulative associations, previously saved in pred1.pm, must be plotted The results are shown in Figures 1a{1b Confidence intervals are set to the default value "area" for the argument ci In the left panel, additional arguments are passed to the low-level plotting function polygon() through ci.arg, to draw instead shading lines as confidence intervals The interpretation of these plots is twofold: the lag curve represents the increase in risk in each future day following an increase of 10 µgr/m3 in PM10 in a specific day (forward interpretation), or otherwise the contributions of each past day with the same PM 10 increase to the risk in a specific day (backward interpretation) The plots in Figures 1a{1b suggest that the initial increase in risk of PM 10 is reversed at longer lags The overall cumulative effect of a 10-unit increase in PM 10 over 15 days of lag (i.e summing all the contributions up to the maximum lag), together with its 95% confidence intervals be extracted by the objects allRRfit, allRRhigh and allRRlow included in pred1.pm, typing: can TẠO BIẾN NGÀY THÁNG DÙNG CHO TIME SERIES gen date=tm(2000m1)+_n-1 Tạo biến date biến tháng tháng format %tq date năm 2000 Có thể dùng tq (quarterly), tm(monthly), tw(weeks), ty(year) Đổi từ interger sang dạng chuỗi (tg: quý- năm, tm: tháng-năm, tw: tuần-năm) gen date = mdy(month, day,year) Tạo biến date từ biến month, day, year có gen day = day(date) sẵn Tạo biến ngày, tuần, tháng, quý, nửa năm gen week = week (date) năm từ biến date đầy đủ ngày/tháng/năm gen month = month (date) gen quarter = quarter (date) gen half = halfyear(date) gen year = year(date) Tạo biến ngày tuần (dow) ngày năm (doy) từ biến dat đầy đủ ngày/tháng/năm THIẾT LẬP BIẾN THỜI GIAN DÙNG CHO PHÂN TÍCH TIME SERIES Thiết lập biến date biến ngày tháng với khoảng cách delta quý Biến date không cần option quarterly biến date format tq trước Thiết lập biến date biến ngày tháng với khoảng cách delta ngày VẼ BIỂU ĐỒ BIẾN THEO THỜI GIAN Vẽ đường thẳng biến gdp theo thời gian (year) Muốn vẽ lệnh tsline phải tsset biến year biến thời gian cho phân tích time series Vẽ đường thẳng biến kgpcap theo thời gian (year) không cần dùng tsset Option mlabel(year) dùng để gán năm cho dot đường thẳng Vẽ đường connect biến co2 theo thời gian (year) vẽ đường thẳng biến gdp theo thời gian (year) Option yaxis (2) dùng để tạo hai trục tung với đơn vị tính khác cho hai đường TẠO LAG, LEAD, VÀ SEASONAL CHO BIẾN TIME SERIES SMOOTHING A TREND Chúng ta dùng lệnh save để lưu liệu tên trend Chúng ta dùng lệnh tsset để thể liệu lệu time series với biến month biến thời gian Stata diễn giải giá trị biến month, thiết lập số giá trị số quan sát, theo cách tốt Tất lệnh time series Stata, bao gồm lệnh tssmooth, cần liệu thiết lập với tsset foreach smoother in h 3h h3 { tssmooth nl S`smoother' = rawtrend,smoother(`smoother') } Tạo loại smoother lệnh vòng lặp foreach Có loại smoother h (Hanning smoother), (span-3 median smoother), 3h (span-3 median smoother dùng Hanning smoother), h3 (Hanning smoother dùng span-3 median smoother), (span-9 median smoother) S`smoother’ tạo biến Sh, S3, S3h, Sh3, S9 Option smoother chạy loại smoother (h, 3, 3h, h3 9) tsline rawtrend S3 Sh,lpattern(solid dash shortdash) legend(cols(1)) Vẽ biểu đồ cho smotther span-3 median Hanning smoother Chúng ta thấy hai smoother tránh giá trị ngoại lai xuất đường rawtrend Tuy nhiên hai loại smoother có cách xử trí giá trị ngoại lai tháng 46 hồn tồn khác Hanning smoother smoother dựa trung bình bị ảnh hưởng số ngoại lại span-3 median dựa vào median nên không bị ảnh hưởng số ngoại lai KIỂM TRA XEM TIME SERIES CĨ CẦN DIFFERENCE HAY KHƠNG? dfuller presap, lags(1) trend Augmented Dickey-Fuller test for unit root Number of obs = 317 Interpolated DickeyFuller Test 1% Critical 5% Critical 10% Critical Statistic Value Value Value Z(t) -4.183 -3.987 -3.427 -3.130 MacKinnon approximate p-value for Z(t) = 0.0047 pperron presap Phillips-Perron test for unit root Number of obs = 318 Newey-West lags =  With both tests (ADF, Phillips-Perron), we would reject the null hypothesis of a unit root and conclude that the approval series is stationary  This makes sense because it is hard to imagine a bounded variable (0-100) having an infinitely exploding variance over time  Yet, as scholars have shown, the series does have some persistence as it trends upward or downward, suggesting that a fractionally integrated model might work best (Box-Steffensmeier & De Boef) TIÊN ĐỐN BẰNG CÁC MƠ HÌNH Lập mơ hình ARIMA so sánh mơ hình arima presap, arima(1,0,0) ARIMA regression Sample: 1978m1 - 2004m7 = 319 Number of obs Wald chi2(1) = 2133.49 Log likelihood = -915.1457 Prob > chi2 = 0.0000 | OPG presap | Coef Std Err z P>|z| [95% Conf Interval] + presap | _cons | 54.51659 3.411078 15.98 0.000 47.831 61.20218 + ARMA | ar | L1 | 9230742 0199844 46.19 0.000 8839054 9622429  The coefficient on the AR(1) is highly significant, although it is close to one, indicating a potential problem with nonstationarity Even though the unit root tests show no problems, we can see why fractional integration techniques are often used for approval data  Let’s check the residuals from the model (this is a chi-square test on the joint significance of all autocorrelations, or the ACF of the residuals) wntestq resid_m1, lags(10) Portmanteau test for white noise Portmanteau (Q) statistic = Prob > chi2(10) = 13.0857 0.2189  The null hypothesis of white noise residuals is accepted, thus we have a decent -0.10 A utoc o rrelatio ns of re sid _m 0.00 0.10 0.20 model We could confirm this by examining the ACF & PACF of the residuals 10 20 Lag 30 40 30 40 P a rtia l a u to c o rre la tio n s o f re s id _ m -0 -0 0 0 0 Bartlett's formula for MA(q) 95% confidence bands 10 95% Confidence bands [se = 1/sqrt(n)] 20 Lag ... phần chu kỳ (cycle) TÍNH CHẤT TIME SERIES Để mơ tả TS người ta dùng hàm phân bố kết hợp (joint distribution function) Hàm có tham số cần quan tâm sau để mô tả cho time series  Mean function: trung... data into Stata by simply copying and pasting in data editor (tutorial) Once imported, you have to indicate Stata that data is time series for this following command is used tsset time This way... SEASONAL CHO BIẾN TIME SERIES SMOOTHING A TREND Chúng ta dùng lệnh save để lưu liệu tên trend Chúng ta dùng lệnh tsset để thể liệu lệu time series với biến month biến thời gian Stata diễn giải

Ngày đăng: 02/09/2021, 20:35

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w