
    !g                       d Z ddlmZmZ ddlmZ ddlmZ ddlZ	ddl
ZddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# ddlm$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z<  G d de=      Z> G d de=      Z? G d de(j                        ZA G d  d!e(j                        ZCy)"z;
Dynamic factor model.

Author: Chad Fulton
License: BSD-3
    )	MONTH_ENDQUARTER_END)OrderedDict)warnN)
cho_factor	cho_solveLinAlgError)_is_using_pandas)int_like)cache_readonly)OLS)GLM)PCA)SARIMAX)QuarterlyAR1)VAR)Bunch)string_like)lagmat)mlemodelinitialization)companion_matrixis_invertibleconstrain_stationary_univariate!constrain_stationary_multivariate!unconstrain_stationary_univariate#unconstrain_stationary_multivariate)SMOOTHER_STATESMOOTHER_STATE_COVSMOOTHER_STATE_AUTOCOV)
PandasData)SimpleTable)Summary)
fmt_paramsc                   f    e Zd ZdZd Zed        Zed        Zed        Zed        Z	ed        Z
y)	FactorBlocka  
    Helper class for describing and indexing a block of factors.

    Parameters
    ----------
    factor_names : tuple of str
        Tuple of factor names in the block (in the order that they will appear
        in the state vector).
    factor_order : int
        Order of the vector autoregression governing the factor block dynamics.
    endog_factor_map : pd.DataFrame
        Mapping from endog variable names to factor names.
    state_offset : int
        Offset of this factor block in the state vector.
    has_endog_Q : bool
        Flag if the model contains quarterly data.

    Notes
    -----
    The goal of this class is, in particular, to make it easier to retrieve
    indexes of subsets of the state vector that are associated with a
    particular block of factors.

    - `factors_ix` is a matrix of indices, with rows corresponding to factors
      in the block and columns corresponding to lags
    - `factors` is vec(factors_ix) (i.e. it stacks columns, so that it is
      `factors_ix.ravel(order='F')`). Thinking about a VAR system, the first
       k*p elements correspond to the equation for the first variable. The next
       k*p elements correspond to the equation for the second variable, and so
       on. It contains all of the lags in the state vector, which is max(5, p)
    - `factors_ar` is the subset of `factors` that have nonzero coefficients,
      so it contains lags up to p.
    - `factors_L1` only contains the first lag of the factors
    - `factors_L1_5` contains the first - fifth lags of the factors

    c                    || _         t        | j                         | _        || _        |j                  d d |f   | _        || _        || _        | j                  dkD  rt        d| j                        | _	        n| j                  | _	        | j                  | j                  z  | _
        | j                  | d<   | j                  | d<   | j                  | d<   | j                  | d<   | j                  | d<   y )Nr      factors
factors_ar
factors_ix
factors_L1factors_L1_5)factor_nameslen	k_factorsfactor_orderlocendog_factor_mapstate_offset	k_endog_Qmax_factor_orderk_statesr)   r*   r+   r,   r-   )selfr.   r1   r3   r4   r5   s         i/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/statespace/dynamic_factor_mq.py__init__zFactorBlock.__init__Q   s    (T../( 0 4 4Q_ E(">>A!$Q(9(9!:D!%!2!2D););; ,,Y!__\!__\!__\#00^    c                     | j                   }t        j                  |t        j                  | j                  | j
                  z        z   | j
                  | j                  f      j                  S )z3Factor state index array, shaped (k_factors, lags).)r4   npreshapearanger0   r7   Tr9   os     r:   r+   zFactorBlock.factors_ixf   sX     zz!bii9K9K(KLL--t~~>@@A	Br<   c                 t    | j                   }t        j                  ||| j                  | j                  z  z    S )z5Factors and all lags in the state vector (max(5, p)).)r4   r>   s_r0   r7   rB   s     r:   r)   zFactorBlock.factorsr   s4     uuQq4>>D,>,>>>??r<   c                 t    | j                   }t        j                  ||| j                  | j                  z  z    S )z;Factors and all lags used in the factor autoregression (p).)r4   r>   rE   r0   r1   rB   s     r:   r*   zFactorBlock.factors_ary   s4     uuQq4>>D,=,===>>r<   c                 Z    | j                   }t        j                  ||| j                  z    S )z!Factors (first block / lag only).r4   r>   rE   r0   rB   s     r:   r,   zFactorBlock.factors_L1   s)     uuQq4>>)**r<   c                 `    | j                   }t        j                  ||| j                  dz  z    S )zFactors plus four lags.r(   rH   rB   s     r:   r-   zFactorBlock.factors_L1_5   s.     uuQq4>>A--..r<   N)__name__
__module____qualname____doc__r;   propertyr+   r)   r*   r,   r-    r<   r:   r&   r&   +   su    #J1* 	B 	B @ @ ? ?
 + +
 / /r<   r&   c                       e Zd ZdZd Zd Zd Zed        Zed        Z	ed        Z
ed        Zed	        Zed
        Zed        Zd Zy)DynamicFactorMQStatesaF   
    Helper class for describing and indexing the state vector.

    Parameters
    ----------
    k_endog_M : int
        Number of monthly (or non-time-specific, if k_endog_Q=0) variables.
    k_endog_Q : int
        Number of quarterly variables.
    endog_names : list
        Names of the endogenous variables.
    factors : int, list, or dict
        Integer giving the number of (global) factors, a list with the names of
        (global) factors, or a dictionary with:

        - keys : names of endogenous variables
        - values : lists of factor names.

        If this is an integer, then the factor names will be 0, 1, ....
    factor_orders : int or dict
        Integer describing the order of the vector autoregression (VAR)
        governing all factor block dynamics or dictionary with:

        - keys : factor name or tuples of factor names in a block
        - values : integer describing the VAR order for that factor block

        If a dictionary, this defines the order of the factor blocks in the
        state vector. Otherwise, factors are ordered so that factors that load
        on more variables come first (and then alphabetically, to break ties).
    factor_multiplicities : int or dict
        This argument provides a convenient way to specify multiple factors
        that load identically on variables. For example, one may want two
        "global" factors (factors that load on all variables) that evolve
        jointly according to a VAR. One could specify two global factors in the
        `factors` argument and specify that they are in the same block in the
        `factor_orders` argument, but it is easier to specify a single global
        factor in the `factors` argument, and set the order in the
        `factor_orders` argument, and then set the factor multiplicity to 2.

        This argument must be an integer describing the factor multiplicity for
        all factors or dictionary with:

        - keys : factor name
        - values : integer describing the factor multiplicity for the factors
          in the given block
    idiosyncratic_ar1 : bool
        Whether or not to model the idiosyncratic component for each series as
        an AR(1) process. If False, the idiosyncratic component is instead
        modeled as white noise.

    Attributes
    ----------
    k_endog : int
        Total number of endogenous variables.
    k_states : int
        Total number of state variables (those associated with the factors and
        those associated with the idiosyncratic disturbances).
    k_posdef : int
        Total number of state disturbance terms (those associated with the
        factors and those associated with the idiosyncratic disturbances).
    k_endog_M : int
        Number of monthly (or non-time-specific, if k_endog_Q=0) variables.
    k_endog_Q : int
        Number of quarterly variables.
    k_factors : int
        Total number of factors. Note that factor multiplicities will have
        already been expanded.
    k_states_factors : int
        The number of state variables associated with factors (includes both
        factors and lags of factors included in the state vector).
    k_posdef_factors : int
        The number of state disturbance terms associated with factors.
    k_states_idio : int
        Total number of state variables associated with idiosyncratic
        disturbances.
    k_posdef_idio : int
        Total number of state disturbance terms associated with idiosyncratic
        disturbances.
    k_states_idio_M : int
        The number of state variables associated with idiosyncratic
        disturbances for monthly (or non-time-specific if there are no
        quarterly variables) variables. If the disturbances are AR(1), then
        this will be equal to `k_endog_M`, otherwise it will be equal to zero.
    k_states_idio_Q : int
        The number of state variables associated with idiosyncratic
        disturbances for quarterly variables. This will always be equal to
        `k_endog_Q * 5`, even if the disturbances are not AR(1).
    k_posdef_idio_M : int
        The number of state disturbance terms associated with idiosyncratic
        disturbances for monthly (or non-time-specific if there are no
        quarterly variables) variables. If the disturbances are AR(1), then
        this will be equal to `k_endog_M`, otherwise it will be equal to zero.
    k_posdef_idio_Q : int
        The number of state disturbance terms associated with idiosyncratic
        disturbances for quarterly variables. This will always be equal to
        `k_endog_Q`, even if the disturbances are not AR(1).
    idiosyncratic_ar1 : bool
        Whether or not to model the idiosyncratic component for each series as
        an AR(1) process.
    factor_blocks : list of FactorBlock
        List of `FactorBlock` helper instances for each factor block.
    factor_names : list of str
        List of factor names.
    factors : dict
        Dictionary with:

        - keys : names of endogenous variables
        - values : lists of factor names.

        Note that factor multiplicities will have already been expanded.
    factor_orders : dict
        Dictionary with:

        - keys : tuple of factor names
        - values : integer describing autoregression order

        Note that factor multiplicities will have already been expanded.
    max_factor_order : int
        Maximum autoregression order across all factor blocks.
    factor_block_orders : pd.Series
        Series containing lag orders, with the factor block (a tuple of factor
        names) as the index.
    factor_multiplicities : dict
        Dictionary with:

        - keys : factor name
        - values : integer describing the factor multiplicity for the factors
          in the given block
    endog_factor_map : dict
        Dictionary with:

        - keys : endog name
        - values : list of factor names
    loading_counts : pd.Series
        Series containing number of endogenous variables loading on each
        factor, with the factor name as the index.
    block_loading_counts : dict
        Dictionary with:

        - keys : tuple of factor names
        - values : average number of endogenous variables loading on the block
          (note that average is over the factors in the block)

    Notes
    -----
    The goal of this class is, in particular, to make it easier to retrieve
    indexes of subsets of the state vector.

    Note that the ordering of the factor blocks in the state vector is
    determined by the `factor_orders` argument if a dictionary. Otherwise,
    factors are ordered so that factors that load on more variables come first
    (and then alphabetically, to break ties).

    - `factors_L1` is an array with the indexes of first lag of the factors
      from each block. Ordered first by block, and then by lag.
    - `factors_L1_5` is an array with the indexes contains the first - fifth
      lags of the factors from each block. Ordered first by block, and then by
      lag.
    - `factors_L1_5_ix` is an array shaped (5, k_factors) with the indexes
      of the first - fifth lags of the factors from each block.
    - `idio_ar_L1` is an array with the indexes of the first lag of the
      idiosyncratic AR states, both monthly (if appliable) and quarterly.
    - `idio_ar_M` is a slice with the indexes of the idiosyncratic disturbance
      states for the monthly (or non-time-specific if there are no quarterly
      variables) variables. It is an empty slice if
      `idiosyncratic_ar1 = False`.
    - `idio_ar_Q` is a slice with the indexes of the idiosyncratic disturbance
      states and all lags, for the quarterly variables. It is an empty slice if
      there are no quarterly variable.
    - `idio_ar_Q_ix` is an array shaped (k_endog_Q, 5) with the indexes of the
      first - fifth lags of the idiosyncratic disturbance states for the
      quarterly variables.
    - `endog_factor_iloc` is a list of lists, with entries for each endogenous
      variable. The entry for variable `i`, `endog_factor_iloc[i]` is a list of
      indexes of the factors that variable `i` loads on. This does not include
      any lags, but it can be used with e.g. `factors_L1_5_ix` to get lags.

    c           
      0   || _         || _        | j                   | j                  z   | _        || _        t	        j
                  t        |      t        j                        }t        |t        t        f      }	t	        j
                  t        |      t        j                        }
|d}t	        j
                  t        |      t        j                        }|s|	st        |t              st        d      |
st        |t              st        d      |st        |t              st        d      |s|	r\|r|dk(  s|	rt        |      dk(  rt        d      |	rt        |      }nt        |      D cg c]  }|  }}|D ci c]  }||d d  
 }}g }|j                         D ]  }|j!                  |        t#        |      }|
r|D ci c]  }|| }}|r|D ci c]  }|| }}| j%                  |||      \  }}|| _        || _        || _        | j-                  ||      | _        | j.                  j0                  d   | _        | j2                  | j                   kD  r&t        d| j2                   d| j                    d	      | j.                  j5                  d
      j7                  d      j9                         j;                  ddgddg      j=                  d      | _        |jA                         D ci c]J  }|t	        jB                  | j>                  jD                  t        |      df         jG                  d
      L }}tI        jJ                  |jA                         dd      }tI        jL                  t        |j                               |d      jO                         j;                  ddgddg      d   | _(        tI        jJ                  |jA                         dd      }tI        jL                  t        |j                               |d      | _)        |
rS| jP                  jA                         }| jR                  jD                  |   | _)        d| jR                  jT                  _+        tI        jL                  t	        jX                  t        | jR                  jT                                    }| j.                  jZ                  D cg c]  }||j]                         vr| }}t        |      rtI        jJ                  |D cg c]  }|f c}dd      }tI        jL                  t	        j^                  t        |      t`              |d      }| jR                  jc                  |      | _)        tI        jL                  t	        jX                  t        | jR                  jT                                    }|je                         }|jg                         rt#        ||         }t        d|       |j]                         | _4        t	        jj                  | jR                        | _6        | j.                  jD                  ||f   | _        d| _7        d| _8        d}g | _9        | jR                  ju                         D ]  \  }}tw        ||| j.                  || j                        }| xjn                  |jx                  z  c_7        | xjp                  |j2                  z  c_8        ||jx                  z  }| jr                  jc                  |        |r| j                   nd| _=        | j                  dz  | _>        | jz                  | j|                  z   | _?        | j                  r| j                   nd| _@        | j                  | _A        | j                  | j                  z   | _B        | jn                  | j~                  z   | _<        | jp                  | j                  z   | _C        d | _D        y c c}w c c}w c c}w c c}w c c}w c c}w c c}w )N   z`factors` argument must an integer number of factors, a list of global factor names, or a dictionary, mapping observed variables to factors.zC`factor_orders` argument must either be an integer or a dictionary.zK`factor_multiplicities` argument must either be an integer or a dictionary.r   z+The model must contain at least one factor.zNumber of factors (zE) cannot be greater than the number of monthly endogenous variables (z).axiscountfactorFT)	ascendingblock)tupleize_colsname)indexr[   orderdtypezfEach factor can be assigned to at most one block of factors in `factor_orders`. Duplicate entries for r(   )E	k_endog_Mr5   k_endogidiosyncratic_ar1r>   
issubdtypetypeinteger
isinstancelisttupledict
ValueErrorr/   rangevaluesextendset_apply_factor_multiplicitiesr)   factor_ordersfactor_multiplicities_construct_endog_factor_mapr3   shaper0   sumrenamereset_indexsort_values	set_indexloading_countskeys
atleast_1dr2   meanpdIndexSeriesto_frameblock_loading_countsfactor_block_ordersr\   r[   concatenatecolumnstolistonesintappend
duplicatedanyr.   r6   max_factor_orderk_states_factorsk_posdef_factorsfactor_blocksitemsr&   r8   k_states_idio_Mk_states_idio_Qk_states_idiok_posdef_idio_Mk_posdef_idio_Qk_posdef_idiok_posdef_endog_factor_iloc)r9   r`   r5   endog_namesr)   rp   rq   rb   factors_is_intfactors_is_listorders_is_intmult_is_intr.   ir[   _factor_namesvalfactor_namerY   r   ixrz   missingdefault_block_orders
duplicatesduplicate_namesr4   r1   s                               r:   r;   zDynamicFactorMQStates.__init__@  ss    #"~~6!2 tG}bjjA$WtUm<d=&92::F ($%!mmD)>$?L/7D) ) * * M4!@ 9 : :z*?F < = = _GqL$W): !NOO#G}05g?11#??9DEt\!_,EGE>># 	&C  %	&=)0<>!, )-7 >M >8D%F)4 &12G%G %F! %F "&!B!B]$9"; *%:" !% @ @[!"..44Q7 >>DNN*24>>2B C,,0NN+;2? @ @ !!%%1%-44W={{GX+>6;T]  +  D8$	 	 '++- /  2==##''UW(<=??Ctt|L /  / XX*//1"$$&II%,,./7%$$,HJ{{'"udm 0; 0==D%F! XXm((*%gN#%99%%'($B  ,,113D'+'?'?'C'CD'ID$29D$$**/ yyNN4 8 8 > >?@B$($9$9$A$A 9D,"5"5"77  9 9w<WEkK>E(-G=B#%99RWWSWC-H35G$E  ((//0DE $99tD$<$<$B$BCDFL!,,.
>>!,z":;O 77F6GI J J )//1 "t'?'? @
 !!%%k<&?@ 	
 !" !*.*B*B*H*H*J 	-&L,l $ 5 5| $0E !!U^^3!!!U__4!ENN*L%%e,	- 2Ct~~#~~1!11D4H4HH 261G1Gt~~Q#~~!11D4H4HH --0B0BB--0B0BB #'G  @E>%F@ /B9 Fs+   /
_5?_:
_?
`8A`	`
`c           
         i }|j                         D ]`  \  }}g }|D ]O  }|j                  |d      }	|	dkD  r%|t        |	      D 
cg c]  }
| d|
dz     c}
z  }?|j                  |       Q |||<   b i }|j                         D ]q  \  }}t	        |t
              s|f}g }|D ]D  }|j                  |d      }	|	dkD  r%|t        |	      D 
cg c]  }
| d|
dz     c}
z  }?||gz  }F ||t        |      <   s ||fS c c}
w c c}
w )a  
        Expand `factors` and `factor_orders` to account for factor multiplity.

        For example, if there is a `global` factor with multiplicity 2, then
        this method expands that into `global.1` and `global.2` in both the
        `factors` and `factor_orders` dictionaries.

        Parameters
        ----------
        factors : dict
            Dictionary of {endog_name: list of factor names}
        factor_orders : dict
            Dictionary of {tuple of factor names: factor order}
        factor_multiplicities : dict
            Dictionary of {factor name: factor multiplicity}

        Returns
        -------
        new_factors : dict
            Dictionary of {endog_name: list of factor names}, with factor names
            expanded to incorporate multiplicities.
        new_factors : dict
            Dictionary of {tuple of factor names: factor order}, with factor
            names in each tuple expanded to incorporate multiplicities.
        rS   .)r   getrk   r   rf   rh   )r9   r)   rp   rq   new_factors
