1 // (C) Copyright Nick Thompson 2019.
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0. (See accompanying file
4 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 #ifndef BOOST_MATH_STATISTICS_LJUNG_BOX_HPP
7 #define BOOST_MATH_STATISTICS_LJUNG_BOX_HPP
12 #include <boost/math/distributions/chi_squared.hpp>
13 #include <boost/math/statistics/univariate_statistics.hpp>
15 namespace boost::math::statistics {
17 template<class RandomAccessIterator>
18 auto ljung_box(RandomAccessIterator begin, RandomAccessIterator end, int64_t lags = -1, int64_t fit_dof = 0) {
19 using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;
20 int64_t n = std::distance(begin, end);
22 throw std::domain_error("Number of lags must be < number of elements in array.");
26 // This is the same default as Mathematica; it seems sensible enough . . .
27 lags = static_cast<int64_t>(std::ceil(std::log(Real(n))));
31 throw std::domain_error("Must have at least one lag.");
34 auto mu = boost::math::statistics::mean(begin, end);
36 std::vector<Real> r(lags + 1, Real(0));
37 for (size_t i = 0; i < r.size(); ++i) {
38 for (auto it = begin + i; it != end; ++it) {
40 Real akml = *(it-i) - mu;
47 for (size_t k = 1; k < r.size(); ++k) {
48 Q += r[k]*r[k]/(r[0]*r[0]*(n-k));
52 typedef boost::math::policies::policy<
53 boost::math::policies::promote_float<false>,
54 boost::math::policies::promote_double<false> >
57 auto chi = boost::math::chi_squared_distribution<Real, no_promote_policy>(Real(lags - fit_dof));
59 Real pvalue = 1 - boost::math::cdf(chi, Q);
60 return std::make_pair(Q, pvalue);
64 template<class RandomAccessContainer>
65 auto ljung_box(RandomAccessContainer const & v, int64_t lags = -1, int64_t fit_dof = 0) {
66 return ljung_box(v.begin(), v.end(), lags, fit_dof);