endog_namefactors_listnew_factor_listr   nr   new_factor_ordersrY   r1   	new_blocks                  r:   ro   z2DynamicFactorMQStates._apply_factor_multiplicities  sm   8 (/ 		6$J O+ 8)--k1=q5#16q(;,- ,7-qQ(@ (; ;O $**;78 '6K
#		6 #0#6#6#8 	?E<eU+I$ /)--k1=q5+08"5&' &1M1q5'": "5 5I +.I/ 3?eI./	? ---+(;"5s   D 
D
c                    g }|j                         D ];  \  }}t        |t        t        f      rt	        |      dk(  s+|j                  |       = t	        |      rt        d| d      t        |      j                  t        |j                                     }t	        |      rt        d| d      i }|j                         D ];  \  }}t        |t              rd||<   |j                  |D ci c]  }|d c}       = t        |j                               }t	        |      }t        j                  t        j                  | j                   |ft"              t        j$                  |d      t        j$                  |d      	      }	|j                         D ]  \  }}d
|	j&                  ||f<    |	S c c}w )as  
        Construct mapping of observed variables to factors.

        Parameters
        ----------
        factors : dict
            Dictionary of {endog_name: list of factor names}
        endog_names : list of str
            List of the names of the observed variables.

        Returns
        -------
        endog_factor_map : pd.DataFrame
            Boolean dataframe with `endog_names` as the index and the factor
            names (computed from the `factors` input) as the columns. Each cell
            is True if the associated factor is allowed to load on the
            associated observed variable.

        r   zyEach observed variable must be mapped to at least one factor in the `factors` dictionary. Variables missing factors are: r   zwIf a `factors` dictionary is provided, then it must include entries for each observed variable. Missing variables are: r^   endog)r[   rW   r\   r   T)r   rf   rg   rh   r/   r   rj   rn   
differencerz   strupdater}   	DataFramer>   zerosra   boolr~   r2   )
r9   r)   r   r   keyvaluer.   vr0   r3   s
             r:   rr   z1DynamicFactorMQStates._construct_endog_factor_map'  s   , !--/ 	$JCedE]3s5zQs#	$ w< @@GyK L L k"--c',,..ABw< BBI!M N N !--/ 	;JC%%&'U###5$9aQT$9:		;
 L--/0%	<<HHdllI.d;((;W5HH\9; "--/ 	4JC/3  e,	4   %:s   3
F<
c                     t        j                  | j                        t        fd| j                  D              }t        j
                  |      S )zFactors.c              3   <   K   | ]  }|j                        y wN)r,   ).0rY   r   s     r:   	<genexpr>z3DynamicFactorMQStates.factors_L1.<locals>.<genexpr>h  s     JeR(()Js   )r>   r@   r   rh   r   r   )r9   ilocr   s     @r:   r,   z DynamicFactorMQStates.factors_L1d  s>     YYt,,-Jt7I7IJJ~~d##r<   c                    t        j                  | j                        }g }| j                  D ]:  }|j	                  ||j
                     j                  d|j                               < t        j                  |d      S )z3Factors plus any lags, index shaped (5, k_factors).r(   rS   rT   )	r>   r@   r   r   r   r-   r?   r0   r   )r9   r   r   rY   s       r:   factors_L1_5_ixz%DynamicFactorMQStates.factors_L1_5_ixk  sm     YYt,,-'' 	LEKK5--.66q%//JK	L~~d++r<   c                     | j                   }| j                  r|| j                  z   }n|| j                  z   }t        j
                  || S )z2Idiosyncratic AR states, (first block / lag only).)r   rb   ra   r5   r>   rE   r9   ix1ix2s      r:   
idio_ar_L1z DynamicFactorMQStates.idio_ar_L1t  sD     ##!!$C&CuuS~r<   c                 z    | j                   }|}| j                  r|| j                  z  }t        j                  || S )z.Idiosyncratic AR states for monthly variables.)r   rb   r`   r>   rE   r   s      r:   	idio_ar_MzDynamicFactorMQStates.idio_ar_M~  s;     ##!!4>>!CuuS~r<   c                     | j                   }| j                  r|| j                  z  }|| j                  dz  z   }t        j
                  || S )z=Idiosyncratic AR states and all lags for quarterly variables.r(   )r   rb   r`   r5   r>   rE   r   s      r:   	idio_ar_QzDynamicFactorMQStates.idio_ar_Q  sI     ##!!4>>!CDNNQ&&uuS~r<   c                     | j                   }| j                  r|| j                  z  }|t        j                  t        j
                  d| j                  z        d| j                  f      j                  z   S )z<Idiosyncratic AR (quarterly) state index, (k_endog_Q, lags).r(   )r   rb   r`   r>   r?   r@   r5   rA   )r9   starts     r:   idio_ar_Q_ixz"DynamicFactorMQStates.idio_ar_Q_ix  sf     %%!!T^^#E

		!dnn,-4>>/BDDEAF 	Gr<   c                     | j                   ag }t        | j                        D ]@  }|j                  t	        j
                  | j                  j                  |         d          B || _         | j                   S )z?List of list of int, factor indexes for each observed variable.r   )r   rk   ra   r   r>   wherer3   r   )r9   ilocsr   s      r:   endog_factor_ilocz'DynamicFactorMQStates.endog_factor_iloc  sn    
 ""*E4<<( IRXXd&;&;&@&@&CDQGHI&+D#&&&r<   c                 8    |dv rt        | |      S t        |      )z
        Use square brackets to access index / slice elements.

        This is convenient in highlighting the indexing / slice quality of
        these attributes in the code below.
        )r,   r   r   r   r   r   )getattrKeyError)r9   r   s     r:   __getitem__z!DynamicFactorMQStates.__getitem__  s(      0 04%%3-r<   N)rJ   rK   rL   rM   r;   ro   rr   rN   r,   r   r   r   r   r   r   r   rO   r<   r:   rQ   rQ      s    qfl'\7.r; z $ $ , ,       G G 	' 	' r<   rQ   c                       e Zd ZdZ	 	 	 	 d fd	Zed        Z	 	 ddZed        Z	d Z
d dZed        Zd!d	Zd
 Zed        Zed        Zed        Zd Zd Z fdZed        Zd Z	 	 	 	 	 	 	 d" fd	Z	 	 	 	 	 d#dZd dZd!dZd!dZd$dZd$dZ	 	 	 	 d% fd	Z	 	 	 	 d& fd	Z	 	 	 	 	 d' fd	Z 	 	 	 	 	 d( fd	Z! xZ"S ))DynamicFactorMQuej  
    Dynamic factor model with EM algorithm; option for monthly/quarterly data.

    Implementation of the dynamic factor model of Bańbura and Modugno (2014)
    ([1]_) and Bańbura, Giannone, and Reichlin (2011) ([2]_). Uses the EM
    algorithm for parameter fitting, and so can accommodate a large number of
    left-hand-side variables. Specifications can include any collection of
    blocks of factors, including different factor autoregression orders, and
    can include AR(1) processes for idiosyncratic disturbances. Can
    incorporate monthly/quarterly mixed frequency data along the lines of
    Mariano and Murasawa (2011) ([4]_). A special case of this model is the
    Nowcasting model of Bok et al. (2017) ([3]_). Moreover, this model can be
    used to compute the news associated with updated data releases.

    Parameters
    ----------
    endog : array_like
        Observed time-series process :math:`y`. See the "Notes" section for
        details on how to set up a model with monthly/quarterly mixed frequency
        data.
    k_endog_monthly : int, optional
        If specifying a monthly/quarterly mixed frequency model in which the
        provided `endog` dataset contains both the monthly and quarterly data,
        this variable should be used to indicate how many of the variables
        are monthly. Note that when using the `k_endog_monthly` argument, the
        columns with monthly variables in `endog` should be ordered first, and
        the columns with quarterly variables should come afterwards. See the
        "Notes" section for details on how to set up a model with
        monthly/quarterly mixed frequency data.
    factors : int, list, or dict, optional
        Integer giving the number of (global) factors, a list with the names of
        (global) factors, or a dictionary with:

        - keys : names of endogenous variables
        - values : lists of factor names.

        If this is an integer, then the factor names will be 0, 1, .... The
        default is a single factor that loads on all variables. Note that there
        cannot be more factors specified than there are monthly variables.
    factor_orders : int or dict, optional
        Integer describing the order of the vector autoregression (VAR)
        governing all factor block dynamics or dictionary with:

        - keys : factor name or tuples of factor names in a block
        - values : integer describing the VAR order for that factor block

        If a dictionary, this defines the order of the factor blocks in the
        state vector. Otherwise, factors are ordered so that factors that load
        on more variables come first (and then alphabetically, to break ties).
    factor_multiplicities : int or dict, optional
        This argument provides a convenient way to specify multiple factors
        that load identically on variables. For example, one may want two
        "global" factors (factors that load on all variables) that evolve
        jointly according to a VAR. One could specify two global factors in the
        `factors` argument and specify that they are in the same block in the
        `factor_orders` argument, but it is easier to specify a single global
        factor in the `factors` argument, and set the order in the
        `factor_orders` argument, and then set the factor multiplicity to 2.

        This argument must be an integer describing the factor multiplicity for
        all factors or dictionary with:

        - keys : factor name
        - values : integer describing the factor multiplicity for the factors
          in the given block

    idiosyncratic_ar1 : bool
        Whether or not to model the idiosyncratic component for each series as
        an AR(1) process. If False, the idiosyncratic component is instead
        modeled as white noise.
    standardize : bool or tuple, optional
        If a boolean, whether or not to standardize each endogenous variable to
        have mean zero and standard deviation 1 before fitting the model. See
        "Notes" for details about how this option works with postestimation
        output. If a tuple (usually only used internally), then the tuple must
        have length 2, with each element containing a Pandas series with index
        equal to the names of the endogenous variables. The first element
        should contain the mean values and the second element should contain
        the standard deviations. Default is True.
    endog_quarterly : pandas.Series or pandas.DataFrame
        Observed quarterly variables. If provided, must be a Pandas Series or
        DataFrame with a DatetimeIndex or PeriodIndex at the quarterly
        frequency. See the "Notes" section for details on how to set up a model
        with monthly/quarterly mixed frequency data.
    init_t0 : bool, optional
        If True, this option initializes the Kalman filter with the
        distribution for :math:`\alpha_0` rather than :math:`\alpha_1`. See
        the "Notes" section for more details. This option is rarely used except
        for testing. Default is False.
    obs_cov_diag : bool, optional
        If True and if `idiosyncratic_ar1 is True`, then this option puts small
        positive values in the observation disturbance covariance matrix. This
        is not required for estimation and is rarely used except for testing.
        (It is sometimes used to prevent numerical errors, for example those
        associated with a positive semi-definite forecast error covariance
        matrix at the first time step when using EM initialization, but state
        space models in Statsmodels switch to the univariate approach in those
        cases, and so do not need to use this trick). Default is False.

    Notes
    -----
    The basic model is:

    .. math::

        y_t & = \Lambda f_t + \epsilon_t \\
        f_t & = A_1 f_{t-1} + \dots + A_p f_{t-p} + u_t

    where:

    - :math:`y_t` is observed data at time t
    - :math:`\epsilon_t` is idiosyncratic disturbance at time t (see below for
      details, including modeling serial correlation in this term)
    - :math:`f_t` is the unobserved factor at time t
    - :math:`u_t \sim N(0, Q)` is the factor disturbance at time t

    and:

    - :math:`\Lambda` is referred to as the matrix of factor loadings
    - :math:`A_i` are matrices of autoregression coefficients

    Furthermore, we allow the idiosyncratic disturbances to be serially
    correlated, so that, if `idiosyncratic_ar1=True`,
    :math:`\epsilon_{i,t} = \rho_i \epsilon_{i,t-1} + e_{i,t}`, where
    :math:`e_{i,t} \sim N(0, \sigma_i^2)`. If `idiosyncratic_ar1=False`,
    then we instead have :math:`\epsilon_{i,t} = e_{i,t}`.

    This basic setup can be found in [1]_, [2]_, [3]_, and [4]_.

    We allow for two generalizations of this model:

    1. Following [2]_, we allow multiple "blocks" of factors, which are
       independent from the other blocks of factors. Different blocks can be
       set to load on different subsets of the observed variables, and can be
       specified with different lag orders.
    2. Following [4]_ and [2]_, we allow mixed frequency models in which both
       monthly and quarterly data are used. See the section on "Mixed frequency
       models", below, for more details.

    Additional notes:

    - The observed data may contain arbitrary patterns of missing entries.

    **EM algorithm**

    This model contains a potentially very large number of parameters, and it
    can be difficult and take a prohibitively long time to numerically optimize
    the likelihood function using quasi-Newton methods. Instead, the default
    fitting method in this model uses the EM algorithm, as detailed in [1]_.
    As a result, the model can accommodate datasets with hundreds of
    observed variables.

    **Mixed frequency data**

    This model can handle mixed frequency data in two ways. In this section,
    we only briefly describe this, and refer readers to [2]_ and [4]_ for all
    details.

    First, because there can be arbitrary patterns of missing data in the
    observed vector, one can simply include lower frequency variables as
    observed in a particular higher frequency period, and missing otherwise.
    For example, in a monthly model, one could include quarterly data as
    occurring on the third month of each quarter. To use this method, one
    simply needs to combine the data into a single dataset at the higher
    frequency that can be passed to this model as the `endog` argument.
    However, depending on the type of variables used in the analysis and the
    assumptions about the data generating process, this approach may not be
    valid.

    For example, suppose that we are interested in the growth rate of real GDP,
    which is measured at a quarterly frequency. If the basic factor model is
    specified at a monthly frequency, then the quarterly growth rate in the
    third month of each quarter -- which is what we actually observe -- is
    approximated by a particular weighted average of unobserved monthly growth
    rates. We need to take this particular weight moving average into account
    in constructing our model, and this is what the second approach does.

    The second approach follows [2]_ and [4]_ in constructing a state space
    form to explicitly model the quarterly growth rates in terms of the
    unobserved monthly growth rates. To use this approach, there are two
    methods:

    1. Combine the monthly and quarterly data into a single dataset at the
       monthly frequency, with the monthly data in the first columns and the
       quarterly data in the last columns. Pass this dataset to the model as
       the `endog` argument and give the number of the variables that are
       monthly as the `k_endog_monthly` argument.
    2. Construct a monthly dataset as a Pandas DataFrame with a DatetimeIndex
       or PeriodIndex at the monthly frequency and separately construct a
       quarterly dataset as a Pandas DataFrame with a DatetimeIndex or
       PeriodIndex at the quarterly frequency. Pass the monthly DataFrame to
       the model as the `endog` argument and pass the quarterly DataFrame to
       the model as the `endog_quarterly` argument.

    Note that this only incorporates one particular type of mixed frequency
    data. See also Banbura et al. (2013). "Now-Casting and the Real-Time Data
    Flow." for discussion about other types of mixed frequency data that are
    not supported by this framework.

    **Nowcasting and the news**

    Through its support for monthly/quarterly mixed frequency data, this model
    can allow for the nowcasting of quarterly variables based on monthly
    observations. In particular, [2]_ and [3]_ use this model to construct
    nowcasts of real GDP and analyze the impacts of "the news", derived from
    incoming data on a real-time basis. This latter functionality can be
    accessed through the `news` method of the results object.

    **Standardizing data**

    As is often the case in formulating a dynamic factor model, we do not
    explicitly account for the mean of each observed variable. Instead, the
    default behavior is to standardize each variable prior to estimation. Thus
    if :math:`y_t` are the given observed data, the dynamic factor model is
    actually estimated on the standardized data defined by:

    .. math::

        x_{i, t} = (y_{i, t} - \bar y_i) / s_i

    where :math:`\bar y_i` is the sample mean and :math:`s_i` is the sample
    standard deviation.

    By default, if standardization is applied prior to estimation, results such
    as in-sample predictions, out-of-sample forecasts, and the computation of
    the "news"  are reported in the scale of the original data (i.e. the model
    output has the reverse transformation applied before it is returned to the
    user).

    Standardization can be disabled by passing `standardization=False` to the
    model constructor.

    **Identification of factors and loadings**

    The estimated factors and the factor loadings in this model are only
    identified up to an invertible transformation. As described in (the working
    paper version of) [2]_, while it is possible to impose normalizations to
    achieve identification, the EM algorithm does will converge regardless.
    Moreover, for nowcasting and forecasting purposes, identification is not
    required. This model does not impose any normalization to identify the
    factors and the factor loadings.

    **Miscellaneous**

    There are two arguments available in the model constructor that are rarely
    used but which deserve a brief mention: `init_t0` and `obs_cov_diag`. These
    arguments are provided to allow exactly matching the output of other
    packages that have slight differences in how the underlying state space
    model is set up / applied.

    - `init_t0`: state space models in Statsmodels follow Durbin and Koopman in
      initializing the model with :math:`\alpha_1 \sim N(a_1, P_1)`. Other
      implementations sometimes initialize instead with
      :math:`\alpha_0 \sim N(a_0, P_0)`. We can accommodate this by prepending
      a row of NaNs to the observed dataset.
    - `obs_cov_diag`: the state space form in [1]_ incorporates non-zero (but
      very small) diagonal elements for the observation disturbance covariance
      matrix.

    Examples
    --------
    Constructing and fitting a `DynamicFactorMQ` model.

    >>> data = sm.datasets.macrodata.load_pandas().data.iloc[-100:]
    >>> data.index = pd.period_range(start='1984Q4', end='2009Q3', freq='Q')
    >>> endog = data[['infl', 'tbilrate']].resample('M').last()
    >>> endog_Q = np.log(data[['realgdp', 'realcons']]).diff().iloc[1:] * 400

    **Basic usage**

    In the simplest case, passing only the `endog` argument results in a model
    with a single factor that follows an AR(1) process. Note that because we
    are not also providing an `endog_quarterly` dataset, `endog` can be a numpy
    array or Pandas DataFrame with any index (it does not have to be monthly).

    The `summary` method can be useful in checking the model specification.

    >>> mod = sm.tsa.DynamicFactorMQ(endog)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 1 factors in 1 blocks   # of factors:                    1
                  + AR(1) idiosyncratic   Idiosyncratic disturbances:  AR(1)
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ========================
    Dep. variable          0
    ------------------------
             infl          X
         tbilrate          X
        Factor blocks:
    =====================
         block      order
    ---------------------
             0          1
    =====================

    **Factors**

    With `factors=2`, there will be two independent factors that will each
    evolve according to separate AR(1) processes.

    >>> mod = sm.tsa.DynamicFactorMQ(endog, factors=2)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 2 factors in 2 blocks   # of factors:                    2
                  + AR(1) idiosyncratic   Idiosyncratic disturbances:  AR(1)
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ===================================
    Dep. variable          0          1
    -----------------------------------
             infl          X          X
         tbilrate          X          X
        Factor blocks:
    =====================
         block      order
    ---------------------
             0          1
             1          1
    =====================

    **Factor multiplicities**

    By instead specifying `factor_multiplicities=2`, we would still have two
    factors, but they would be dependent and would evolve jointly according
    to a VAR(1) process.

    >>> mod = sm.tsa.DynamicFactorMQ(endog, factor_multiplicities=2)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 2 factors in 1 blocks   # of factors:                    2
                  + AR(1) idiosyncratic   Idiosyncratic disturbances:  AR(1)
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ===================================
    Dep. variable        0.1        0.2
    -----------------------------------
             infl         X          X
         tbilrate         X          X
        Factor blocks:
    =====================
         block      order
    ---------------------
      0.1, 0.2          1
    =====================

    **Factor orders**

    In either of the above cases, we could extend the order of the (vector)
    autoregressions by using the `factor_orders` argument. For example, the
    below model would contain two independent factors that each evolve
    according to a separate AR(2) process:

    >>> mod = sm.tsa.DynamicFactorMQ(endog, factors=2, factor_orders=2)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 2 factors in 2 blocks   # of factors:                    2
                  + AR(1) idiosyncratic   Idiosyncratic disturbances:  AR(1)
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ===================================
    Dep. variable          0          1
    -----------------------------------
             infl          X          X
         tbilrate          X          X
        Factor blocks:
    =====================
         block      order
    ---------------------
             0          2
             1          2
    =====================

    **Serial correlation in the idiosyncratic disturbances**

    By default, the model allows each idiosyncratic disturbance terms to evolve
    according to an AR(1) process. If preferred, they can instead be specified
    to be serially independent by passing `ididosyncratic_ar1=False`.

    >>> mod = sm.tsa.DynamicFactorMQ(endog, idiosyncratic_ar1=False)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 1 factors in 1 blocks   # of factors:                    1
                    + iid idiosyncratic   Idiosyncratic disturbances:    iid
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ========================
    Dep. variable          0
    ------------------------
             infl          X
         tbilrate          X
        Factor blocks:
    =====================
         block      order
    ---------------------
             0          1
    =====================

    *Monthly / Quarterly mixed frequency*

    To specify a monthly / quarterly mixed frequency model see the (Notes
    section for more details about these models):

    >>> mod = sm.tsa.DynamicFactorMQ(endog, endog_quarterly=endog_Q)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 1 factors in 1 blocks   # of quarterly variables:        2
                + Mixed frequency (M/Q)   # of factors:                    1
                  + AR(1) idiosyncratic   Idiosyncratic disturbances:  AR(1)
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ========================
    Dep. variable          0
    ------------------------
             infl          X
         tbilrate          X
          realgdp          X
         realcons          X
        Factor blocks:
    =====================
         block      order
    ---------------------
             0          1
    =====================

    *Customize observed variable / factor loadings*

    To specify that certain that certain observed variables only load on
    certain factors, it is possible to pass a dictionary to the `factors`
    argument.

    >>> factors = {'infl': ['global']
    ...            'tbilrate': ['global']
    ...            'realgdp': ['global', 'real']
    ...            'realcons': ['global', 'real']}
    >>> mod = sm.tsa.DynamicFactorMQ(endog, endog_quarterly=endog_Q)
    >>> print(mod.summary())
                        Model Specification: Dynamic Factor Model
    ==========================================================================
    Model:         Dynamic Factor Model   # of monthly variables:          2
                + 2 factors in 2 blocks   # of quarterly variables:        2
                + Mixed frequency (M/Q)   # of factor blocks:              2
                  + AR(1) idiosyncratic   Idiosyncratic disturbances:  AR(1)
    Sample:                     1984-10   Standardize variables:        True
                              - 2009-09
    Observed variables / factor loadings
    ===================================
    Dep. variable     global       real
    -----------------------------------
             infl       X
         tbilrate       X
          realgdp       X           X
         realcons       X           X
        Factor blocks:
    =====================
         block      order
    ---------------------
        global          1
          real          1
    =====================

    **Fitting parameters**

    To fit the model, use the `fit` method. This method uses the EM algorithm
    by default.

    >>> mod = sm.tsa.DynamicFactorMQ(endog)
    >>> res = mod.fit()
    >>> print(res.summary())
                              Dynamic Factor Results
    ==========================================================================
    Dep. Variable:      ['infl', 'tbilrate']   No. Observations:         300
    Model:              Dynamic Factor Model   Log Likelihood       -127.909
                     + 1 factors in 1 blocks   AIC                   271.817
                       + AR(1) idiosyncratic   BIC                   301.447
    Date:                   Tue, 04 Aug 2020   HQIC                  283.675
    Time:                           15:59:11   EM Iterations              83
    Sample:                       10-31-1984
                                - 09-30-2009
    Covariance Type:            Not computed
                        Observation equation:
    ==============================================================
    Factor loadings:          0    idiosyncratic: AR(1)       var.
    --------------------------------------------------------------
                infl      -0.67                    0.39       0.73
            tbilrate      -0.63                    0.99       0.01
           Transition: Factor block 0
    =======================================
                     L1.0    error variance
    ---------------------------------------
             0       0.98              0.01
    =======================================
    Warnings:
    [1] Covariance matrix not calculated.

    *Displaying iteration progress*

    To display information about the EM iterations, use the `disp` argument.

    >>> mod = sm.tsa.DynamicFactorMQ(endog)
    >>> res = mod.fit(disp=10)
    EM start iterations, llf=-291.21
    EM iteration 10, llf=-157.17, convergence criterion=0.053801
    EM iteration 20, llf=-128.99, convergence criterion=0.0035545
    EM iteration 30, llf=-127.97, convergence criterion=0.00010224
    EM iteration 40, llf=-127.93, convergence criterion=1.3281e-05
    EM iteration 50, llf=-127.92, convergence criterion=5.4725e-06
    EM iteration 60, llf=-127.91, convergence criterion=2.8665e-06
    EM iteration 70, llf=-127.91, convergence criterion=1.6999e-06
    EM iteration 80, llf=-127.91, convergence criterion=1.1085e-06
    EM converged at iteration 83, llf=-127.91,
       convergence criterion=9.9004e-07 < tolerance=1e-06

    **Results: forecasting, impulse responses, and more**

    One the model is fitted, there are a number of methods available from the
    results object. Some examples include:

    *Forecasting*

    >>> mod = sm.tsa.DynamicFactorMQ(endog)
    >>> res = mod.fit()
    >>> print(res.forecast(steps=5))
                 infl  tbilrate
    2009-10  1.784169  0.260401
    2009-11  1.735848  0.305981
    2009-12  1.730674  0.350968
    2010-01  1.742110  0.395369
    2010-02  1.759786  0.439194

    *Impulse responses*

    >>> mod = sm.tsa.DynamicFactorMQ(endog)
    >>> res = mod.fit()
    >>> print(res.impulse_responses(steps=5))
           infl  tbilrate
    0 -1.511956 -1.341498
    1 -1.483172 -1.315960
    2 -1.454937 -1.290908
    3 -1.427240 -1.266333
    4 -1.400069 -1.242226
    5 -1.373416 -1.218578

    For other available methods (including in-sample prediction, simulation of
    time series, extending the results to incorporate new data, and the news),
    see the documentation for state space models.

    References
    ----------
    .. [1] Bańbura, Marta, and Michele Modugno.
           "Maximum likelihood estimation of factor models on datasets with
           arbitrary pattern of missing data."
           Journal of Applied Econometrics 29, no. 1 (2014): 133-160.
    .. [2] Bańbura, Marta, Domenico Giannone, and Lucrezia Reichlin.
           "Nowcasting."
           The Oxford Handbook of Economic Forecasting. July 8, 2011.
    .. [3] Bok, Brandyn, Daniele Caratelli, Domenico Giannone,
           Argia M. Sbordone, and Andrea Tambalotti. 2018.
           "Macroeconomic Nowcasting and Forecasting with Big Data."
           Annual Review of Economics 10 (1): 615-43.
           https://doi.org/10.1146/annurev-economics-080217-053214.
    .. [4] Mariano, Roberto S., and Yasutomo Murasawa.
           "A coincident index, common factors, and monthly real GDP."
           Oxford Bulletin of Economics and Statistics 72, no. 1 (2010): 27-46.

    c                 P   |"|t        d      | j                  ||      \  }}t        |d       }|r+t        |t        j
                        rH|j                         }n7t        j                  |      dk  rt        j                  |      j                  }||j                  d   }|r|j                  j                         }nA|j                  d   dk(  rdg}n+t        |j                  d         D cg c]
  }d|dz     }}t        |d      | _        |j                  d   | j                   z
  | _        t%        | j                   | j"                  |||||      x}| _        || _        || _        || _        | j&                  j.                  | _        | j&                  j0                  | _        | j&                  j2                  | _        | j&                  j4                  | _        t7        | j0                        | _        | j&                  j:                  | _        || _        |	| _        |
| _         | j>                  r|r[t	        jB                  |jD                  d   dz
  |jD                  d   |jD                  jF                        }|jI                  |      }nHt        jJ                  t        jL                  g|j                  d   z  |j                  f   j                  }t        |tN              rt7        |      dk(  rz|\  }}|j                  d   }t        |t        j
                        rJ|jD                  jQ                  t	        jR                  |            st        d	| d
|jD                   d      t        jT                  |      }t        |t        j
                        rJ|jD                  jQ                  t	        jR                  |            st        d	| d
|jD                   d      t        jT                  |      }t        j                  |      |fk7  st        j                  |      |fk7  rt        d| d      d}|rt	        j
                  ||      }t	        j
                  ||      }n}|dv r%|jW                  d      }|jY                  d      }nT|dv rEt        jZ                  |j                  d         }t        j\                  |j                  d         }nt        d      || _/        || _0        || _1        t        jd                  | j`                  dk        rZt        jf                  | j`                  dk        }t        jh                  |      |d      j                         }t        d| d      | jb                  r|| j^                  z
  | j`                  z  }t        jj                  d | j                    t        jj                  | j                   d  dx}| _6        to        |   |f|jr                  |jt                  d| | jb                  r?| jv                  jx                  | j`                  z  | j^                  z   | jv                  _<        d|vr)| jz                  j}                  | j                                | j<                  r+t        j                  | j                         | d|d   |d   f<   g d}t        t7        |            D ]<  }||   }|t        j                  | j"                        z  | d|d   |d   d d |f   f<   > | j@                  r%t        j                  | j                        dz  | d <   |j                  D ]r  }|j4                  dk(  rd}n+t        jZ                  |j4                  |j4                  f      }t        dg|g|j                  z  z         j                  | d!|d"   |d"   f<   t | j"                  dk(  rd}n+t        jZ                  | j"                  | j"                  f      }t        dg|gd#z  z         j                  | d!|d$   |d$   f<   dx}}|j                  D ]D  }||j4                  z  }t        j                  |j4                        | d%|d&   d d df   ||f<   |}F | j<                  r;|| j                   z   }t        j                  | j                         | d%|d   ||f<   |}|| j"                  z   }t        j                  | j"                        | d%|d   d d df   ||f<   t        d't        j                  | j.                  j                        fd(t        j                  |j                  D cg c]  }|j4                  dz  |j                  z    c}      fd)t        j                  |j                  D cg c]!  }|j4                  |j4                  dz   z  dz  # c}      fd*| j<                  r| j                  ndfd+| j                  fg      | _I        t        j                  t        | j                  j                                     | _K        t        j                  t        j                  | j                        t        j                  t        | j                  j                                     d d       }t        t        | j                  j                         |            | _R        i | _S        | xj                  g d,t        |j                               z   z  c_T        y c c}w c c}w c c}w )-NzIf `endog_quarterly` is specified, then `endog` must contain only monthly variables, and so `k_endog_monthly` cannot be specified since it will be inferred from the shape of `endog`.   rS   yk_endog_monthlyr   )freqzLInvalid value passed for `standardize`: if a Pandas Series, must have index z. Got r   zEInvalid value passed for `standardize`: each element must be shaped (z,).Tr\   )rS   TrT   )r   Fz'Invalid value passed for `standardize`.绽|=zwConstant variable(s) found in observed variables, but constants cannot be included in this model. These variables are: )MQ)r8   r   r   designr   r   rS   r      r   rS   r   r   -C6?obs_cov
transitionr)   r(   r   	selectionr+   loadings	factor_ar
factor_covrb   idiosyncratic_var)r)   rp   rq   rb   standardizeinit_t0obs_cov_diag)Urj   construct_endogr
   rf   r}   r   r   r>   ndim
atleast_2drA   rs   r   r   rk   r   r`   r5   rQ   _sr)   rp   rq   r3   r   r.   r0   r/   k_factor_blocksr   rb   r   r   period_ranger\   r   reindexc_nanrh   equalsr~   r{   r|   stdr   r   _endog_mean
_endog_stdr   r   r   arrayrE   _osuperr;   r8   r   data
orig_endogssm
initialize_default_initializationeyera   r   r   r7   r   rt   rl   r1   paramsrg   k_paramssplitr@   cumsumri   ziprz   _p_loading_constraints
_init_keys)r9   r   r   r)   rp   rq   rb   r   endog_quarterlyr   r   kwargsendog_is_pandasr   r   sr   
endog_mean	endog_stdr   namesrC   multipliersmrY   tmpr   r   	__class__s                               r:   r;   zDynamicFactorMQ.__init__  s	   
 &*  ": ; ;
 &*%9%9&("E?*5$7%+(wwu~!e,.."#kk!nO--..0K{{1~""e49%++a.4IJq1q5'{JJ!/3DEQ$..8 ,NNDNNK02CE 	EDG
 *%:" $ 8 8#'77#>#>  GG00**"4#;#;< $ 8 8!2(<<__U[[^a%7R*/++*:*:<b)rvvhQ7@ACC
 k5)c+.>!.C$/!J	 AA:ryy1$$++BHH[,AB  "%%0M
8H8H7I"L M M  ]]:6
9bii0OO**288K+@A  "%%0M	7H"K L L MM)4	$,0Ct0K  "==>Cs"D E EK YYzE
IIi{C	I%+J		q	)IJ&%++a.1JA/IFGG%#&66$//E)*$//E12BHH[)"Q%0779E EEJG1N O O T---@E 't~~') 	)DG
 	 	#ajj 	#!	# 		$$t69I9II II  6)HH < < >?
 !!57VVDNN5KD1S61[>12%s;'( 	,AAABFF4>>** 1S61^#4QT#::;	,  ffT\\2T9DO __ 	GE!#hhAB !uu/B/B'B!BCEE uY/y1AAB	G >>QC((DNNDNN;<CaSC519_-// 	\1[>1[>9: c__ 	E5??"Cu' eL1!Q$7S@AC		
 !!&C9;9ODanc#g56CDNN"FF4>>" 	[!N+AqD13s7:; " 5 5 < <=>"&&/0"@&+ #(//1"4u7I7I"I "@ A B26601#A', $)??eoo6I#Ja#O #A B C  $ 6 6A? $,,/#1 2 tDKK$6$6$89: XXbii.iiT[[%7%7%9 :;CR@Bs4;;++-r23 %'! 	  #6;;=12 	2a K|"@#As   4l!#l)&l#c                 b   |d}t        |t        j                  t        j                  f      st	        d|z         |j
                  j                  dvrt	        d|z         t        |j
                  dd      d   dk(  s)t        |j
                  dd	      }t	        d
| d|z         d}t        |t        j                  t        j                  f      st	        d|z         |j
                  j                  dvrt	        d|z         t        |j
                  dd      d   dk(  s)t        |j
                  dd	      }t	        d| d|z         t        |j
                  d      r|j                  d      }t        |j
                  d      r|j                  d      }|j                         }|j
                  j                         |_        |j                  t              j                         }|j                  t              j                         }|j
                  j                         |_        t        j                   ||gd      }|j"                  j%                         }|j'                         dkD  r|j"                  j(                  j+                  t,              }|j
                  D ]?  }	|j.                  |	   }
|
dk(  r||	k(  }t1        |
      D cg c]  }|	 |dz     c}||<   A ||_        n|j                         }|j2                  }t5        |      dk(  r|d   nd}||fS c c}w )aR  
        Construct a combined dataset from separate monthly and quarterly data.

        Parameters
        ----------
        endog_monthly : array_like
            Monthly dataset. If a quarterly dataset is given, then this must
            be a Pandas object with a PeriodIndex or DatetimeIndex at a monthly
            frequency.
        endog_quarterly : array_like or None
            Quarterly dataset. If not None, then this must be a Pandas object
            with a PeriodIndex or DatetimeIndex at a quarterly frequency.

        Returns
        -------
        endog : array_like
            If both endog_monthly and endog_quarterly were given, this is a
            Pandas DataFrame with a PeriodIndex at the monthly frequency, with
            all of the columns from `endog_monthly` ordered first and the
            columns from `endog_quarterly` ordered afterwards. Otherwise it is
            simply the input `endog_monthly` dataset.
        k_endog_monthly : int
            The number of monthly variables (which are ordered first) in the
            returned `endog` dataset.
        zIf given both monthly and quarterly data then the monthly dataset must be a Pandas object with a date index at a monthly frequency.z.Given monthly dataset is not a Pandas object. )
datetime64periodz9Given monthly dataset has an index with non-date values. freqstrNr   r   NonezIndex of given monthly dataset has a non-monthly frequency (to check this, examine the `freqstr` attribute of the index of the dataset - it should start with M if it is monthly). Got z. zlIf a quarterly dataset is given, then it must be a Pandas object with a date index at a quarterly frequency.z0Given quarterly dataset is not a Pandas object. z;Given quarterly dataset has an index with non-date values. r   zIndex of given quarterly dataset has a non-quarterly frequency (to check this, examine the `freqstr` attribute of the index of the dataset - it should start with Q if it is quarterly). Got 	to_periodrS   rT   r   )rf   r}   r   r   rj   r\   inferred_typer   hasattrr!  copyto_timestampresampler   firstr   concatr   value_countsr6   rl   astypeobjectr2   rk   rs   r/   )clsendog_monthlyr  base_msgr  quarterly_resampr   column_countsr   r[   rV   maskr   rs   r   s                  r:   r   zDynamicFactorMQ.construct_endog  sd   8 &LH mbii-FG  "46>"? @ @$$22 ;E E  "ACK"L M M]00)SA!DK!-"5"5y&I  ")
 *1	"5
 8@"@ A A&H o		2<</HI  "46>"? @ @ &&44 =G G  "ACK"L M M_22IsCAF#M!/"7"7FK  ")
 *1	"5
 8@"@ A A }**K8 - 7 7 <,,k:"1";";C"@  /335%5%;%;%H%H%J"/88EKKM/88CIIK%5%;%;%E%E%G"II}.>?aHE "MM668M  "Q&--..55f=)// MD)--d3Ez "d?D?DU|$L!va!eW%5$LGDMM !(!&&(E##&)%jAo%(1o%% %Ms   L,c                     |r'| j                   r| j                  | j                  f|d<    | j                  |f||d|}|S )a  
        Clone state space model with new data and optionally new specification.

        Parameters
        ----------
        endog : array_like
            The observed time-series process :math:`y`
        k_endog_monthly : int, optional
            If specifying a monthly/quarterly mixed frequency model in which
            the provided `endog` dataset contains both the monthly and
            quarterly data, this variable should be used to indicate how many
            of the variables are monthly.
        endog_quarterly : array_like, optional
            Observations of quarterly variables. If provided, must be a
            Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at
            the quarterly frequency.
        kwargs
            Keyword arguments to pass to the new model class to change the
            model specification.

        Returns
        -------
        model : DynamicFactorMQ instance
        r   )r   r  )r   r   r   _clone_from_init_kwds)r9   r   r   r  retain_standardizationr  mods          r:   clonezDynamicFactorMQ.clone>  sW    4 "d&6&6%)%5%5t$GF=!(d((7#2+7/57 
r<   c                 2    dt         t        j                  fiS )Nfit)DynamicFactorMQResultsr   MLEResultsWrapperr9   s    r:   _res_classeszDynamicFactorMQ._res_classes_  s    .0J0JKLLr<   c                 d   | j                   }t        j                  | j                        }|j                  D ]  }|j                  |d   d        | j                  r=t        |d   j                  |d   j                        D ]  }|j                  |d        |j                  |d   d       |S )Nr)   
stationaryr   r   )
r   r   Initializationr8   r   rn   rb   rk   r   stop)r9   r  initrY   r   s        r:   r  z'DynamicFactorMQ._default_initializationc  s    GG,,T]];__ 	5EHHU9%|4	5!!1[>//;1D1DE *L)*;.r<   c                 F   ||du s| j                   dk(  rdnd}|du r|durt        d      ||du}| j                  }t        |t              s|g}|r|D cg c]  }t        |       }}|dur'|}|D cg c]  }t        |      |k  r|n|d | dz    }}|S c c}w c c}w )NFrS      z?Can only truncate endog names if they are returned as a string.z...)ra   rj   r   rf   rg   r   r/   )r9   truncate	as_stringr   r[   r   s         r:   _get_endog_namesz DynamicFactorMQ._get_endog_namesn  s     )U 2dlla6GuRH(%"7 : ; ; -I &&+t,&-K1<=3t9=K=5 A'24# $'t9>4tBQx%7GG 4K 4  >4s   B6Bc                     d| j                    d| j                   dg}| j                  dkD  r|j                  d       | j                  rdnd}|j                  | d       |S )	NzDynamic Factor Modelz factors in z blocksr   zMixed frequency (M/Q)AR(1)iidz idiosyncratic)r0   r   r5   r   rb   )r9   
model_name
error_types      r:   _model_namezDynamicFactorMQ._model_name  sr     #~~l4+?+?*@HJ
 >>A56 $ 6 6WE
ZL78r<   c                 D   | j                  |d      }d}| j                  r)| j                  }|d   }d|z  g}|d   }|dd|z  z   gz  }n#t        d      dt        | j                        z   g}| j
                  }g }|j                  d	|d   gf       t        d
t        |            D ]  }	|j                  dd||	   z   gf        |d|d   gfd|d
   gfgz  }g }
| j                  dkD  r"|
d| j                  gfd| j                  gfgz  }
n|
d| j                  gfgz  }
| j                  d
k(  r|
d| j                  gfgz  }
n|
d| j                  gfgz  }
|
d| j                  rdndgfd| j                  gfgz  }
t!               }| | _        |j%                  | ||
|       d
}| `| j&                  j)                  ddd      }||_        	 |j-                         }|D ]  \  }}||   dt        |      dz  z  z   ||<   ! d|j*                  _        |j5                         }|j6                  }|j8                  j;                  t              j=                         }d}d}t?        |||t@        |      }|jB                  jE                  ||       |d
z  }| jF                  j5                         }|d    j;                  d!       |d <   	 |d"g   j;                  t              |d"g<   |j6                  }|j8                  j;                  t              j=                         }d}d#}t?        |||t@        |      }|jB                  jE                  ||       |d
z  }|S # t.        $ r |j1                         }Y w xY w# t.        $ r  |d"g   jI                  t              |d"g<   Y w xY w)$a`  
        Create a summary table describing the model.

        Parameters
        ----------
        truncate_endog_names : int, optional
            The number of characters to show for names of observed variables.
            Default is 24 if there is more than one observed variable, or
            an unlimited number of there is only one.
        T)rD  rE  z)Model Specification: Dynamic Factor Modelr   z%sr   z- z - zModel:rS    z+ zSample:z# of monthly variables:z# of quarterly variables:z# of observed variables:z# of factors:z# of factor blocks:zIdiosyncratic disturbances:rH  rI  zStandardize variables:)gleftgrighttitleX)TF r   zDep. variableNz$Observed variables / factor loadingstxt_fmtrQ  rY   c                 $    dj                  |       S )Nz, )join)r.   s    r:   <lambda>z)DynamicFactorMQ.summary.<locals>.<lambda>  s    <!8 r<   r]   zFactor blocks:)%rF  _index_dates_indexr   nobsrL  r   rk   r/   r5   r`   ra   r   r0   rb   r   r#   modeladd_table_2colsr3   replacer\   r   AttributeError	iteritemsr[   rv   rl   r   mapr   r"   r$   tablesinsertr   applymap)r9   truncate_endog_namesr   rQ  r   dsamplerJ  top_leftr   	top_rightsummarytable_ixr  r   r[   colparams_dataparams_headerparams_stubstables                        r:   rj  zDynamicFactorMQ.summary  s    ++5I6: , < <B1AQhZF2AtdQh''F!fec$))n45F %%
 JqM?34q#j/* 	:AOOR$A"6!789	:$&) 	 	>>A*T^^,<=,t~~.>?A AI 5~FGGI1$?T^^,<=>>I043G3G2HIJJI4#'#9#9uEG/$2B2B1CDF 	F	 )
HY&+ 	  	-J $$,,C-CD 
	%JJLE  	?ID#dsc$i1n'=>DJ	?)

!kk((-4466e- 	h.A ''335W))8:W	<"G9o11#6D'O kk((-446 e- 	h.AS  	%NN$E	%4  	<"G9o66s;D'O	<s$   M M6 M32M36&NNc                 4    t        | j                               S )z+Summary tables showing model specification.)r   rj  r;  s    r:   __str__zDynamicFactorMQ.__str__   s    4<<>""r<   c           
      \   g }| j                   j                  D ]a  }||j                  dd D cg c]  }|  c}z  }t        d|j                        D ]%  }||j                  D cg c]
  }d| d|  c}z  }' c | j                         }| j                  r(|| j                  d      }||D cg c]  }d| 	 c}z  }|| j                  d      }||D cg c]  }d| 	 c}z  }t        dd	      D ]  }||D cg c]
  }d| d
|  c}z  } |S c c}w c c}w c c}w c c}w c c}w )zA(list of str) List of human readable names for unobserved states.NrS   Lr   r   zeps_M.r   zeps_Q.r(   z.eps_Q.)r   r   r.   rk   r7   rF  rb   r   )r9   state_namesrY   r[   r  r   endog_names_Mendog_names_Qs           r:   ru  zDynamicFactorMQ.state_names  sj    WW** 	@E%2D2DQ2GH$tfIHHK1e112 @,1,>,> @$( #$A3av  @ @@	@ ++-!!'5MFfTFOFFK#DGGCL1 	MBD&BBq! 	LA]KTas'$0KKK	L! I @ G CKs   
D%D
0DD$=D)c                    g }| j                  d      }|D ]a  }| j                  j                  D ]F  }|j                  D ]5  }| j                  j
                  ||f   s|j                  d| d|        7 H c | j                  j                  D ]Y  }|j                  D ]H  }|t        d|j                  dz         D cg c]  }|j                  D ]  }d| d| d|    c}}z  }J [ t        t        | j                  j                              D ]f  }| j                  j                  |   }|t        |j                        D 	
cg c]'  }	t        |	dz         D ]  }
d| d	|	dz    d
|
dz    d ) c}
}	z  }h | j                  rP|| j                  d      }||D cg c]  }d| 	 c}z  }|| j                  d      }||D cg c]  }d| 	 c}z  }||D cg c]  }d| 	 c}z  }|S c c}}w c c}
}	w c c}w c c}w c c}w )z5(list of str) List of human readable parameter names.FrE  zloading.z->rS   rt  r   zfb(z).cov.chol[,]r   z	L1.eps_M.r   z	L1.eps_Q.zsigma2.)rF  r   r   r.   r3   r2   r   rk   r1   r/   r0   rb   r   )r9   param_namesr   r   rY   r   	to_factorr   from_factorjkrv  r[   rw  s                 r:   r|  zDynamicFactorMQ.param_names  sr     ++e+<% 	DJ.. D#(#5#5 DK,,00[1HI#**&{m2j\BDDD	D WW** 	GE"// G	).q%2D2Dq2H)I G$%383E3E G$/ #$A3a}Byk B  G B  G GG	G s4770012 	3AGG))!,E%*5??%;3 !%*1q5\3 ! "!KAwaAwa@ 3@ 3 3K	3 !!'5M=I4iv.IIK'5M=I4iv.IIK 	[AT'$(AA- G3 J J Bs    #G2
,G8
!G>	HHc           	      x   t        j                  | j                  t         j                        }| j                  j
                  d| j                   }g }t        j                  t        j                  | j                        j                         j                         d      }| j                  D ]  }t        j                  |j                  dd|f         d   }t!        |      dk(  r3t        j                  | j                  j                  dd|f         d   }|dd|f   }t#        |ddd	      }|j%                  |j&                         |dd|fxx   |j(                  z  cc<    t        j*                  |d
      }g }	g }
t-        | j                        D ]  }| j.                  j0                  |   }|dd|f   }t3        | j                  dd|f   |d      }|j5                         }|	|j6                  j9                         z  }	|
j%                  |j:                          t-        | j                  | j<                        D ]  }| j.                  j0                  |   }t?        |dd|f   dd      }tA        | j                  dd|f   |d      }|jC                  | jE                  |            }|	|j6                  dt!        |       j9                         z  }	|
j%                  |jF                          |	|| jH                  d   <   d}g }g }d}| j.                  jJ                  D ]  }|dd|||jL                  z   f   }||jL                  z  }|jN                  dk(  r;|jL                  dk(  r@tQ        ||jN                  ddf      }|jR                  }|dd }|dd }|jR                  dd }n|jL                  dkD  rtU        |      }|j5                  |jN                  dd      }|j6                  jV                  jY                         }t         jZ                  j]                  |j^                        }|t        j`                  |         }t        jb                  t        jd                  ||jL                  |jL                  |jN                  f      d      }tg        dgti               z         }|setk        d|j                   d       ddd t        jl                  |jo                  d
            }|t        jp                  |jL                           }|j9                         z  }|j9                         z  } ||| jH                  d   <   ||| jH                  d   <   | jr                  rg }g } t-        | j                        D ]  }tQ        |
|   dd      }!|!jR                  }|j%                  t        jt                  |d   dd              | j%                  t        jt                  |d   d!t         jv                                t-        | j                  | j<                        D ]  }| j                  dd|f   jy                         }"|
|   |"t        jz                  |"       <   t}        |"      }!|!j5                  d"dd#      }#|!j                  |#d$d%      }#|j%                  t        jt                  |#d   dd              | j%                  t        jt                  |#d   d!t         jv                                ||| jH                  d&   <   | || jH                  d'   <   |S t-        | j                        D cg c]  }t        j                  |
|          } }t-        | j                  | j<                        D ]  }| j                  dd|f   jy                         }"|
|   |"t        jz                  |"       <   t}        |"      }!|!j5                  dd(      }#| j%                  t        jt                  |#d   d!t         jv                                | || jH                  d'   <   |S c c}w ))z>(array) Starting parameters for maximum likelihood estimation.r^   NW)requirementsr   rS   eigF)ncompmethod	normalizerT   drop)exogr      in)originalr   r   T)r]   r   r   )maxlagsictrend)r   r   rS   zPNon-stationary starting factor autoregressive parameters found for factor block z%. Using zeros as starting parameters.r   r   )rS   r   r   c)r]   r  gGzgGz?gh㈵>
   )maxiterreturn_paramsdispr(   )r  r  rb   r   )r  r  )Ar>   r   r	  float64r3   r   r`   requirer}   r   r   interpolatebfillr.   r   r2   r/   r   r   r)   
projectionr   rk   r   r   r   r8  r  r   residra   r   r   fit_constrainedloading_constraintsresid_responser  r   r0   r1   r   start_paramsr   rA   ravellinalgcholeskysigma_utril_indices_from	transposer?   r   rg   r   diagr   tril_indicesrb   clipinfr$  isnanr   fit_emvar)$r9   r  endog_factor_map_Mr)   r   r[   endog_ixfactor_endogres_pcar   r  r   	factor_ixfactor_exogmod_olsres_olsmod_glmres_glmr>  r   r   rY   factors_endogmod_factorsspblock_factor_arblock_factor_covcoefficient_matricesres_factorsrt  
cov_factoridio_ar1idio_varmod_idior   res_idios$                                       r:   r  zDynamicFactorMQ.start_paramsF  s[    $--rzz: "2277H

LL$00288:
 %% 	5D xx 2 6 6q$w ?@CH8}!88D$9$9$=$=ag$FGJ H-L,aOGNN7??+!X+'"4"44	5 ..q1
 t~~& 	(A11!4I!!Y,/K$**QT*fMGkkmG--//HLL'	( t~~t||4 	1A11!4I I!6DIK$**QT*KHG--d.F.Fq.IJGI7>>@@HLL//0	1 '/twwz"#
 
	
WW** +	4E#AqU__)<'<$<=M A!!Q&!#%m-2-?-?A,FH --"$Sb'#%bc7 '2'?'?'D$1$!-0)oo!..4s . D #."4"4"6"6"<"<">II&&{':':;#$R%9%9!%<#= ')||JJ % % 2 2 456?(A$ 'sT3G2G-H'HIJ  ++, -$$ % &'"WW]%6%6A%6%>?
ru?@ !//11I*1133JW+	4X (1tww{#$(2tww|$%
 !!HH4>>* ?"589CH**1ud ;<2bff =>	?
 4>>4<<8 	DJJq!t$))+"'(288A;,'?#<<$-2 ( 4#??8Q9= + ?UD ABT266 BC	D 4<F477./03;F477./0  382GHQuQx(HHH4>>4<<8 DJJq!t$))+"'(288A;,'?#<<d<GT266 BCD 4<F477./0 Is   `7c           	      $   |j                         }|| j                  d      }g }d}| j                  j                  D ]  }|j                  dz  |j
                  z  }t        j                  ||||z    |j                  |j                  |j
                  z  f      }t        j                  |j                        }	t        ||	      \  }}
||j                         j                         z  }||z  } ||| j                  d   <   | j                  rW|| j                  d      }t        | j                        D cg c]  }t        |||dz          d    c}|| j                  d   <   || j                  d      dz  || j                  d   <   |S c c}w )a"  
        Transform parameters from optimizer space to model space.

        Transform unconstrained parameters used by the optimizer to constrained
        parameters used in likelihood evaluation.

        Parameters
        ----------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer, to be
            transformed.

        Returns
        -------
        constrained : array_like
            Array of constrained parameters which may be used in likelihood
            evaluation.
        r   r   r   rb   rS   r   )r$  r  r   r   r0   r1   r>   r?   r  r   r  r   rb   rk   ra   r   )r9   unconstrainedconstrainedunconstrained_factor_arconstrained_factor_arr   rY   length	tmp_coefftmp_cov_r  s               r:   transform_paramsz DynamicFactorMQ.transform_params  s   & $((* #00D"E "WW** 		E__a'%*<*<<F

'!f*5%//E4F4F"FGII ffU__-G<Y=DFLIq!Y__%6%=%=%??!KA		 -BDGGK() !!$TWW-@%ABH t||,9. 01q50AB1E9.K 345  345q8 	DGG/01 9.   8Fc           	      $   |j                         }|| j                  d      }g }d}| j                  j                  D ]  }|j                  dz  |j
                  z  }t        j                  ||||z    |j                  |j                  |j
                  z  f      }t        j                  |j                        }	t        ||	      \  }}
||j                         j                         z  }||z  } ||| j                  d   <   | j                  rW|| j                  d      }t        | j                        D cg c]  }t        |||dz          d    c}|| j                  d   <   || j                  d      dz  || j                  d   <   |S c c}w )a	  
        Transform parameters from model space to optimizer space.

        Transform constrained parameters used in likelihood evaluation
        to unconstrained parameters used by the optimizer.

        Parameters
        ----------
        constrained : array_like
            Array of constrained parameters used in likelihood evaluation, to
            be transformed.

        Returns
        -------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer.
        r   r   r   rb   rS   r   g      ?)r$  r  r   r   r0   r1   r>   r?   r  r   r  r   rb   rk   ra   r   )r9   r  r  r  r  r   rY   r  r  r  r  r  s               r:   untransform_paramsz"DynamicFactorMQ.untransform_params  s   $ $((* !,DGGK,@ A"$WW** 		E__a'%*<*<<F

%aF
3%//E4F4F"FGII ffU__-G>y?FHLIq#y'8'?'?'AA#KA		 /Fdggk*+ !!"477+>#?@H t||,;. 2(1QU2CDQG;.M$''"567 $''"567< 	dgg123 ;.r  c                    t        |   |fi |}| j                  }| j                  }| j                  }||d      }d}t        | j                        D ]A  }| j                  j                  |   }	t        |	      }
|d   |	   }||||
z    | d||f<   ||
z  }C t        j                  g d      dddf   }t        | j                  | j                        D ]i  }| j                  j                  |   }	t        |	      }
|d   dd|	f   }t        j                  ||||
z    |z        | d||j                         f<   ||
z  }k ||d      }d}|j                  D ]p  }|j                  d	z  |j                  z  }t        j                   ||||z    |j                  |j                  |j                  z  f      }||z  }|| d
|d   |d   f<   r ||d      }d}d}|j                  D ]  }|j                  |j                  dz   z  d	z  }t        j"                  |j                  |j                  f|j$                        }||||z    |t        j&                  |      <   ||z  }||j(                  z  }||j                  z   }|| d||||f<   |} | j*                  r)t        j,                  ||d            }|| d
|d   |d   f<   | j*                  r:t        j,                  ||d            | d| j                  d| j                  df<   y||d      }t        j,                  ||d            | d|d   |d   f<   t        j,                  ||d            | d| j                  d| j                  df<   y)aK  
        Update the parameters of the model.

        Parameters
        ----------
        params : array_like
            Array of new parameters.
        transformed : bool, optional
            Whether or not `params` is already transformed. If set to False,
            `transform_params` is called. Default is True.

        r   r   r,   r   r   Nr   r   r   r   r*   r   rS   r^   	state_covrb   r   r   r   r   r   )r  r   r   r   r  rk   r`   r   r/   r>   r   ra   r  r   r0   r1   r?   r   r_   r  rA   rb   r  )r9   r  r  rC   r  pr   r   r   r   r0   r  r  r   rY   r	  Ar   r   rt  r   r   alphar  r  s                           r:   r   zDynamicFactorMQ.update5  s    1&1 GGGGGG !J-(t~~& 	A77,,Q/DD	I,-I+3E%):K+LD1i'(YE	 hh/48t~~t||4 	A77,,Q/DD	I+,QW5I3588uy01K?4AD1ioo//0YE	 1[>*	__ 	ME)E,>,>>H

% 01%//E4F4F"FGIA XEKLDu\2E,4GGH	M AlO,
__ 		E%//A*=>!CH%//5??;%||-A)3E%(:J)KAb""1%&XEACCA'C23Dc#gs3w./C		 !!GGF1%8#9:;ECHDq,?@ !!q!4567 dnnot~~>? a 345H.0gghqv6F.GDAcFAcF*+3() dnnot~~>?r<   c                     ddt        j                  | j                        z
  j                         z  t        j                  dt         j
                  z        z  S )z
        Constant term in the joint log-likelihood function.

        Useful in facilitating comparisons to other packages that exclude the
        constant from the log-likelihood computation.
        g      rS   r   )r>   r  r   rt   logpir;  s    r:   loglike_constantz DynamicFactorMQ.loglike_constant  s@     q288DJJ//4466BEE	9JJJr<   c                 j   || j                   k  rt        d      || j                  vr| j                  j                  |   j                         }t        j                  |dz  |dz  f      }t        j                  |j                  d         }t        j                  g d      }t        j                  |dd t        j                  |      d   z  j                  |dz  |f      |ddd|f<   t        j                  d	g|dz  z        |dd|df<   ||f| j                  |<   | j                  |   S )
al	  
        Matrix formulation of quarterly variables' factor loading constraints.

        Parameters
        ----------
        i : int
            Index of the `endog` variable to compute constraints for.

        Returns
        -------
        R : array (k_constraints, k_factors * 5)
        q : array (k_constraints,)

        Notes
        -----
        If the factors were known, then the factor loadings for the ith
        quarterly variable would be computed by a linear regression of the form

        y_i = A_i' f + B_i' L1.f + C_i' L2.f + D_i' L3.f + E_i' L4.f

        where:

        - f is (k_i x 1) and collects all of the factors that load on y_i
        - L{j}.f is (k_i x 1) and collects the jth lag of each factor
        - A_i, ..., E_i are (k_i x 1) and collect factor loadings

        As the observed variable is quarterly while the factors are monthly, we
        want to restrict the estimated regression coefficients to be:

        y_i = A_i f + 2 A_i L1.f + 3 A_i L2.f + 2 A_i L3.f + A_i L4.f

        Stack the unconstrained coefficients: \Lambda_i = [A_i' B_i' ... E_i']'

        Then the constraints can be written as follows, for l = 1, ..., k_i

        - 2 A_{i,l} - B_{i,l} = 0
        - 3 A_{i,l} - C_{i,l} = 0
        - 2 A_{i,l} - D_{i,l} = 0
        - A_{i,l} - E_{i,l} = 0

        So that k_constraints = 4 * k_i. In matrix form the constraints are:

        .. math::

            R \Lambda_i = q

        where :math:`\Lambda_i` is shaped `(k_i * 5,)`, :math:`R` is shaped
        `(k_constraints, k_i * 5)`, and :math:`q` is shaped `(k_constraints,)`.


        For example, for the case that k_i = 2, we can write:

        |  2 0   -1  0    0  0    0  0    0  0  |   | A_{i,1} |     | 0 |
        |  0 2    0 -1    0  0    0  0    0  0  |   | A_{i,2} |     | 0 |
        |  3 0    0  0   -1  0    0  0    0  0  |   | B_{i,1} |     | 0 |
        |  0 3    0  0    0 -1    0  0    0  0  |   | B_{i,2} |     | 0 |
        |  2 0    0  0    0  0   -1  0    0  0  |   | C_{i,1} |  =  | 0 |
        |  0 2    0  0    0  0    0 -1    0  0  |   | C_{i,2} |     | 0 |
        |  1 0    0  0    0  0    0  0   -1  0  |   | D_{i,1} |     | 0 |
        |  0 1    0  0    0  0    0  0    0 -1  |   | D_{i,2} |     | 0 |
                                                    | E_{i,1} |     | 0 |
                                                    | E_{i,2} |     | 0 |

        z%No constraints for monthly variables.r  r(   r   r   rS   N.Nr   )r`   rj   r  r3   r   rt   r>   r   rs   r   r?   r  rA   r  )r9   r   r0   Rqr  s         r:   r  z#DynamicFactorMQ.loading_constraints  s   B t~~DEED-----221599;I)a-Q78A$A ((?3K!zzQR266)#4Y#??BBQ	* ,Aa)m
  "wwty1}'=>Aam,-q6D%%a(((++r<   c                     |dk(  r! | j                   d|||||||	|
||||||d|S t        |   di d|d|d|d|d|d|d	|d
|d|d|d|d|d|d|d|d||S )a  
        Fits the model by maximum likelihood via Kalman filter.

        Parameters
        ----------
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            If None, the default is given by Model.start_params.
        transformed : bool, optional
            Whether or not `start_params` is already transformed. Default is
            True.
        includes_fixed : bool, optional
            If parameters were previously fixed with the `fix_params` method,
            this argument describes whether or not `start_params` also includes
            the fixed parameters, in addition to the free parameters. Default
            is False.
        cov_type : str, optional
            The `cov_type` keyword governs the method for calculating the
            covariance matrix of parameter estimates. Can be one of:

            - 'opg' for the outer product of gradient estimator
            - 'oim' for the observed information matrix estimator, calculated
              using the method of Harvey (1989)
            - 'approx' for the observed information matrix estimator,
              calculated using a numerical approximation of the Hessian matrix.
            - 'robust' for an approximate (quasi-maximum likelihood) covariance
              matrix that may be valid even in the presence of some
              misspecifications. Intermediate calculations use the 'oim'
              method.
            - 'robust_approx' is the same as 'robust' except that the
              intermediate calculations use the 'approx' method.
            - 'none' for no covariance matrix calculation.

            Default is 'none', since computing this matrix can be very slow
            when there are a large number of parameters.
        cov_kwds : dict or None, optional
            A dictionary of arguments affecting covariance matrix computation.

            **opg, oim, approx, robust, robust_approx**

            - 'approx_complex_step' : bool, optional - If True, numerical
              approximations are computed using complex-step methods. If False,
              numerical approximations are computed using finite difference
              methods. Default is True.
            - 'approx_centered' : bool, optional - If True, numerical
              approximations computed using finite difference methods use a
              centered approximation. Default is False.
        method : str, optional
            The `method` determines which solver from `scipy.optimize`
            is used, and it can be chosen from among the following strings:

            - 'em' for the EM algorithm
            - 'newton' for Newton-Raphson
            - 'nm' for Nelder-Mead
            - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
            - 'lbfgs' for limited-memory BFGS with optional box constraints
            - 'powell' for modified Powell's method
            - 'cg' for conjugate gradient
            - 'ncg' for Newton-conjugate gradient
            - 'basinhopping' for global basin-hopping solver

            The explicit arguments in `fit` are passed to the solver,
            with the exception of the basin-hopping solver. Each
            solver has several optional arguments that are not the same across
            solvers. See the notes section below (or scipy.optimize) for the
            available arguments and for the list of explicit arguments that the
            basin-hopping solver supports.
        maxiter : int, optional
            The maximum number of iterations to perform.
        tolerance : float, optional
            Tolerance to use for convergence checking when using the EM
            algorithm. To set the tolerance for other methods, pass
            the optimizer-specific keyword argument(s).
        full_output : bool, optional
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
        disp : bool, optional
            Set to True to print convergence messages.
        callback : callable callback(xk), optional
            Called after each iteration, as callback(xk), where xk is the
            current parameter vector.
        return_params : bool, optional
            Whether or not to return only the array of maximizing parameters.
            Default is False.
        optim_score : {'harvey', 'approx'} or None, optional
            The method by which the score vector is calculated. 'harvey' uses
            the method from Harvey (1989), 'approx' uses either finite
            difference or complex step differentiation depending upon the
            value of `optim_complex_step`, and None uses the built-in gradient
            approximation of the optimizer. Default is None. This keyword is
            only relevant if the optimization method uses the score.
        optim_complex_step : bool, optional
            Whether or not to use complex step differentiation when
            approximating the score; if False, finite difference approximation
            is used. Default is True. This keyword is only relevant if
            `optim_score` is set to 'harvey' or 'approx'.
        optim_hessian : {'opg','oim','approx'}, optional
            The method by which the Hessian is numerically approximated. 'opg'
            uses outer product of gradients, 'oim' uses the information
            matrix formula from Harvey (1989), and 'approx' uses numerical
            approximation. This keyword is only relevant if the
            optimization method uses the Hessian matrix.
        low_memory : bool, optional
            If set to True, techniques are applied to substantially reduce
            memory usage. If used, some features of the results object will
            not be available (including smoothed results and in-sample
            prediction), although out-of-sample forecasting is possible.
            Note that this option is not available when using the EM algorithm
            (which is the default for this model). Default is False.
        llf_decrease_action : {'ignore', 'warn', 'revert'}, optional
            Action to take if the log-likelihood decreases in an EM iteration.
            'ignore' continues the iterations, 'warn' issues a warning but
            continues the iterations, while 'revert' ends the iterations and
            returns the result from the last good iteration. Default is 'warn'.
        llf_decrease_tolerance : float, optional
            Minimum size of the log-likelihood decrease required to trigger a
            warning or to end the EM iterations. Setting this value slightly
            larger than zero allows small decreases in the log-likelihood that
            may be caused by numerical issues. If set to zero, then any
            decrease will trigger the `llf_decrease_action`. Default is 1e-4.
        **kwargs
            Additional keyword arguments to pass to the optimizer.

        Returns
        -------
        MLEResults

        See Also
        --------
        statsmodels.base.model.LikelihoodModel.fit
        statsmodels.tsa.statespace.mlemodel.MLEResults
        emr  transformedcov_typecov_kwdsr  	toleranceem_initializationmstep_methodfull_outputr  r  
low_memoryllf_decrease_actionllf_decrease_tolerancer  r  includes_fixedr  r  r  r  r  r  callbackr  optim_scoreoptim_complex_stepoptim_hessianflagsr  rO   )r  r  r8  )r9   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  s                          r:   r8  zDynamicFactorMQ.fit  s   X T>4;; I){!Hg#7H){+
$7'=I BHI I 7; 	1)	17B	1-	18@	1 "	1 +1	1 ;B	1 (		1 /3		1
 "	1
 2?	1 (	1 $6	1 ,	1 49	1 &	1 	1r<   c                 >   | j                   rt        d      |rt        d      || j                  }d}nt	        j
                  |d      }|s| j                  |      }t        |dg d	      }t        |      }| j                  }g }|g}d}| j                  j                  g}d
}d
}d}||k  ry|sv|dk  s||kD  rk| j                  |d   ||	      }|d
   j                  j                         }|s| j                  |d          g }| d   }| j                  j                  }t	        j                   | j"                        }| j$                  d
k(  r| j&                  s|j(                  d
   }|j*                  dk(  r?||d   |d   f   }t	        j,                  t        j.                  j1                  |      dk        s|j3                  |d   d       |j5                  dt7        |j8                                n|j(                  D ]  }t7        ||d            }|j:                  |   j*                  }|dk(  s3||d   |d   f   }t	        j,                  t        j.                  j1                  |      dk        rv|j3                  |d   d       |j5                  dt7        |j8                                 | j&                  r\| j=                  d      } t?        |d   j@                  |d   jB                        D ]{  }!|j:                  |!f   j*                  }|dk(  s#t	        jD                  ||!|!f         dk  rA|j3                  |!d       | |!|d   j@                  z
     }"|j5                  d|"        } | j$                  d
kD  rt7        ||d            }|j:                  |   j*                  }|dk(  rh||d   |d   f   }t	        j,                  t        j.                  j1                  |      dk        s&|j3                  |d   d       |j5                  d       tG        |      d
kD  rbtI        d|dz    d| d       | jK                  |d   |||||||	|
|||||      }#| j                  jM                  | jO                                |#S |d
kD  xr ||d   z
  | k  }$|dk(  r |$rtI        d|dz    d| d        |dz  }d}n@|d!k(  r|$rtI        d|dz    d"       |j5                  |       |j5                  |d          |rTt        jP                  | j"                  d#|d
   jR                  d$   |d
   jT                  d$   %      }|j5                  |       |d
kD  rTd&t	        jD                  |d   |d'   z
        z  t	        jD                  |d         t	        jD                  |d'         z   z  }nt        jV                  }|r|d
k(  rtY        d(|d   d)       n)|r'|dz   |z  d
k(  rtY        d*|dz    d+|d   d)d,|d)       |dz  }||k  r|s|dk  rd||kD  rk||k(  xr ||kD  }%|%rtI        d-| d.|d   d)d,|d)d/|d)d0	       |r_|rtY        d1| d+|d   d)d,|d)d/|d)d0	       n>|%rtY        d-| d.|d   d)d,|d)d/|d)d0	       ntY        d2| d+|d   d)d,|d)d3|d)       |r|d   }&|&S |r'| j                  j                  }'|| j                  _        | j[                  |d   d||4      }&|r'| j                  _        |
ra|j5                  |&j\                         t_        d8i t	        j
                  |      t	        j
                  |      ||d5}(t_        d8i d6||d7})nd}(d})|(|&j`                  _1        |)|&j`                  _2        |&S )9a  
        Fits the model by maximum likelihood via the EM algorithm.

        Parameters
        ----------
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            The default is to use `DynamicFactorMQ.start_params`.
        transformed : bool, optional
            Whether or not `start_params` is already transformed. Default is
            True.
        cov_type : str, optional
            The `cov_type` keyword governs the method for calculating the
            covariance matrix of parameter estimates. Can be one of:

            - 'opg' for the outer product of gradient estimator
            - 'oim' for the observed information matrix estimator, calculated
              using the method of Harvey (1989)
            - 'approx' for the observed information matrix estimator,
              calculated using a numerical approximation of the Hessian matrix.
            - 'robust' for an approximate (quasi-maximum likelihood) covariance
              matrix that may be valid even in the presence of some
              misspecifications. Intermediate calculations use the 'oim'
              method.
            - 'robust_approx' is the same as 'robust' except that the
              intermediate calculations use the 'approx' method.
            - 'none' for no covariance matrix calculation.

            Default is 'none', since computing this matrix can be very slow
            when there are a large number of parameters.
        cov_kwds : dict or None, optional
            A dictionary of arguments affecting covariance matrix computation.

            **opg, oim, approx, robust, robust_approx**

            - 'approx_complex_step' : bool, optional - If True, numerical
              approximations are computed using complex-step methods. If False,
              numerical approximations are computed using finite difference
              methods. Default is True.
            - 'approx_centered' : bool, optional - If True, numerical
              approximations computed using finite difference methods use a
              centered approximation. Default is False.
        maxiter : int, optional
            The maximum number of EM iterations to perform.
        tolerance : float, optional
            Parameter governing convergence of the EM algorithm. The
            `tolerance` is the minimum relative increase in the likelihood
            for which convergence will be declared. A smaller value for the
            `tolerance` will typically yield more precise parameter estimates,
            but will typically require more EM iterations. Default is 1e-6.
        disp : int or bool, optional
            Controls printing of EM iteration progress. If an integer, progress
            is printed at every `disp` iterations. A value of True is
            interpreted as the value of 1. Default is False (nothing will be
            printed).
        em_initialization : bool, optional
            Whether or not to also update the Kalman filter initialization
            using the EM algorithm. Default is True.
        mstep_method : {None, 'missing', 'nonmissing'}, optional
            The EM algorithm maximization step. If there are no NaN values
            in the dataset, this can be set to "nonmissing" (which is slightly
            faster) or "missing", otherwise it must be "missing". Default is
            "nonmissing" if there are no NaN values or "missing" if there are.
        full_output : bool, optional
            Set to True to have all available output from EM iterations in
            the Results object's mle_retvals attribute.
        return_params : bool, optional
            Whether or not to return only the array of maximizing parameters.
            Default is False.
        low_memory : bool, optional
            This option cannot be used with the EM algorithm and will raise an
            error if set to True. Default is False.
        llf_decrease_action : {'ignore', 'warn', 'revert'}, optional
            Action to take if the log-likelihood decreases in an EM iteration.
            'ignore' continues the iterations, 'warn' issues a warning but
            continues the iterations, while 'revert' ends the iterations and
            returns the result from the last good iteration. Default is 'warn'.
        llf_decrease_tolerance : float, optional
            Minimum size of the log-likelihood decrease required to trigger a
            warning or to end the EM iterations. Setting this value slightly
            larger than zero allows small decreases in the log-likelihood that
            may be caused by numerical issues. If set to zero, then any
            decrease will trigger the `llf_decrease_action`. Default is 1e-4.

        Returns
        -------
        DynamicFactorMQResults

        See Also
        --------
        statsmodels.tsa.statespace.mlemodel.MLEModel.fit
        statsmodels.tsa.statespace.mlemodel.MLEResults
        zFCannot fit using the EM algorithm while holding some parameters fixed.z?Cannot fit using the EM algorithm when using low_memory option.NTrS   )ndminr  )ignorer   revertoptionsr   Fr   )rA  r  r   r>  r)   gA?diffusezfactor block: ry  r   z*idiosyncratic AR(1) for monthly variable: r   z8idiosyncratic AR(1) for the block of quarterly variablesz0Non-stationary parameters found at EM iteration zu, which is not compatible with stationary initialization. Initialization was switched to diffuse for the following:  z, and fitting was restarted.r  r  z)Log-likelihood decreased at EM iteration z-. Reverting to the results from EM iteration z4 (prior to the decrease) and returning the solution.r   z&, which can indicate numerical issues.known.r   )constantstationary_covr   zEM start iterations, llf=z.5gzEM iteration z, llf=z, convergence criterion=z)EM reached maximum number of iterations (z&), without achieving convergence: llf=z  (while specified tolerance was )zEM terminated at iteration zEM converged at iteration z < tolerance=)r  r  r  )r  llfiterinitsr  )r  r  r  rO   )3_has_fixed_paramsNotImplementedErrorrj   r  r>   r   r  r   r   r   r  r   _em_iterationllf_obsrt   r   r@   r8   r5   rb   r   initialization_typeallr  eigvalsrn   r   rh   r.   blocksrF  rk   r   r@  absr/   r   r  r  r  r?  smoothed_statesmoothed_state_covr  printsmoothr  r   _resultsmle_retvalsmle_settings)*r9   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rA  r  r   delta	terminateoutnew_llfswitch_initrA   r   rY   Tbb	init_typer   r  r[   resultsllf_decreasenot_convergedresult	base_init
em_retvalsem_settingss*                                             r:   r  zDynamicFactorMQ.fit_em	  s   D !!% 'H I I 3 4 4 ,,LK88L:L00>L)!602 4y GG(()	'k)Q59;L$$VBZd2> % @C!fnn((*G %CF# &xx..yy/ >>Q&t/E/EOOA.E//<?uY/y1AAB!vvbii&7&7&;y&IJ HHU9%5yA'..!$$)%*<*<$=#>!@A
 "# 	E!$uY'7"89$(KKN$F$F	$4!"5#3U95E#E!FB#%66"))*;*;B*?9*M#N $y)99 E + 2 2%((-e.@.@(A'B%D!E	E ))"&"7"7$"7"GK"1[>#7#7;9L9LM :$(KK$5$I$I	$4#%66!AqD'?i#@ $I 6'21q~7K7K3K'L + 2 2%226%9!:: ~~)!$q~"67$(KKN$F$F	$4!"1[>1[>#A!BB#%66"))*;*;B*?9*M#N $; C + 2 2%D!E {#a' UG $ )M)E	G H
 #kk%+BZ[!)H '9*;%1{!#-,?/E * 	GG HH''(D(D(FG"N
 AG7SW,1G0GG  #h.<@Q HDDE3KL M Q 	&&0\DQUG LA A B

7#c!f%$)88w!$Q!6!6v!>'*1v'@'@'HJD LL&q5B#b'(9!:: ffSWos2w?AE FFE AF5c"gc]CDA~!3M!a%s2wsm D449#;@ A FAs 'k)Q59;Lx g;%)*; <WI F88;B} E++0+3Ic?!E F 3A3fSWSM J005c{83qJ K A' K==@WSM J005c{83qJ K
 21#VCGC= I005c{%i_6 7
 BZF> 9 ! HH33	*.' [[*2X ! GF *3' 

6::&" 70@-/XXc].//4&6 7
 $ <4=29'; < "
"*4FOO'+6FOO(r<   c                 X    | j                  ||      }| j                  |||      }||fS )zEM iteration.)rA  )r  )_em_expectation_step_em_maximization_step)r9   params0rA  r  resparams1s         r:   r  zDynamicFactorMQ._em_iteration
  sD     ''d'; ,,S':F - H G|r<   c                 r   | j                  |       |'| j                  j                  }|| j                  _        | j                  j                  t        t
        z  t        z  d      }t        j                  | j                  j                  j                  d      |_        || j                  _        |S )zEM expectation step.F)update_filterT)r$  )r   r  r   r  r   r   r    r>   r   _kalman_filterloglikelihoodr  )r9   r"  rA  r  r#  s        r:   r   z$DynamicFactorMQ._em_expectation_step
  s     	G//I&*DHH#hhoo//2HH  ! hhHH##11> &/DHH#
r<   c           	      	   | j                   }|j                  j                  d   }|j                  j	                  ddd      }|j
                  j	                  ddd      }|j                         t        j                  ||j	                  ddd            z   }|dd t        j                  |dd |dd j	                  ddd            z   }	t        j                  |j                        }
||
rdnd}|j                         }|dk(  r|
rt        d	      |dk(  r| j                  }n |dk(  r| j                  }nt        d
|z         ||||| j                         \  }}g }g }|j                   D ]  }|dd|d   |d   f   j#                  d      }|	dd|d   |d   f   j#                  d      }|dd|d   |d   f   j#                  d      }|j$                  d   dz
  }	 t'        t)        |      |j                        j                  }|||j                  z  z
  |z  }||j1                         j3                         z  }|t        j,                  j5                  |      t        j6                  |         j3                         z  } | j                  r|d   }|dd||f   j#                  d      j9                         }|	dd||f   j#                  d      j9                         }|dd||f   j#                  d      j9                         }|j$                  d   dz
  }||z  }|||z  z
  |z  }np|d   }|dd||f   j#                  d      }t        j:                  |j9                         | j<                  d      |j9                         |j$                  d   z  f   }t        j>                  |      }g }tA        | jB                        D ];  }| j                   jD                  |   } |d   |    }!||||!f   j3                         z  }= ||| jF                  d   <   ||| jF                  d   <   ||| jF                  d   <   | j                  r|| jF                  d   <   ||| jF                  d   <   |S # t*        $ r8 t        j,                  j/                  ||j                        j                  }Y w xY w)zEM maximization step.r  r   r   rS   Nr   r   
nonmissingzMCannot use EM algorithm option `mstep_method="nonmissing"` with missing data.z'Invalid maximization step method: "%s".)	compute_Hr*   rT   r,   r   r   r   r   r   rb   r   )$r   r	  rA   r
  r  smoothed_state_autocovr$  r>   matmulr   nmissinglowerrj   _em_maximization_obs_nonmissing_em_maximization_obs_missingrb   r   rt   rs   r   r   r	   r  solver  r   r  r  diagonalr_r   
zeros_likerk   ra   r   r  )"r9   r#  r"  r  r  acov_aacov_aEaaEaa1has_missingfuncLambdaHr   r   r  r  BCr[  f_Af_Qr   AdBdCdr  sigma2r$  r   r   r   r  s"                                     r:   r!  z%DynamicFactorMQ._em_maximization_step
  s   GG  +&&00Aq9++55aA> jjlRYYq!++aA*>??cr{RYYquaf.>.>q!Q.GHH ffS\\*(39L#))+<'K O P P <'77DY&44DF+, - - c1T5K5K1KM	 	
 	MACRC<!L/9:>>A>FAQ,<89==1=EAAB,<89==1=EA99Q<!#D0
1qss355 sQSSy=D(C++--I		""3'(<(<S(ABIIKMJ!	M( !!<BSbS"b[!%%1%-668BaRi$$!$,557BQRRZ$$!$,557B99Q<!#DGE52:o-F<BAr2I"""*AUU1::<5::<#))A,67 8F --(t||$ 	6A77,,Q/D,-Iq)|,3355H	6 (0
#$(1$%)3%&!!49GDGG/0106+,-S  0 iiooa-//0s   ')Q===R>=R>c                 @   | j                   }|j                  }|j                  }t        j                  | j
                  |f|      }t        | j
                        D ]  }	| j                  dd|	|	dz   f   }
| j                   j                  |	   }|d   |   }t        j                  dd ft        j                  ||      z   }||   j                  d      }|
j                  |dd|df   z  }| j                  r3|j                  |	z   }|dz   }||dd|||f   j                  d      z  }	 t        t        |      |j                        j                  ||	|f<    |r| d   j'                         }||ddd|f<   | j                  j                  |d   z  |j                  z  }| j                  j                  | j                  z  }|| z   |j                  z
  ||j                  d      z  |j                  z  z   | j(                  z  }||fS t        j                  | j
                  | j
                  f|      t        j*                  z  }||fS # t         $ r= t        j"                  j%                  ||j                        j                  ||	|f<   Y ?w xY w)	z@EM maximization step, observation equation without missing data.r^   NrS   r,   r   rT   r   r  )r   r_   r   r>   r   ra   rk   r   r   rE   ix_rt   rA   rb   r   r   r	   r  r2  r$  r[  r   )r9   r#  r9  r6  r+  r  r_   r  r=  r   r   r   r  r   r  r?  r   r   ZBLr@  r>  s                         r:   r0  z/DynamicFactorMQ._em_maximization_obs_nonmissing5  s_   GG		 4<<+59t||$ 	AA

1aAg:&A77,,Q/D,-I%%(rvvi;;BB#Aa9a((A%%((1,AgSCGY./333;;A'0A'D'F'Fq)|$	A6 X##%AAa!eH&	)ACC/B

tzz)AbS244!cgg1go"5";;tyyHA qy $,,5UCbffLAqy+  A (*yyq!##'>'@'@q)|$As   1.IAJJc                 \   | j                   }|j                  }|j                  }t        j                  | j
                  |f|      }d|j                  j                  z
  }	|	j                  t              }
t        | j                        D ]  }| j                   j                  |   }|d   |   }|
dd|f   }| j                  |||dz   f   }t        j                  |||      }||   j                  d      }|j                  |t        j                  ||         d   z  }| j                   r5|j                  |z   }|dz   }|||||f   d|f   j                  d      z  }	 t#        t%        |      |j                        j                  |||f<    | j,                  dkD  rt        j.                  g d	      dddf   }t        | j                  | j
                        D ]  }| j                   j                  |   }|d
   dd|f   j1                         j3                         }| j5                  |      \  }}|| j                  z
  }|
dd|f   }| j                  |||dz   f   }t        j                  |||      }||   j                  d      }|j                  |t        j                  ||         d   z  }| j                   rat        j6                  dd ft        j                  |d   |   |      z   }||   }||||   j                  d      z  j                  d      z  }	 t%        |      }t#        ||j                        j                  d   }t#        ||j                        }t%        ||z        }t#        ||      }|||z  |z  z
  }||||f<    |r| d   j;                         }"||"ddd|j<                  d   f<   t        j>                  | j                        }#|#j                  |#z  }$|	d   }	d|	z
  }%|	|"z  }&|&jA                  ddd      }'|#d   |jA                  ddd      z  |'z  }(|})|(jA                  ddd      }*|%jA                  ddd      }+|$|( |*z
  |&|)z  |'z  z   |%| d   z  |+z  z   j                  d      z   | jB                  z  },||,fS t        j                  | j
                  | j
                  f|      t        jD                  z  },||,fS # t&        $ r= t        j(                  j+                  ||j                        j                  |||f<   Y w xY w# t&        $ ru t        j(                  j9                  |      } || z  d   }t        j(                  j9                  || z  |j                  z        }!|| |j                  z  |!z  |z  |z  z
  }Y w xY w)z=EM maximization step, observation equation with missing data.r^   rS   r,   Nr   rT   r  .r   r   r   r   r  r   r   )#r   r_   r   r>   r   ra   r   rA   r*  r   rk   r`   r   r   rH  rt   rb   r   r   r	   r  r2  r5   r   r  r   r  rE   invr$  rs   
nan_to_numr  r[  r   )-r9   r#  r9  r6  r+  r  r_   r  r=  r  r1  r   r   r  r  ytr   AiBir   r   r  r  r  iQBiQEepsfL_and_lowerunrestrictedAiiRTRAiiRTiR
restrictedAiiRARirI  r   r@  IWWLWLTrJ  r  BLTIWTr>  s-                                                r:   r1  z,DynamicFactorMQ._em_maximization_obs_missingg  sw   GG		 4<<+59xx~ t~~& 	CA77,,Q/D,-IQT
AAqQwJ'B9i0BR!$B"&&I./77B%%((1,Agc!SW*oc9n599q9AAC'0B'F'H'Hq)|$!	C2 >>A((?3AtG<K4>>4<<8 )2ww003/0D9??AHHJ	//21'AJZZ1QU7
+VVAy)4W[[a[(ddQrvva34V<<))%%(rvva.?.CY'OOBGEK%(,,A,*>>CCCKKCG",R.K#,[#%%#@#B#B1#EL%k1337E",QY"7K(a8H!-0@<0O!OJ (2q)|$S)2b X##%A%+Aa!&,,q/!!"djj)AaA)AQBQB,,q!Q'C9Aq! 44s:BA,,q!Q'C,,q!Q'CrcCi"q&3,.4	?*S0125#1#+>AEKA
 qy $,,5UCbffLAqye  C (*yyr244'@'B'Bq)|$CX # G ))--+C$'#Iq>L99==S1337D"."%)d"2Q"6"E#FJGs'   &.S$/A)T-$AT*)T*-A:V+*V+c
                 6    t        |   |f||||||||	d|
S )a  
        Kalman smoothing.

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        return_ssm : bool,optional
            Whether or not to return only the state space output or a full
            results object. Default is to return a full results object.
        cov_type : str, optional
            See `MLEResults.fit` for a description of covariance matrix types
            for results object. Default is None.
        cov_kwds : dict or None, optional
            See `MLEResults.get_robustcov_results` for a description required
            keywords for alternative covariance estimators
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.
        r  r  complex_stepr  r  
return_ssmresults_classresults_wrapper_class)r  r  )r9   r  r  r  rb  r  r  rc  rd  re  r  r  s              r:   r  zDynamicFactorMQ.smooth  sA    6 w~C +N%8!"7	C <B	C 	Cr<   c                 6    t        |   |f||||||||	d|S )a  
        Kalman filtering.

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        return_ssm : bool,optional
            Whether or not to return only the state space output or a full
            results object. Default is to return a full results object.
        cov_type : str, optional
            See `MLEResults.fit` for a description of covariance matrix types
            for results object. Default is 'none'.
        cov_kwds : dict or None, optional
            See `MLEResults.get_robustcov_results` for a description required
            keywords for alternative covariance estimators
        low_memory : bool, optional
            If set to True, techniques are applied to substantially reduce
            memory usage. If used, some features of the results object will
            not be available (including in-sample prediction), although
            out-of-sample forecasting is possible. Default is False.
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.
        ra  )r  filter)r9   r  r  r  rb  r  r  rc  rd  re  r  r  r  s               r:   rg  zDynamicFactorMQ.filter  sB    @ w~C +N%8!"7	C <B	C 	Cr<   c                     t        |   ||f|||||||	|
||d
|}| j                  rc|r`t        | j                  t
              }|j                  }|rt        |      dk(  r<| j                  j                  d   }| j                  j                  d   }||z  |z   }|S t        |      dk(  r:|j                  | j                  dd      j                  | j                  dd      }|S t        |      dk(  r|| j                  z  | j                  z   }|S t        |      dk(  r|| j                  z  | j                  z   }|S t        j                  | j                        d   }t        j                  | j                        d   }||z  |z   }|S )a  
        Simulate a new time series following the state space model.

        Parameters
        ----------
        params : array_like
            Array of parameters to use in constructing the state space
            representation to use when simulating.
        nsimulations : int
            The number of observations to simulate. If the model is
            time-invariant this can be any number. If the model is
            time-varying, then this number must be less than or equal to the
            number of observations.
        measurement_shocks : array_like, optional
            If specified, these are the shocks to the measurement equation,
            :math:`\varepsilon_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_endog`, where `k_endog` is the
            same as in the state space model.
        state_shocks : array_like, optional
            If specified, these are the shocks to the state equation,
            :math:`\eta_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the
            same as in the state space model.
        initial_state : array_like, optional
            If specified, this is the initial state vector to use in
            simulation, which should be shaped (`k_states` x 1), where
            `k_states` is the same as in the state space model. If unspecified,
            but the model has been initialized, then that initialization is
            used. This must be specified if `anchor` is anything other than
            "start" or 0 (or else you can use the `simulate` method on a
            results object rather than on the model object).
        anchor : int, str, or datetime, optional
            First period for simulation. The simulation will be conditional on
            all existing datapoints prior to the `anchor`.  Type depends on the
            index of the given `endog` in the model. Two special cases are the
            strings 'start' and 'end'. `start` refers to beginning the
            simulation at the first period of the sample, and `end` refers to
            beginning the simulation at the first period after the sample.
            Integer values can run from 0 to `nobs`, or can be negative to
            apply negative indexing. Finally, if a date/time index was provided
            to the model, then this argument can be a date string to parse or a
            datetime type. Default is 'start'.
        repetitions : int, optional
            Number of simulated paths to generate. Default is 1 simulated path.
        exog : array_like, optional
            New observations of exogenous regressors, if applicable.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is
            True.
        includes_fixed : bool, optional
            If parameters were previously fixed with the `fix_params` method,
            this argument describes whether or not `params` also includes
            the fixed parameters, in addition to the free parameters. Default
            is False.
        original_scale : bool, optional
            If the model specification standardized the data, whether or not
            to return simulations in the original scale of the data (i.e.
            before it was standardized by the model). Default is True.

        Returns
        -------
        simulated_obs : ndarray
            An array of simulated observations. If `repetitions=None`, then it
            will be shaped (nsimulations x k_endog) or (nsimulations,) if
            `k_endog=1`. Otherwise it will be shaped
            (nsimulations x k_endog x repetitions). If the model was given
            Pandas input then the output will be a Pandas object. If
            `k_endog > 1` and `repetitions` is not None, then the output will
            be a Pandas DataFrame that has a MultiIndex for the columns, with
            the first level containing the names of the `endog` variables and
            the second level containing the repetition number.
        )
measurement_shocksstate_shocksinitial_stateanchorrepetitionsr  extend_modelextend_kwargsr  r  rS   r   r   rU   levelr  )r  simulater   rf   r  r!   rs   r/   r   r   r   multiplyaddr>   r   )r9   r  nsimulationsri  rj  rk  rl  rm  r  rn  ro  r  r  original_scaler  sim
use_pandasrs   r   r|   r  s                       r:   rr  zDynamicFactorMQ.simulate!  s   ` gLN5G%]{%]#NN
 GMN #DIIz:JIIEu:?//..q1C++003D)d*C, 
% Z1_<<aq<I"s4#3#3!1sE " 
 u:?/$2B2BBC 
 Z1_/$2B2BBC 
	 --8CC==)9)9:9ED)d*C
r<   c                    t        |   |f||||||||	|
|d
|}| j                  r|rt        | j                  t
              }|j                  }|rZt        |      dk(  r|| j                  j                  d   z  }|S t        |      dk(  r|j                  | j                  dd      }|S t        |      dk(  r|| j                  z  }|S t        |      dk(  r|| j                  z  }|S )a[  
        Impulse response function.

        Parameters
        ----------
        params : array_like
            Array of model parameters.
        steps : int, optional
            The number of steps for which impulse responses are calculated.
            Default is 1. Note that for time-invariant models, the initial
            impulse is not counted as a step, so if `steps=1`, the output will
            have 2 entries.
        impulse : int or array_like
            If an integer, the state innovation to pulse; must be between 0
            and `k_posdef-1`. Alternatively, a custom impulse vector may be
            provided; must be shaped `k_posdef x 1`.
        orthogonalized : bool, optional
            Whether or not to perform impulse using orthogonalized innovations.
            Note that this will also affect custum `impulse` vectors. Default
            is False.
        cumulative : bool, optional
            Whether or not to return cumulative impulse responses. Default is
            False.
        anchor : int, str, or datetime, optional
            Time point within the sample for the state innovation impulse. Type
            depends on the index of the given `endog` in the model. Two special
            cases are the strings 'start' and 'end', which refer to setting the
            impulse at the first and last points of the sample, respectively.
            Integer values can run from 0 to `nobs - 1`, or can be negative to
            apply negative indexing. Finally, if a date/time index was provided
            to the model, then this argument can be a date string to parse or a
            datetime type. Default is 'start'.
        exog : array_like, optional
            New observations of exogenous regressors for our-of-sample periods,
            if applicable.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is
            True.
        includes_fixed : bool, optional
            If parameters were previously fixed with the `fix_params` method,
            this argument describes whether or not `params` also includes
            the fixed parameters, in addition to the free parameters. Default
            is False.
        original_scale : bool, optional
            If the model specification standardized the data, whether or not
            to return impulse responses in the original scale of the data (i.e.
            before it was standardized by the model). Default is True.
        **kwargs
            If the model has time-varying design or transition matrices and the
            combination of `anchor` and `steps` implies creating impulse
            responses for the out-of-sample period, then these matrices must
            have updated values provided for the out-of-sample steps. For
            example, if `design` is a time-varying component, `nobs` is 10,
            `anchor=1`, and `steps` is 15, a (`k_endog` x `k_states` x 7)
            matrix must be provided with the new design matrix values.

        Returns
        -------
        impulse_responses : ndarray
            Responses for each endogenous variable due to the impulse
            given by the `impulse` argument. For a time-invariant model, the
            impulse responses are given for `steps + 1` elements (this gives
            the "initial impulse" followed by `steps` responses for the
            important cases of VAR and SARIMAX models), while for time-varying
            models the impulse responses are only given for `steps` elements
            (to avoid having to unexpectedly provide updated time-varying
            matrices).

        )
stepsimpulseorthogonalized
cumulativerl  r  rn  ro  r  r  rS   r   r   rp  )r  impulse_responsesr   rf   r  r!   rs   r/   r   r   rs  )r9   r  rz  r{  r|  r}  rl  r  rn  ro  r  r  rv  r  irfsrx  rs   r  s                    r:   r~  z!DynamicFactorMQ.impulse_responses  s   V w(5)j<'[)5
 .45 #DIIz:JJJEu:?$//"6"6q"99D  Z1_==q=JD  u:?$//1D
  Z1_$//1Dr<   )	NrS   rS   NTTNFF)NNF)NNr   )NTFnoneNr    ư>TNrS   FNFNNNNFr  r   )NTr  Nr  r  FTNTFFr  r   )F)TFFr  NFNN)	TFFr  NFNNF)NNNNNNNNTFT)rS   r   FFNNNNTFT)#rJ   rK   rL   rM   r;   classmethodr   r6  rN   r<  r  rF  rL  rj  rr  ru  r|  r  r  r  r   r  r  r8  r  r  r   r!  r0  r1  r  rg  rr  r~  __classcell__r  s   @r:   r   r     s   G	R NO?CAF#S2j c& c&J BF%*B M M	2 
 
jX#  . ' 'R I IV0d/bM+^ K KT,l GLADAEDIEI>F#'_1B DJ@EFJ/4DH	xt		(Un0dqf ?D=A/3%)CB ?D=A/36;$CL AE?C;?FK $	wr :;IMFJ;@)-	h hr<   r   c                        e Zd ZdZd fd	Zed        Z	 	 ddZed        Z		 	 	 ddZ
	 	 	 	 d fd	Z	 	 	 	 	 d fd	Z	 	 d fd		Z	 	 d fd
	Z	 	 d fd	Z	 	 	 ddZ	 	 	 	 d fd	Z xZS )r9  z5
    Results from fitting a dynamic factor model
    c                 ,    t        |   ||||fi | y r   )r  r;   )r9   r\  r  filter_resultsr  r  r  s         r:   r;   zDynamicFactorMQResults.__init__	  s!    6>8	?7=	?r<   c                    d}| j                   j                  dkD  rI| j                   j                  j                  }t	        j
                  | j                   j                        |   j                         }t        | j                  j                  j                  dd|f   | j                  j                  j                  t        j                  |ddf   |f   dd      }| j                  ,| j                  j                  j                  dd|f   |_        | j                   ?| j                  j"                  j                  t        j                  |ddf   |f   |_        |S )a  
        Estimates of unobserved factors.

        Returns
        -------
        out : Bunch
            Has the following attributes shown in Notes.

        Notes
        -----
        The output is a bunch of the following format:

        - `filtered`: a time series array with the filtered estimate of
          the component
        - `filtered_cov`: a time series array with the filtered estimate of
          the variance/covariance of the component
        - `smoothed`: a time series array with the smoothed estimate of
          the component
        - `smoothed_cov`: a time series array with the smoothed estimate of
          the variance/covariance of the component
        - `offset`: an integer giving the offset in the state vector where
          this component begins
        Nr   )filteredfiltered_covsmoothedsmoothed_cov)r\  r0   r   r,   r>   r   ru  r   r   statesr  r2   r  rE   r	  r  r
  r  )r9   r  r   r   s       r:   r)   zDynamicFactorMQResults.factors  s   2 ::!#::==++D$**001$7>>@B--11!R%8![[5599"%%A,:JKD2C "".#{{33772>&&2KK,,00r1ur1AB  
r<   c           	         ddl m} t        |dg d      }|| j                  dnd}| j                  j
                  }| j                  j                  }| j                  j                  j                  }| j                  j                  }| j                  j                  }|d	k(  rt        j                  ||f      }	t        |      D ]  }
 || j                  |   j                  dd|
f         }t        |      D ]m  }|j                  ||
f   rE| j                   j"                  |   }t%        ||d
      j'                         j(                  |	||
f<   Yt        j*                  |	||
f<   o  t-        j.                  |	||      }	|	S |dk(  rt        j                  |f      }	 || j                  |         }t        |      D ]  }| j                   j"                  |   }t        j0                  d|j                  |   f   j3                         }|j4                  dd|f   }t%        ||d
      j'                         j(                  |	|<    t-        j6                  |	|      }	|	S |dk(  rWt        j                  ||f      }	 || j                  |         }t        |      D ]  }| j                   j"                  |   }t        |      D ]  }
| j                  j                  j                  j                  ||
f   rt        j0                  d|j                  |d|
dz   f   dg||
z
  dz
  z  f   }|j4                  dd|j9                  t:              j3                         f   }t%        ||d
      j'                         j(                  |	||
f<   t        j*                  |	||
f<     t-        j.                  |	||      }		S )a  
        Get coefficients of determination (R-squared) for variables / factors.

        Parameters
        ----------
        method : {'individual', 'joint', 'cumulative'}, optional
            The type of R-squared values to generate. "individual" plots
            the R-squared of each variable on each factor; "joint" plots the
            R-squared of each variable on each factor that it loads on;
            "cumulative" plots the successive R-squared values as each
            additional factor is added to the regression, for each variable.
            Default is 'individual'.
        which: {None, 'filtered', 'smoothed'}, optional
            Whether to compute R-squared values based on filtered or smoothed
            estimates of the factors. Default is 'smoothed' if smoothed results
            are available and 'filtered' otherwise.

        Returns
        -------
        rsquared : pd.DataFrame or pd.Series
            The R-squared values from regressions of observed variables on
            one or more of the factors. If method='individual' or
            method='cumulative', this will be a Pandas DataFrame with observed
            variables as the index and factors as the columns . If
            method='joint', will be a Pandas Series with observed variables as
            the index.

        See Also
        --------
        plot_coefficients_of_determination
        coefficients_of_determination
        r   )add_constantr  
individualjointr}  r  Nr  r  r  r  r  r   r  Tr   r}  rS   F)statsmodels.toolsr  r   r	  r\  ra   r0   r   r3   r   r.   r>   r   rk   r)   r   r  r   r   r8  rsquaredr   r}   r   r4  r   r2   r   r*  r   )r9   r  whichr  ra   r0   ef_mapr   r.   coefficientsr   r  r  r   r   rR  s                   r:   !get_coefficients_of_determinationz8DynamicFactorMQResults.get_coefficients_of_determination5  s   D 	3VX 8F G="&"5"5"=J:E**$$JJ((	//jj,,zz..\!88Wi$89L9% 4#DLL$7$<$<QT$BCw 4A{{1a4( $ 3 3 9 9! <tV<@@BKK %QT* .0VVQT*44 <<K0<>L< 9 w88WJ/LU 34D7^ B++11!4UU4Q/0779HHQUOq&1557@@ Q	B 99\EL& % |#88Wi$89LU 34D7^ 4++11!4y) 4Azz}}55::1a4@UU4QQY)?$)7i!ma.?#@$A B HHQ		$(>(>(@%@Aq&9==?HH %QT* .0VVQT*44 <<K0<>L r<   c                 &    | j                  d      S )a  
        Individual coefficients of determination (:math:`R^2`).

        Coefficients of determination (:math:`R^2`) from regressions of
        endogenous variables on individual estimated factors.

        Returns
        -------
        coefficients_of_determination : ndarray
            A `k_endog` x `k_factors` array, where
            `coefficients_of_determination[i, j]` represents the :math:`R^2`
            value from a regression of factor `j` and a constant on endogenous
            variable `i`.

        Notes
        -----
        Although it can be difficult to interpret the estimated factor loadings
        and factors, it is often helpful to use the coefficients of
        determination from univariate regressions to assess the importance of
        each factor in explaining the variation in each endogenous variable.

        In models with many variables and factors, this can sometimes lend
        interpretation to the factors (for example sometimes one factor will
        load primarily on real variables and another on nominal variables).

        See Also
        --------
        get_coefficients_of_determination
        plot_coefficients_of_determination
        r  )r  )r  r;  s    r:   coefficients_of_determinationz4DynamicFactorMQResults.coefficients_of_determination  s    @ 55\5JJr<   c                    ddl m}m}  |         |||      }t        |dg d      }|| j                  j
                  dk  }| j                  ||      }|dv rd	}	|j                  j                         D ]  \  }
}|j                  | j                  j                  d	|	      }|j                  d
       |j                  |
 d       |j                  |d       |	t        |j                        k  s|s|j                   j#                  g        |	d	z  }	 |S |dk(  rg|j                  d	d	d	      }|j                  d
       |j                  dd       |j                  |d       |s|j                   j#                  g        |S )a  
        Plot coefficients of determination (R-squared) for variables / factors.

        Parameters
        ----------
        method : {'individual', 'joint', 'cumulative'}, optional
            The type of R-squared values to generate. "individual" plots
            the R-squared of each variable on each factor; "joint" plots the
            R-squared of each variable on each factor that it loads on;
            "cumulative" plots the successive R-squared values as each
            additional factor is added to the regression, for each variable.
            Default is 'individual'.
        which: {None, 'filtered', 'smoothed'}, optional
            Whether to compute R-squared values based on filtered or smoothed
            estimates of the factors. Default is 'smoothed' if smoothed results
            are available and 'filtered' otherwise.
        endog_labels : bool, optional
            Whether or not to label the endogenous variables along the x-axis
            of the plots. Default is to include labels if there are 5 or fewer
            endogenous variables.
        fig : Figure, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        The endogenous variables are arranged along the x-axis according to
        their position in the model's `endog` array.

        See Also
        --------
        get_coefficients_of_determination
        r   )_import_mplcreate_mpl_figr  r  r  r(   )r  r  )r  r}  rS   )r   rS   z$R^2$)rQ  ylabelbar)axkindr  z($R^2$ - regression on all loaded factors)statsmodels.graphics.utilsr  r  r   r\  ra   r  rA   iterrowsadd_subplotr0   set_ylimrn   plotr/   r   xaxisset_ticklabels)r9   r  r  endog_labelsfigfigsizer  r  r  plot_idxr   coeffsr  s                r:   "plot_coefficients_of_determinationz9DynamicFactorMQResults.plot_coefficients_of_determination  s   P 	KS'*VX 8F G ::--2L 99@E : G 11H'/zz':':'< 
#V__TZZ%9%91hGF#}h?r.c("2"233<HH++B/A
( 
 wAq)BKKFFD"  $MMReM,''+
r<   c                    t        |   d||||||||	|
d	|}| j                  j                  r.|r+|j                  }|j
                  j                  \  }}t        j                  | j                  j                        }t        j                  | j                  j                        }| j                  j                  dkD  r|dddf   }|dddf   }|j                  j                  |z  |z   |j                  _        |dk(  r$|j                  xj                  |dz  z  c_        |S ||j                  j                  z  |j                  z  |j                  _        |S )a  
        In-sample prediction and out-of-sample forecasting.

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.
        dynamic : bool, int, str, or datetime, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Can also be an absolute date string to parse or a
            datetime type (these are not interpreted as offsets).
            Prior to this observation, true endogenous values will be used for
            prediction; starting with this observation and continuing through
            the end of prediction, forecasted endogenous values will be used
            instead.
        information_set : str, optional
            The information set to condition each prediction on. Default is
            "predicted", which computes predictions of period t values
            conditional on observed data through period t-1; these are
            one-step-ahead predictions, and correspond with the typical
            `fittedvalues` results attribute. Alternatives are "filtered",
            which computes predictions of period t values conditional on
            observed data through period t, and "smoothed", which computes
            predictions of period t values conditional on the entire dataset
            (including also future observations t+1, t+2, ...).
        signal_only : bool, optional
            Whether to compute forecasts of only the "signal" component of
            the observation equation. Default is False. For example, the
            observation equation of a time-invariant model is
            :math:`y_t = d + Z \alpha_t + \varepsilon_t`, and the "signal"
            component is then :math:`Z \alpha_t`. If this argument is set to
            True, then forecasts of the "signal" :math:`Z \alpha_t` will be
            returned. Otherwise, the default is for forecasts of :math:`y_t`
            to be returned.
        original_scale : bool, optional
            If the model specification standardized the data, whether or not
            to return predictions in the original scale of the data (i.e.
            before it was standardized by the model). Default is True.
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. See `FilterResults.predict` for more details.

        Returns
        -------
        forecast : ndarray
            Array of out of in-sample predictions and / or out-of-sample
            forecasts. An (npredict x k_endog) array.
        )	r   enddynamicinformation_setsignal_onlyr\   r  rn  ro  rS   Nr   rO   )r  get_predictionr\  r   prediction_resultsr   rs   r>   r   r   r   ra   r  _predicted_mean_var_pred_meanrA   )r9   r   r  r  r  r  rv  r\   r  rn  ro  r  r#  r  ra   r  r|   r   r  s                     r:   r  z%DynamicFactorMQResults.get_prediction  sL   | g$ L5c75D1<+0t2>3@L
 EKL ::!!n!$!7!7+1177JGQ88DJJ223D((4::001Czz!!A%D!G}$'l ,,s2T9 LL( !|++sAv5+
 
 #,,555= + 
r<   c                    |
dk(  r@t        j                  | j                  j                  | j                  j                  z
        }
t        |   |f||||||||	|
|||d|}|s| j                  j                  r|r| j                  j                  }| j                  j                  }|j                  |z  |_
        |j                  |z  |_        |j                  |j                  |z  |_        |j                  |j                  |z  |_        |j                  |j                  |z  |_        dD ]h  }t        ||      }d}t!        |d      r|j"                  }|j%                  |d      }|dvr|j'                  |d      }|||_        t)        |||       j |j*                  j-                  |d	d
      j%                  |dd
      |_        |j.                  j-                  |d	d
      j%                  |dd
      |_        |S )u  
        Compute impacts from updated data (news and revisions).

        Parameters
        ----------
        comparison : array_like or MLEResults
            An updated dataset with updated and/or revised data from which the
            news can be computed, or an updated or previous results object
            to use in computing the news.
        impact_date : int, str, or datetime, optional
            A single specific period of impacts from news and revisions to
            compute. Can also be a date string to parse or a datetime type.
            This argument cannot be used in combination with `start`, `end`, or
            `periods`. Default is the first out-of-sample observation.
        impacted_variable : str, list, array, or slice, optional
            Observation variable label or slice of labels specifying that only
            specific impacted variables should be shown in the News output. The
            impacted variable(s) describe the variables that were *affected* by
            the news. If you do not know the labels for the variables, check
            the `endog_names` attribute of the model instance.
        start : int, str, or datetime, optional
            The first period of impacts from news and revisions to compute.
            Can also be a date string to parse or a datetime type. Default is
            the first out-of-sample observation.
        end : int, str, or datetime, optional
            The last period of impacts from news and revisions to compute.
            Can also be a date string to parse or a datetime type. Default is
            the first out-of-sample observation.
        periods : int, optional
            The number of periods of impacts from news and revisions to
            compute.
        exog : array_like, optional
            Array of exogenous regressors for the out-of-sample period, if
            applicable.
        comparison_type : {None, 'previous', 'updated'}
            This denotes whether the `comparison` argument represents a
            *previous* results object or dataset or an *updated* results object
            or dataset. If not specified, then an attempt is made to determine
            the comparison type.
        state_index : array_like or "common", optional
            An optional index specifying a subset of states to use when
            constructing the impacts of revisions and news. For example, if
            `state_index=[0, 1]` is passed, then only the impacts to the
            observed variables arising from the impacts to the first two
            states will be returned. If the string "common" is passed and the
            model includes idiosyncratic AR(1) components, news will only be
            computed based on the common states. Default is to use all states.
        return_raw : bool, optional
            Whether or not to return only the specific output or a full
            results object. Default is to return a full results object.
        tolerance : float, optional
            The numerical threshold for determining zero impact. Default is
            that any impact less than 1e-10 is assumed to be zero.
        endog_quarterly : array_like, optional
            New observations of quarterly variables, if `comparison` was
            provided as an updated monthly dataset. If this argument is
            provided, it must be a Pandas Series or DataFrame with a
            DatetimeIndex or PeriodIndex at the quarterly frequency.

        References
        ----------
        .. [1] Bańbura, Marta, and Michele Modugno.
               "Maximum likelihood estimation of factor models on datasets with
               arbitrary pattern of missing data."
               Journal of Applied Econometrics 29, no. 1 (2014): 133-160.
        .. [2] Bańbura, Marta, Domenico Giannone, and Lucrezia Reichlin.
               "Nowcasting."
               The Oxford Handbook of Economic Forecasting. July 8, 2011.
        .. [3] Bańbura, Marta, Domenico Giannone, Michele Modugno, and Lucrezia
               Reichlin.
               "Now-casting and the real-time data flow."
               In Handbook of economic forecasting, vol. 2, pp. 195-237.
               Elsevier, 2013.
        common)impact_dateimpacted_variabler   r  periodsr  comparison_typerevisions_details_startstate_index
return_rawr  r  N)prev_impacted_forecastsnews	revisionsupdate_realizedupdate_forecastsrevisedrevised_prevpost_impacted_forecastsrevisions_allrevised_allrevised_prev_allr[   rS   )rq  )r  r  r   rp  )r>   r@   r\  r8   ra   r  r  r   r   r   total_impactsupdate_impactsrevision_impactsrevision_detailed_impactsrevision_grouped_impactsr   r#  r[   rs  rt  setattrweightsdividerevision_weights)r9   
comparisonr  r  r   r  r  r  r  r  r  r  r  r  rv  r  news_resultsr  r  r[   dta	orig_namer  s                         r:   r  zDynamicFactorMQResults.news^  s7   ^ ("		$**--

0B0BBC  w|L$//u#$$;#
L EKL djj44//J

--I
 **Y6 & ++i7 ',,8 11I= -55A ::YF 644@ 99IE 5M 1 lD1
 !	3' #Ill9Al644''*A'6C ((CHdC0-1F $$++IAQ+G%-XiaqX%I   --#VIAQV?%XiaqXA )
 r<   c                 $   | j                   j                  r4|r2| j                   d   }| j                   j                  | j                   d<   t        
|   ||      \  }}}}| j                   j                  r|r| j                   d<   |dk(  r~| j                   j                  rh|rf| j                   j
                  }	|j                  |	dd      }|j                  |	dd      }|j                  |	dd      }|j                  |	dd      }||||fS )a  
        Decompose smoothed output into contributions from observations

        Parameters
        ----------
        decomposition_of : {"smoothed_state", "smoothed_signal"}
            The object to perform a decomposition of. If it is set to
            "smoothed_state", then the elements of the smoothed state vector
            are decomposed into the contributions of each observation. If it
            is set to "smoothed_signal", then the predictions of the
            observation vector based on the smoothed state vector are
            decomposed. Default is "smoothed_state".
        state_index : array_like, optional
            An optional index specifying a subset of states to use when
            constructing the decomposition of the "smoothed_signal". For
            example, if `state_index=[0, 1]` is passed, then only the
            contributions of observed variables to the smoothed signal arising
            from the first two states will be returned. Note that if not all
            states are used, the contributions will not sum to the smoothed
            signal. Default is to use all states.
        original_scale : bool, optional
            If the model specification standardized the data, whether or not
            to return simulations in the original scale of the data (i.e.
            before it was standardized by the model). Default is True.

        Returns
        -------
        data_contributions : pd.DataFrame
            Contributions of observations to the decomposed object. If the
            smoothed state is being decomposed, then `data_contributions` is
            shaped `(k_states x nobs, k_endog x nobs)` with a `pd.MultiIndex`
            index corresponding to `state_to x date_to` and `pd.MultiIndex`
            columns corresponding to `variable_from x date_from`. If the
            smoothed signal is being decomposed, then `data_contributions` is
            shaped `(k_endog x nobs, k_endog x nobs)` with `pd.MultiIndex`-es
            corresponding to `variable_to x date_to` and
            `variable_from x date_from`.
        obs_intercept_contributions : pd.DataFrame
            Contributions of the observation intercept to the decomposed
            object. If the smoothed state is being decomposed, then
            `obs_intercept_contributions` is
            shaped `(k_states x nobs, k_endog x nobs)` with a `pd.MultiIndex`
            index corresponding to `state_to x date_to` and `pd.MultiIndex`
            columns corresponding to `obs_intercept_from x date_from`. If the
            smoothed signal is being decomposed, then
            `obs_intercept_contributions` is shaped
            `(k_endog x nobs, k_endog x nobs)` with `pd.MultiIndex`-es
            corresponding to `variable_to x date_to` and
            `obs_intercept_from x date_from`.
        state_intercept_contributions : pd.DataFrame
            Contributions of the state intercept to the decomposed
            object. If the smoothed state is being decomposed, then
            `state_intercept_contributions` is
            shaped `(k_states x nobs, k_states x nobs)` with a `pd.MultiIndex`
            index corresponding to `state_to x date_to` and `pd.MultiIndex`
            columns corresponding to `state_intercept_from x date_from`. If the
            smoothed signal is being decomposed, then
            `state_intercept_contributions` is shaped
            `(k_endog x nobs, k_states x nobs)` with `pd.MultiIndex`-es
            corresponding to `variable_to x date_to` and
            `state_intercept_from x date_from`.
        prior_contributions : pd.DataFrame
            Contributions of the prior to the decomposed object. If the
            smoothed state is being decomposed, then `prior_contributions` is
            shaped `(nobs x k_states, k_states)`, with a `pd.MultiIndex`
            index corresponding to `state_to x date_to` and columns
            corresponding to elements of the prior mean (aka "initial state").
            If the smoothed signal is being decomposed, then
            `prior_contributions` is shaped `(nobs x k_endog, k_states)`,
            with a `pd.MultiIndex` index corresponding to
            `variable_to x date_to` and columns corresponding to elements of
            the prior mean.

        Notes
        -----
        Denote the smoothed state at time :math:`t` by :math:`\alpha_t`. Then
        the smoothed signal is :math:`Z_t \alpha_t`, where :math:`Z_t` is the
        design matrix operative at time :math:`t`.
        obs_intercept)decomposition_ofr  smoothed_signalr   rp  )r\  r   r   r  get_smoothed_decompositionr   rs  )r9   r  r  rv  cache_obs_interceptdata_contributionsobs_intercept_contributionsstate_intercept_contributionsprior_contributionsr  r  s             r:   r  z1DynamicFactorMQResults.get_smoothed_decomposition  sC   j ::!!n"&**_"=*.***@*@DJJ'
 G.!1{ / L	=	8	&(;
 ::!!n*=DJJ'  11JJ**~

--I #++IAQ+G  ,44AQ 5 0 ( .66AQ 7 0 * $,,YQa,H   #$?-/BD 	Dr<   c                 6   t         j                  ||      \  }}t        |j                        dk(  r|j                  d   nd}	|| j                  j
                  k7  s|	| j                  j                  k7  rt        d      ||d<   t        
| $  |f||||d|S )a
  
        Recreate the results object with new data appended to original data.

        Creates a new result object applied to a dataset that is created by
        appending new data to the end of the model's original data. The new
        results can then be used for analysis or forecasting.

        Parameters
        ----------
        endog : array_like
            New observations from the modeled time-series process.
        endog_quarterly : array_like, optional
            New observations of quarterly variables. If provided, must be a
            Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at
            the quarterly frequency.
        refit : bool, optional
            Whether to re-fit the parameters, based on the combined dataset.
            Default is False (so parameters from the current results object
            are used to create the new results object).
        fit_kwargs : dict, optional
            Keyword arguments to pass to `fit` (if `refit=True`) or `filter` /
            `smooth`.
        copy_initialization : bool, optional
            Whether or not to copy the initialization from the current results
            set to the new model. Default is True.
        retain_standardization : bool, optional
            Whether or not to use the mean and standard deviations that were
            used to standardize the data in the current model in the new model.
            Default is True.
        **kwargs
            Keyword arguments may be used to modify model specification
            arguments when created the new model object.

        Returns
        -------
        results
            Updated Results object, that includes results from both the
            original dataset and the new dataset.

        Notes
        -----
        The `endog` and `exog` arguments to this method must be formatted in
        the same way (e.g. Pandas Series versus Numpy array) as were the
        `endog` and `exog` arrays passed to the original model.

        The `endog` (and, if applicable, `endog_quarterly`) arguments to this
        method should consist of new observations that occurred directly after
        the last element of `endog`. For any other kind of dataset, see the
        `apply` method.

        This method will apply filtering to all of the original data as well
        as to the new data. To apply filtering only to the new data (which
        can be much faster if the original dataset is large), see the `extend`
        method.

        See Also
        --------
        extend
        apply
        r   rS   7Cannot append data of a different dimension to a model.r   )refit
fit_kwargscopy_initializationr4  )
r   r   r/   rs   r\  r`   ra   rj   r  r   )r9   r   r  r  r  r  r4  r  r   ra   r  s             r:   r   zDynamicFactorMQResults.appends  s    @ "1!@!@?"$ %($4$9%++a.qtzz3334::--- ) * * %4 !w~E: 3#9E >DE 	Er<   c                 2   t         j                  ||      \  }}t        |j                        dk(  r|j                  d   nd}|| j                  j
                  k7  s|| j                  j                  k7  rt        d      ||d<   t        | $  |f||d|S )a  
        Recreate the results object for new data that extends original data.

        Creates a new result object applied to a new dataset that is assumed to
        follow directly from the end of the model's original data. The new
        results can then be used for analysis or forecasting.

        Parameters
        ----------
        endog : array_like
            New observations from the modeled time-series process.
        endog_quarterly : array_like, optional
            New observations of quarterly variables. If provided, must be a
            Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at
            the quarterly frequency.
        fit_kwargs : dict, optional
            Keyword arguments to pass to `filter` or `smooth`.
        retain_standardization : bool, optional
            Whether or not to use the mean and standard deviations that were
            used to standardize the data in the current model in the new model.
            Default is True.
        **kwargs
            Keyword arguments may be used to modify model specification
            arguments when created the new model object.

        Returns
        -------
        results
            Updated Results object, that includes results only for the new
            dataset.

        See Also
        --------
        append
        apply

        Notes
        -----
        The `endog` argument to this method should consist of new observations
        that occurred directly after the last element of the model's original
        `endog` array. For any other kind of dataset, see the `apply` method.

        This method will apply filtering only to the new data provided by the
        `endog` argument, which can be much faster than re-filtering the entire
        dataset. However, the returned results object will only have results
        for the new data. To retrieve results for both the new data and the
        original data, see the `append` method.
        r   rS   r  r   )r  r4  )
r   r   r/   rs   r\  r`   ra   rj   r  rm   )	r9   r   r  r  r4  r  r   ra   r  s	           r:   rm   zDynamicFactorMQResults.extend  s    f "1!@!@?"$ %($4$9%++a.qtzz3334::--- ) * * %4 !w~E(#9E=CE 	Er<   c                      | j                   j                  |f|||d|}	|r:t        j                  j	                  | j
                        }
|
|	j                  _        | j                  |	||      }|S )a#
  
        Apply the fitted parameters to new data unrelated to the original data.

        Creates a new result object using the current fitted parameters,
        applied to a completely new dataset that is assumed to be unrelated to
        the model's original data. The new results can then be used for
        analysis or forecasting.

        Parameters
        ----------
        endog : array_like
            New observations from the modeled time-series process.
        k_endog_monthly : int, optional
            If specifying a monthly/quarterly mixed frequency model in which
            the provided `endog` dataset contains both the monthly and
            quarterly data, this variable should be used to indicate how many
            of the variables are monthly.
        endog_quarterly : array_like, optional
            New observations of quarterly variables. If provided, must be a
            Pandas Series or DataFrame with a DatetimeIndex or PeriodIndex at
            the quarterly frequency.
        refit : bool, optional
            Whether to re-fit the parameters, using the new dataset.
            Default is False (so parameters from the current results object
            are used to create the new results object).
        fit_kwargs : dict, optional
            Keyword arguments to pass to `fit` (if `refit=True`) or `filter` /
            `smooth`.
        copy_initialization : bool, optional
            Whether or not to copy the initialization from the current results
            set to the new model. Default is False.
        retain_standardization : bool, optional
            Whether or not to use the mean and standard deviations that were
            used to standardize the data in the current model in the new model.
            Default is True.
        **kwargs
            Keyword arguments may be used to modify model specification
            arguments when created the new model object.

        Returns
        -------
        results
            Updated Results object, that includes results only for the new
            dataset.

        See Also
        --------
        statsmodels.tsa.statespace.mlemodel.MLEResults.append
        statsmodels.tsa.statespace.mlemodel.MLEResults.apply

        Notes
        -----
        The `endog` argument to this method should consist of new observations
        that are not necessarily related to the original model's `endog`
        dataset. For observations that continue that original dataset by follow
        directly after its last element, see the `append` and `extend` methods.
        )r   r  r4  )r  r  )r\  r6  r   r?  from_resultsr  r  _apply)r9   r   r   r  r  r  r  r4  r  r5  rA  r#  s               r:   applyzDynamicFactorMQResults.apply  s}    x djju )o/>6L) "() !00==##%D%)CGG"kk#UzkB
r<   c
                     | j                   }
|d}|| j                   j                  }| j                   j                  |      }d}g }t        | dd      }t        | dd      }|#|j                  dk(  r|d|j
                   gfgz  }t        %|   |||||xr ||||	||
      }d	}|st        j                  | j                  j                  dd|
j                  d
   df   ||
j                        }	 |j                  d       }d	}|
j"                  r$| j$                  |
j&                  d      |d<   |d	z  }| j$                  |
j&                  d      |d<   |j(                  | d }||   j+                  t,              ||<   	 |j.                  dd| df   j                  d       |j.                  dd| df<   d|j0                  _        t5        j6                  |
j8                        }t;        |
j<                        D ]=  }|D cg c]  }||
j                  j>                  |   vr|! }}d|j.                  ||f<   ? |jA                         }|jB                  }|j(                  jE                         }d}d}tG        |||tH        |      }|jJ                  jM                  ||       |d	z  }d}d}t;        tO        |
j                  jP                              D ]R  }|
j                  jP                  |   }||j8                  z  }| j                  jR                  } g }!t;        |jT                        D ](  }|!|j                  D "cg c]  }"d|d	z    d|"  c}"z  }!* t        j                  | |jV                  |jX                  df   |j                  |!      }d|j0                  _        	 |j                  d       }| j                  jZ                  }#|j8                  d	k(  r|#||f   |d<   nE|j                  |d<   t;        |j8                        D ]  }|#||||z   f   ||j                  |   <     |j(                  |j8                   d }||   j+                  t,              ||<   	 |j.                  dd|j8                   df   j                  d       }$|$|j.                  dd|j8                   df<   |jA                         }|jB                  }|j(                  jE                         }d}d!| }tG        |||tH        |      }|jJ                  jM                  ||       |d	z  }|}U |S # t        $ r |j!                  d       }Y Mw xY w# t        $ r> |j.                  dd| df   j!                  d       |j.                  dd| df<   Y w xY wc c}w c c}"w # t        $ r |j!                  d       }Y w xY w# t        $ r4 |j.                  dd|j8                   df   j!                  d        }$Y mw xY w)"a  
        Summarize the Model.

        Parameters
        ----------
        alpha : float, optional
            Significance level for the confidence intervals. Default is 0.05.
        start : int, optional
            Integer of the start observation. Default is 0.
        title : str, optional
            The title used for the summary table.
        model_name : str, optional
            The name of the model used. Default is to use model class name.

        Returns
        -------
        summary : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        NzDynamic Factor Results)rD  r  r  r  zEM Iterations)
r  r   rQ  rJ  display_paramsdisplay_diagnosticsre  display_max_endogextra_top_leftextra_top_rightrS   r,   r   r   c                     d| z  S Nz%.2frO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  s
    &1* r<   c                     d| z  S r  rO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  s
    vz r<   rb   z   idiosyncratic: AR(1)r   zvar.c                 
    | dS Nz.2frO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  
    3 r<   c                 
    | dS r  rO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  r  r<   zFactor loadings:r   zObservation equation:rT  rt  rN  c                     d| z  S r  rO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  s
    fqj r<   c                     d| z  S r  rO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  s
    6A: r<   z   error variancez   error covariancec                 
    | dS r  rO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  
    QsG r<   c                 
    | dS r  rO   r  s    r:   rX  z0DynamicFactorMQResults.summary.<locals>.<lambda>  r  r<   zTransition: Factor block ).r\  rL  rF  r   r  r  r  rj  r}   r   r  r   r   r.   ra  r_  rd  rb   r  r  r   r*  r+  r   r\   r[   r>   r@   r0   rk   ra   r   rv   rl   r   r"   r$   rb  rc  r/   r   r   r1   r,   r*   r  )&r9   r  r   rQ  rJ  r  r  display_params_as_listre  r  r5  r   r  r  r  r  rj  rk  r  k_idiocols_to_cast	base_ilocr   r  r   rm  rn  ro  rp  r   r   rY   rA   	lag_namesr[   r   formatted_valsr  s&                                        r:   rj  zDynamicFactorMQResults.summaryO  sE   8 jj =,E//J jj11) 2 + dM48t^T:#(;(;t(Ck6F6F5G2I JKKO '/uEj*E/E 3!5/)? " L % <<##**1cff\.BA+EF!3+;+;=D;xx 45 F$$KK': ;< ./!;;svv.A'BCDL<<1L!%l!3!:!:6!BD*)-1vgh;)?)C)C(**		!fWX+& 1DJJO 		#--0I3;;' )#, AaCFF$<$<Q$??  A A%(		!T'")
 ##%D ++K LL//1ML+E]L"%1E NN!!(E2MH CC3svv3345 3,,Q/u&''22	u112 BA.3.@.@"B&* %&a!eWAdV"4 "B BIB ||Ae&6&68H8H!&K$L*/*<*<,57 #%

?88$89D ''11??a'01#s(D,-272D2DD./"5??3 J67Cq8H6IU//23J#||U__,<,=>%),%7%>%>v%F\"%)YYq5??2B2C/C%D%H%H,&N 3A		!eoo-../'')"kk $ 3 3 5#3A37#&e5 %%h6Ag3j I " ;}}%9:;" " *)-1vgh;)?)H)H(**		!fWX+&*A8"B & ?==)=>D?" & %)YYq5??2B2C/C%D%M%M,&NsU   7T8 :U $V$V)
2V./0W8UUAV! V!.WW9XXr   )r  N)r  NNNN)
NNF	predictedFTNNNN)NNNNNNNFNFr   NT)r	  NT)NFNTT)NNT)NNFNFT)	g?NNNTFFNr   )rJ   rK   rL   rM   r;   rN   r)   r  r   r  r  r  r  r  r   rm   r  rj  r  r  s   @r:   r9  r9    s    ? % %N 8D04Zx K KB 9EDH=AM^ <A@E=A8<Zx DH6:;@;@26	]~ ;KDHtDl KO@DOEb >B&*@ED BF@E%)GR EI9>CG"#g gr<   r9  )DrM   statsmodels.compat.pandasr   r   collectionsr   warningsr   numpyr>   pandasr}   scipy.linalgr   r   r	   statsmodels.tools.datar
   statsmodels.tools.validationr   statsmodels.tools.decoratorsr   #statsmodels.regression.linear_modelr   +statsmodels.genmod.generalized_linear_modelr   statsmodels.multivariate.pcar   "statsmodels.tsa.statespace.sarimaxr   )statsmodels.tsa.statespace._quarterly_ar1r   #statsmodels.tsa.vector_ar.var_modelr   statsmodels.tools.toolsr   r   statsmodels.tsa.tsatoolsr   statsmodels.tsa.statespacer   r    statsmodels.tsa.statespace.toolsr   r   r   r   r   r   *statsmodels.tsa.statespace.kalman_smootherr   r   r    statsmodels.base.datar!   statsmodels.iolib.tabler"   statsmodels.iolib.summaryr#   !statsmodels.iolib.tableformattingr$   ri   r&   rQ   MLEModelr   
MLEResultsr9  rO   r<   r:   <module>r"     s    = #    ; ; 3 1 7 3 ; , 6 B 3 ) 4 + ?) )@ @ , / - 8^/$ ^/Bj D j ZI)h'' I)XRqX00 qr<   