rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
return np.abs(fft.fft(self.ma, n) / fft.fft(self.ar, n))[n//2-1:] | hw = fft.fft(self.ma, n) / fft.fft(self.ar, n) w = fft.fftfreq(n) wslice = slice(n//2-1, None, None) return (np.abs(hw)**2)[wslice], w[wslice] | def spddirect(self, n): #size = s1+s2-1 #abs looks wrong return np.abs(fft.fft(self.ma, n) / fft.fft(self.ar, n))[n//2-1:] |
return np.squeeze(hw) | return np.squeeze(hw), w.squeeze() | def spdroots_(self, arroots, maroots, w): '''spectral density for frequency using polynomial roots |
0.5 / np.pi * self.mapoly(np.exp(w*1j)) | return 0.5 / np.pi * self.mapoly(np.exp(w*1j)) def plot4(self, fig, nobs=100, nacf=20, nfreq=100): rvs = self.generate_sample(size=100, burnin=500) acf = self.acf(nacf)[:nacf] pacf = self.pacf(nacf) w = np.linspace(0, np.pi, nfreq) spdr, wr = self.spdroots(w) ax = fig.add_subplot(2,2,1) ax.plot(rvs) ax.set_title('Ra... | def spdmapoly(self, w, twosided=False): '''ma only, need division for ar, use LagPolynomial ''' if w is None: w = np.linspace(0, np.pi, nfreq) 0.5 / np.pi * self.mapoly(np.exp(w*1j)) |
spd2 = arma1.spdshift(2**10) | spd2, w2 = arma1.spdshift(2**10) | def spdar1(ar, w): if len(ar) == 1: rho = ar else: rho = ar[1] return 0.5 / np.pi /(1 + rho*rho - 2 * rho * np.cos(w)) |
spd3 = arma1.spddirect(2**10) | spd3, w3 = arma1.spddirect(2**10) | def spdar1(ar, w): if len(ar) == 1: rho = ar else: rho = ar[1] return 0.5 / np.pi /(1 + rho*rho - 2 * rho * np.cos(w)) |
spdr = arma1.spdroots(w) | spdr, wr = arma1.spdroots(w) | def spdar1(ar, w): if len(ar) == 1: rho = ar else: rho = ar[1] return 0.5 / np.pi /(1 + rho*rho - 2 * rho * np.cos(w)) |
wper, spdper = arma1.arma_periodogram(nfreq) | wper, spdper = arma1.periodogram(nfreq) | def spdar1(ar, w): if len(ar) == 1: rho = ar else: rho = ar[1] return 0.5 / np.pi /(1 + rho*rho - 2 * rho * np.cos(w)) |
class ARMA(LikelihoodModel): | class ARMA(GenericLikelihoodModel): | def updatematrices(params, y, xi10, ntrain, penalty, upperbound, lowerbound): """ TODO: change API, update names This isn't general. Copy of Luca's matlab example. """ paramsorig = params # are the bounds binding? params = np.min((np.max((lowerbound,params),axis=0),upperbound), axis=0) rho = params[0] sigma1 = params... |
dk = zipfile.ZipFile('/home/skipper/statsmodels/DK-data.zip') | dk = zipfile.ZipFile('/home/skipper/statsmodels/statsmodels-skipper/scikits/statsmodels/sandbox/tsa/DK-data.zip') | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
from scikits.statsmodels.sandbox.tsa.arima import arma_generate_sample | from scikits.statsmodels.tsa.arima_process import arma_generate_sample | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
self.recursionparams[2] = 1 | def __init__(self, endog, exog, tree, paramsind): self.endog = endog self.datadict = exog self.tree = tree self.paramsind = paramsind | |
bv = np.exp(bv) | bv = np.exp(bv/tau) | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' endog = self.endog datadict = self.datadict paramsind = self.paramsind branchsum = self.branchsum |
self.recursionparams[self.parinddict[tree]])) | self.recursionparams[self.parinddict[tree]]) / tau) | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' endog = self.endog datadict = self.datadict paramsind = self.paramsind branchsum = self.branchsum |
if isinstance(b, str): | if not type(b) == tuple: | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' endog = self.endog datadict = self.datadict paramsind = self.paramsind branchsum = self.branchsum |
bprob = branchvalue[bidx]/branchsum | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' endog = self.endog datadict = self.datadict paramsind = self.paramsind branchsum = self.branchsum | |
return leafprob | return np.log(leafprob) | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' endog = self.endog datadict = self.datadict paramsind = self.paramsind branchsum = self.branchsum |
INPUTS: p -- probabilities | Parameters ---------- p: array-like Probabilities | def deriv(self, p): |
xlags = sm.add_constant(lagmat(x, nlags), prepend=True) | xlags = sm.add_constant(xlags, prepend=True) | def pacf_ols(x, nlags=40): '''Calculate partial autocorrelations Parameters ---------- x : 1d array observations of time series for which pacf is calculated nlags : int Number of lags for which pacf is returned. Lag 0 is not returned. Returns ------- pacf : 1d array partial autocorrelations, maxlag+1 elements Notes... |
Parameter --------- | Parameters ---------- | def invertroots(self, retnew=False): '''make MA polynomial invertible by inverting roots inside unit circle |
colwidths = 15, | def summary(self, yname=None, xname=None): """returns a string that summarizes the regression results | |
results[lag] = mod_instance.fit(*fitargs, maxlag=lag) | results[lag] = mod_instance.fit(*fitargs, **{maxlag:lag}) | def _autolag(mod, endog, exog, lagstart, maxlag, method, modargs=(), fitargs=()): """ Returns the results for the lag length that maximimizes the info criterion. Parameters ---------- mod : Model class Model estimator class. modargs : tuple args to pass to model. See notes. fitargs : tuple args to pass to fit. See n... |
lead = windsize//2 | lead = -0 sl = slice((windsize-1) or None, -2*(windsize-1) or None) | def movmoment(x, k, windowsize=3, lag='lagged'): '''non-central moment Parameters ---------- x : array time series data windsize : int window size lag : 'lagged', 'centered', or 'leading' location of window relative to current position Returns ------- mk : array k-th moving non-central moment, with same shape as x ... |
lead = 0 | lead = -windsize//2 sl = slice((windsize-1)+windsize//2 or None, -(windsize-1)-windsize//2 or None) | def movmoment(x, k, windowsize=3, lag='lagged'): '''non-central moment Parameters ---------- x : array time series data windsize : int window size lag : 'lagged', 'centered', or 'leading' location of window relative to current position Returns ------- mk : array k-th moving non-central moment, with same shape as x ... |
lead = -windsize//2 +1 | lead = -windsize +2 sl = slice(2*(windsize-1)+1+lead or None, -(2*(windsize-1)+lead)+1 or None) | def movmoment(x, k, windowsize=3, lag='lagged'): '''non-central moment Parameters ---------- x : array time series data windsize : int window size lag : 'lagged', 'centered', or 'leading' location of window relative to current position Returns ------- mk : array k-th moving non-central moment, with same shape as x ... |
return np.correlate(xext**k, avgkern, 'full')[windsize-lead:-(windsize+lead)] | return np.correlate(xext**k, avgkern, 'full')[sl] | def movmoment(x, k, windowsize=3, lag='lagged'): '''non-central moment Parameters ---------- x : array time series data windsize : int window size lag : 'lagged', 'centered', or 'leading' location of window relative to current position Returns ------- mk : array k-th moving non-central moment, with same shape as x ... |
return signal.correlate(xext**k, avgkern[:,None], 'full')[windsize-lead:-(windsize+lead),:] | return signal.correlate(xext**k, avgkern[:,None], 'full')[sl,:] | def movmoment(x, k, windowsize=3, lag='lagged'): '''non-central moment Parameters ---------- x : array time series data windsize : int window size lag : 'lagged', 'centered', or 'leading' location of window relative to current position Returns ------- mk : array k-th moving non-central moment, with same shape as x ... |
newparams = params.copy() if p != 0: newparams = ((1-exp(-params[k:k+p]))/(1+exp(-params[k:k+p]))).copy() tmp = ((1-exp(-params[k:k+p]))/(1+exp(-params[k:k+p]))).copy() for j in range(1,p): a = newparams[j] for kiter in range(j): tmp[kiter] -= a * newparams[j-kiter-1] newparams[:j] = tmp[:j] params[k:k+p] = newparam... | newparams = self._transparams(start_params) | def loglike(self, params): |
if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a * newparams[j-k-1])/(1-a**2) newparams[:j] = tmp[:j] invarcoefs = -log((1-newparams)/(1+newparams)) start_params[k:k+p] = invarcoefs if q != 0: tmp = macoefs.copy() newpar... | start_params = self._invtransparams(start_params) | def fit(self, start_params=None, transparams=True): self.transparams = transparams r = self.r p = self.p q = self.q k = self.k |
results = optimize.fmin_bfgs(loglike, start_params, gtol=1e-2, full_output=1, maxiter=35, disp=1, norm=2) | def fit(self, start_params=None, transparams=True): self.transparams = transparams r = self.r p = self.p q = self.q k = self.k | |
results = optimize.fmin_l_bfgs_b(loglike, start_params, approx_grad=True, m=30, pgtol=1e-7, factr=1e3, bounds=bounds, iprint=1) | def fit(self, start_params=None, transparams=True): self.transparams = transparams r = self.r p = self.p q = self.q k = self.k | |
return y/self.n | return y*1./self.n | def initialize(self, Y): ''' Initialize the response variable. |
Inverse of the link functin. Just a placeholder. | Inverse of the link function. Just a placeholder. | def inverse(self, z): """ Inverse of the link functin. Just a placeholder. |
>>> std_res = (mod_fit.resid - mod_fit.resid.mean())/mod_fit.resid.std() | >>> std_res = (res - res.mean())/res.std() | def qqplot(data, dist=stats.distributions.norm, binom_n=None): """ qqplot of the quantiles of x versus the ppf of a distribution. Parameters ---------- data : array-like 1d data array dist : scipy.stats.distribution or string Compare x against dist. Strings aren't implemented yet. The default is scipy.stats.distribu... |
y_low = np.min(y.min(),quantiles.min())-.25 y_high = np.max(y.max(),quantiles.max())+.25 | y_low = np.min((y.min(),quantiles.min()))-.25 y_high = np.max((y.max(),quantiles.max()))+.25 | def qqplot(data, dist=stats.distributions.norm, binom_n=None): """ qqplot of the quantiles of x versus the ppf of a distribution. Parameters ---------- data : array-like 1d data array dist : scipy.stats.distribution or string Compare x against dist. Strings aren't implemented yet. The default is scipy.stats.distribu... |
errors = [0] * p | if macoefs.size == 0: macoefs = 0 if arcoefs.size == 0: arcoefs = 0 errors = [0] * q | def loglike_css(self, params): """ Conditional Sum of Squares likelihood function. """ p = self.p q = self.q k = self.k y = self.endog.copy() nobs = self.nobs # how to handle if empty? if self.transparams: newparams = self._transparams(params) else: newparams = params if k > 0: |
errors.append(y[i]-sum(arcoefs*y[i-p:i])-sum(macoefs*errors[i-q:i])) | errors.append(y[i]-sum(arcoefs*y[i-p:i])-sum(macoefs*errors[-q:])) | def loglike_css(self, params): """ Conditional Sum of Squares likelihood function. """ p = self.p q = self.q k = self.k y = self.endog.copy() nobs = self.nobs # how to handle if empty? if self.transparams: newparams = self._transparams(params) else: newparams = params if k > 0: |
ssr = sum(errors[p:]**2) | ssr = sum(errors[q:]**2) | def loglike_css(self, params): """ Conditional Sum of Squares likelihood function. """ p = self.p q = self.q k = self.k y = self.endog.copy() nobs = self.nobs # how to handle if empty? if self.transparams: newparams = self._transparams(params) else: newparams = params if k > 0: |
arest = tsa.arima.ARIMA h = arest.generate_sample(ar,ma,nobs,0.1) | from scikits.statsmodels.tsa.arima_process import arma_generate_sample h = arma_generate_sample(ar,ma,nobs,0.1) | def generate_kindofgarch(nobs, ar, ma, mu=1.): '''simulate garch like process but not squared errors in arma used for initial trial but produces nice graph ''' #garm1, gmam1 = [0.4], [0.2] #pqmax = 1 |
def miso_lfilter(ar, ma, x, useic=False): | from scikits.statsmodels.tsa.filters import miso_lfilter def miso_lfilter_old(ar, ma, x, useic=False): | def miso_lfilter(ar, ma, x, useic=False): #[0.1,0.1]): ''' use nd convolution to merge inputs, then use lfilter to produce output arguments for column variables return currently 1d Parameters ---------- ar : array_like, 1d, float autoregressive lag polynomial including lag zero, ar(L)y_t ma : array_like, same ndim as... |
return np.roots(np.r_[1,-self.params[self.k:self.p]])**-1 | return np.roots(np.r_[1,-self.arparams])**-1 | def arroots(self): return np.roots(np.r_[1,-self.params[self.k:self.p]])**-1 |
return np.roots(np.r_[1,np.r_[1,self.params[self.k+self.p:]]])**-1 | return np.roots(np.r_[1,self.maparams]])**-1 | def maroots(self): return np.roots(np.r_[1,np.r_[1,self.params[self.k+self.p:]]])**-1 |
maxiter=maxiter, full_output=full_output, disp=disp) | maxiter=maxiter, disp=disp) | def fit(self, maxlag=None, method='cmle', ic=None, trend='c', transparams=True, start_params=None, solver=None, maxiter=35, full_output=1, disp=1, callback=None, **kwargs): """ Fit the unconditional maximum likelihood of an AR(p) process. |
self.loglike = loglike | self.loglike = self.loglike_css | def fit(self, order, start_params=None, trend='c', method = "css-mle", transparams=True, solver=None, maxiter=35, full_output=1, disp=1, callback=None, **kwargs): """ Fits ARMA(p,q) model using exact maximum likelihood via Kalman filter. |
X = np.column_stack((lagmat(endog,p,'both')[p_tmp+(q-p):,1:], | X = np.column_stack((lagmat(endog,p,'both')[p_tmp+(q-p):], | def _fit_start_params(self, order): """ Get starting parameters for fit. |
SeeAlso ------- | See Also -------- | def pca(data, keepdim=0, normalize=0, demean=True): '''principal components with eigenvector decomposition similar to princomp in matlab Parameters ---------- data : ndarray, 2d data with observations by rows and variables in columns keepdim : integer number of eigenvectors to keep if keepdim is zero, then all eigenve... |
return np.roots(np.r_[1,np.r_[1,self.params[self.k+self.p:]]])**-1 | return np.roots(np.r_[1,self.maparams])**-1 | def maroots(self): return np.roots(np.r_[1,np.r_[1,self.params[self.k+self.p:]]])**-1 |
Yin = np.clip(Y, 1e-12, np.inf) return 2*np.sum(Y*np.log(Yin/mu))/scale | if np.any(Y==0): retarr = np.zeros(Y.shape) Ymu = Y/mu mask = Ymu != 0 YmuMasked = Ymu[mask] Ymasked = Y[mask] np.putmask(retarr, mask, Ymasked*np.log(YmuMasked)/scale) return 2*np.sum(retarr) else: return 2*np.sum(Y*np.log(Y/mu))/scale | def deviance(self, Y, mu, scale=1.): ''' Poisson deviance function |
F = xhat = np.dot(x, xhatparams) | F = xhat = np.dot(z, xhatparams) | def fit(self): #Greene 5th edt., p.78 section 5.4 #move this maybe y,x,z = self.endog, self.exog, self.instrument ztz = np.dot(z.T, z) ztx = np.dot(z.T, x) xhatparams = np.linalg.solve(ztz, ztx) print 'x.T.shape, xhatparams.shape', x.shape, xhatparams.shape F = xhat = np.dot(x, xhatparams) FtF = np.dot(F.T, F) Ftx = np... |
w = np.eye(len(start)) | w = np.eye(self.nmoms) | def fititer(self, start, maxiter=2, start_weights=None, weights_method='cov', wargs=()): '''iterative estimation with updating of optimal weighting matrix |
exampledata = 'iv' | exampledata = 'ivfake' | def momcondIVLS(params, endog, exog, instrum): return instrum * (endog - np.dot(exog, params))[:,None] |
else: | elif exampledata == 'iv': | def sample_iv(exog): X = exog e = sige * np.random.normal(size=nobs) endog = np.dot(X, beta) + e X[:,0] += 0.01 * e z1 = X.sum(1) + np.random.normal(size=nobs) z2 = X[:,1] z3 = (np.dot(X, np.array([2,1, 0])) + sige/2. * np.random.normal(size=nobs)) z4 = X[:,1] + np.random.normal(size=nobs) instrument = np.column_stack(... |
y = self.endog | y = self.endog.copy() | def predict(self, n=0): """ If n == 0, returns fitted values. |
T_mat = block_diag(identity(k),T_mat) R_mat = np.zeros((p+k,1)) R_mat[k] = 1 | R_mat = np.zeros((p,1)) R_mat[0] = 1 | def predict(self, n=0): """ If n == 0, returns fitted values. |
if k==1: alpha[0] = params[0] predictedvalues[0] = alpha[0] Q_0 = dot(inv(identity((p+k)**2)-kron(T_mat,T_mat)),dot(R_mat, | if k==1: y -= dot(self.exog, params[:k]) Q_0 = dot(inv(identity(p**2)-kron(T_mat,T_mat)),dot(R_mat, | def predict(self, n=0): """ If n == 0, returns fitted values. |
rvsb = stats.beta.rvs(5,15,size=200) | rvsb = stats.beta.rvs(10,15,size=2000) print 'true params', 10, 15, 0, 1 | def fit_mps(dist, data, x0=None): '''Estimate distribution parameters with Maximum Product-of-Spacings Parameters ---------- params : array_like, tuple ? parameters of the distribution funciton xsorted : array_like data that is already sorted dist : instance of a distribution class only cdf method is used Returns ---... |
print '\n\nExample: Lomax, Pareto, Generalized Pareto Distributions' print '--------------------------------------------------------' | def fit_mps(dist, data, x0=None): '''Estimate distribution parameters with Maximum Product-of-Spacings Parameters ---------- params : array_like, tuple ? parameters of the distribution funciton xsorted : array_like data that is already sorted dist : instance of a distribution class only cdf method is used Returns ---... | |
def fit(self): | def fit(self, start=None): | def fit(self): ''' Estimate the parameters using default settings. |
def fitgmm(self, momcond, args, start, weights=None): | def fitgmm(self, start, weights=None): | def fitgmm(self, momcond, args, start, weights=None): '''estimate parameters using GMM |
if not fixed is None: raise NotImplementedError tmp = momcond(start, *args) nmoms = tmp.shape[-1] | def fitgmm(self, momcond, args, start, weights=None): '''estimate parameters using GMM | |
weights = np.eye(nmoms) | weights = np.eye(self.nmoms) | def fitgmm(self, momcond, args, start, weights=None): '''estimate parameters using GMM |
resgmm = fitgmm(momcond, (), start, weights=winv, fixed=None, weightsoptimal=False) | resgmm = self.fitgmm(start, weights=winv) | def fititer(self, start, maxiter=2, start_weights=None, weights_method='cov', wargs=()): '''iterative estimation with updating of optimal weighting matrix |
dk = zipfile.ZipFile('./DK-data.zip') | dk = zipfile.ZipFile('/home/skipper/statsmodels/DK-data.zip') | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
raise IOError("Install DK-data.zip from http://www.ssfpack.com/DKbook.html") | raise IOError("Install DK-data.zip from http://www.ssfpack.com/DKbook.html or specify its correct local path.") | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
arma = ARMA(y, constant=False, order=(1,1)) | arma = ARMA(y) arma.fit(trend='nc', order=(1,1)) | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
arma22 = ARMA(y_arma22, constant=False, order=(2,2)) arma22.fit() | arma22 = ARMA(y_arma22) arma22.fit(trend = 'nc', order=(2,2)) | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
ar = ARMA(data.endog, constant=False, order=(9,0)) ar.fit() | ar = ARMA(data.endog) ar.fit(trend='nc', order=(9,0)) | def Q(x): cholQ = np.array([[x[1],0],[0,x[2]]]) return np.dot(cholQ,cholQ.T) |
def __init__(self, endog=None, exog=None, panel=None, time=None, xtnames=None, equation=None, panel_data=None): if panel_data == None: | # def __init__(self, endog=None, exog=None, panel_arr=None, time_arr=None, | |
self.initialize(endog, exog, panel, time, xtnames, equation) | # def __init__(self, endog=None, exog=None, panel_arr=None, time_arr=None, | |
def __init__(self, panel_data, endog_name, exog_name=None): if not isinstance(panel_data, (LongPanel, PanelData)): raise ValueError, "Only pandas.LongPanel or PanelData objects are \ supported" if not isinstance(endog_name, str): raise ValueError, "endog_name must be a string containing the name\ of the endogenous vari... | def initialize(self, endog, exog, panel, time, xtnames, equation): """ Initialize plain array model. See PanelModel """ names = equation.split(" ") self.endog_name = names[0] exog_names = names[1:] self.panel_name = xtnames[0] self.time_name = xtnames[1] novar = exog.var(0) == 0 if True in novar: cons_index = np... | def __init__(self, panel_data, endog_name, exog_name=None): if not isinstance(panel_data, (LongPanel, PanelData)): raise ValueError, "Only pandas.LongPanel or PanelData objects are \ |
def fit(self, method=None, effects='oneway', *opts): """ method : LSDV, demeaned, MLE, GLS, BE, FE effects : 'invidividual', 'oneway', or 'twoway' """ method = method.lower() if method not in ["lsdv", "demeaned", "mle", "gls", "be", "fe"]: | def fit(self, model=None, method=None, effects='oneway'): """ method : LSDV, demeaned, MLE, GLS, BE, FE, optional model : BTWNP : Between panels BTWNT : Between time periods FIXONE : One-way fixed effects FIXONETIME : One-way time fixed effects GMM : Dynamic panel estimator POOLED : Pooled RANONE : One-way random effec... | def fit(self, method=None, effects='oneway', *opts): """ method : LSDV, demeaned, MLE, GLS, BE, FE effects : 'invidividual', 'oneway', or 'twoway' """ method = method.lower() if method not in ["lsdv", "demeaned", "mle", "gls", "be", "fe"]: raise ValueError, "%s not a valid method" % method if method == "lsdv": self.fit... |
if method == "lsdv": self.fit_lsdv(opts) def fit_lsdv(self, errors='oneway'): """ Fit using least squares dummy variables. Notes ----- Should only be used for small `nobs`. """ pdummies = None tdummies = None class OneWayError(PanelModel): pass class TwoWayError(PanelModel): pass | if model == 'pooled': return GLS(self.endog, self.exog).fit() if model == 'between': return self._fit_btwn(method, effects) if model == 'fixed': return self._fit_fixed(method, effects) def _fit_btwn(self, method, effects): endog = self._group_mean(self.endog, index=effects) exog = self._group_mean(self.ex... | def fit(self, method=None, effects='oneway', *opts): """ method : LSDV, demeaned, MLE, GLS, BE, FE effects : 'invidividual', 'oneway', or 'twoway' """ method = method.lower() if method not in ["lsdv", "demeaned", "mle", "gls", "be", "fe"]: raise ValueError, "%s not a valid method" % method if method == "lsdv": self.fit... |
exog = data.exog[:-20] arrpanel = nprf.append_fields(exog, 'investment', endog, float, | fullexog = data.exog[:-20] panel_arr = nprf.append_fields(fullexog, 'investment', endog, float, | def fit_lsdv(self, errors='oneway'): """ Fit using least squares dummy variables. |
panel = LongPanel.fromRecords(arrpanel, major_field='year', | panel_panda = LongPanel.fromRecords(panel_arr, major_field='year', | def fit_lsdv(self, errors='oneway'): """ Fit using least squares dummy variables. |
panel_mod_oneway = OneWayError(panel, endog_name='investment') | exog = fullexog[['value','capital']].view(float).reshape(-1,2) exog = sm.add_constant(exog) panel = group(fullexog['firm']) year = fullexog['year'] panel_mod = PanelModel(endog, exog, panel, year, xtnames=['firm','year'], equation='invest value capital') panel_ols = panel_mod.fit(model='pooled') panel_be = panel_mod.f... | def fit_lsdv(self, errors='oneway'): """ Fit using least squares dummy variables. |
nobs = len(np.array(f0)) | nobs = len(np.atleast_1d(f0)) | def approx_fprime1(xk, f, epsilon=1e-12, args=()): ''' Gradient of function, or Jacobian if function f returns 1d array Parameters ---------- xk : array parameters at which the derivative is evaluated f : function `*((xk,)+args)` returning either one value or 1d array epsilon : float stepsize, TODO add default *args :... |
return grad | return np.squeeze(grad) | def approx_fprime1(xk, f, epsilon=1e-12, args=()): ''' Gradient of function, or Jacobian if function f returns 1d array Parameters ---------- xk : array parameters at which the derivative is evaluated f : function `*((xk,)+args)` returning either one value or 1d array epsilon : float stepsize, TODO add default *args :... |
return [], tree, [] | return [], [tree], [] | def getnodes(tree): ''' walk tree to get list of branches and list of leaves Parameters ---------- tree : list of tuples tree as defined for RU2NMNL Returns ------- branch : list list of all branch names leaves : list list of all leaves names ''' if type(tree) == tuple: name, subtree = tree ab = [name] al = [] #dege... |
print '----------- starting next branch-----------' print name, datadict[name], 'tau=', tau print 'subtree', subtree | if DEBUG: print '----------- starting next branch-----------' print name, datadict[name], 'tau=', tau print 'subtree', subtree | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print b | if DEBUG: print b | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print '----------- returning to branch-----------', print name print 'branchsum in branch', name, branchsum | if DEBUG: print '----------- returning to branch-----------', print name print 'branchsum in branch', name, branchsum | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print 'parent', parent | if DEBUG: print 'parent', parent | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print 'self.datadict[name], self.probs[k]', print self.datadict[name], self.probs[k] | if DEBUG: print 'self.datadict[name], self.probs[k]', print self.datadict[name], self.probs[k] | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print 'repr(b)', repr(b), bidx | if DEBUG: print 'repr(b)', repr(b), bidx | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print '*********** branchsum at bottom branch', branchsum | if DEBUG: print '*********** branchsum at bottom branch', branchsum | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print 'branchprob', bname, k, bprob, branchsum | if DEBUG: print 'branchprob', bname, k, bprob, branchsum | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print 'working on branch', tree, branchsum | if DEBUG: print 'working on branch', tree, branchsum | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
print 'final branch with', tree, ''.join(tree), leavessum | if DEBUG: print 'final branch with', tree, ''.join(tree), leavessum | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
endog = 5 tree0 = ('top', [('Fly',['Air']), ('Ground', ['Train', 'Car', 'Bus']) ] ) ''' this is with real data from Greene's clogit example datadict = dict(zip(['Air', 'Train', 'Bus', 'Car'], [xifloat[i]for i in range(4)])) ''' datadict = dict(zip(['Air', 'Train', 'Bus', 'Car'], ['Airdata', 'Traindata', 'Bus... | if __name__ == '__main__': DEBUG = 0 endog = 5 tree0 = ('top', [('Fly',['Air']), ('Ground', ['Train', 'Car', 'Bus']) ] ) ''' this is with real data from Greene's clogit example | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
np.arange(4))) datadict.update({'top' : [], | [xifloat[i]for i in range(4)])) ''' datadict = dict(zip(['Air', 'Train', 'Bus', 'Car'], ['Airdata', 'Traindata', 'Busdata', 'Cardata'])) if testxb: datadict = dict(zip(['Air', 'Train', 'Bus', 'Car'], np.arange(4))) datadict.update({'top' : [], 'Fly' : [], 'Ground': []}) paramsind = {'top' : [], | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
'Ground': []}) paramsind = {'top' : [], 'Fly' : [], 'Ground': [], 'Air' : ['GC', 'Ttme', 'ConstA', 'Hinc'], 'Train' : ['GC', 'Ttme', 'ConstT'], 'Bus' : ['GC', 'Ttme', 'ConstB'], 'Car' : ['GC', 'Ttme'] } modru = RU2NMNL(endog, datadict, tree0, paramsind) modru.recursionparams[-1] = 2 modru.recursionparams[1]... | 'Ground': [], 'Air' : ['GC', 'Ttme', 'ConstA', 'Hinc'], 'Train' : ['GC', 'Ttme', 'ConstT'], 'Bus' : ['GC', 'Ttme', 'ConstB'], 'Car' : ['GC', 'Ttme'] } modru = RU2NMNL(endog, datadict, tree0, paramsind) modru.recursionparams[-1] = 2 modru.recursionparams[1] = 1 print 'Example 1' print '---------\n' print modru.c... | def calc_prob(self, tree, parent=None): '''walking a tree bottom-up based on dictionary ''' |
keepidx = ~np.isnany(Y) | keepidx = ~np.isnan(Y) | def drop_missing(Y,X=None, axis=1): """ Returns views on the arrays Y and X where missing observations are dropped. Y : array-like X : array-like, optional axis : int Axis along which to look for missing observations. Default is 1, ie., observations in rows. Returns ------- Y : array All Y where the X : array Notes... |
h = miso_lfilter(ar, ma, etax, useic=self._icetax))[0] | h = miso_lfilter(ar, ma, etax, useic=self._icetax)[0] | def geth(self, params): ''' |
fhd = StataReader(open(fname, 'r'), missing_values=False) | fhd = StataReader(open(fname, 'rb'), missing_values=False) | def genfromdta(fname, excludelist=None, missing_flt=-999., missing_str=""): """ Returns an ndarray from a Stata .dta file. Parameters ---------- fname missing_values excludelist missing_flt missing_str Notes ------ If the parser encounters a format that it doesn't understand, then it will convert to string. This may... |
if names: fh.write(delimiter.join(names) + '\n') | def savetxt(fname, X, names=None, fmt='%.18e', delimiter=' '): """ Save an array to a text file. This is just a copy of numpy.savetxt patched to support structured arrays or a header of names. Does not include py3 support now in savetxt. Parameters ---------- fname : filename or file handle If the filename ends in `... | |
fmt = default_fmts[output_format].copy() | fmt = self.output_formats[output_format].copy() | def _get_fmt(self, output_format, **fmt_dict): """Return dict, the formatting options. """ #first get the default formatting try: fmt = default_fmts[output_format].copy() except KeyError: raise ValueError('Unknown format: %s' % output_format) #second get table specific formatting (if possible) try: fmt.update(self.tabl... |
try: fmt.update(self.table.output_formats[output_format]) except AttributeError: pass | def _get_fmt(self, output_format, **fmt_dict): """Return dict, the formatting options. """ #first get the default formatting try: fmt = default_fmts[output_format].copy() except KeyError: raise ValueError('Unknown format: %s' % output_format) #second get table specific formatting (if possible) try: fmt.update(self.tabl... | |
data_fmts = ["%s"], data_fmt = "%s", | data_fmts = ['%s'], data_fmt = '%s', | def format(self, width, output_format='txt', **fmt_dict): """Return string. This is the default formatter for cells. Override this to get different formating. A cell formatter must accept as arguments a cell (self) and an output format, one of ('html', 'txt', 'csv', 'latex'). It will generally respond to the datatype, ... |
data_aligns = "c", stubs_align = "l", | data_aligns = 'c', stubs_align = 'l', | def format(self, width, output_format='txt', **fmt_dict): """Return string. This is the default formatter for cells. Override this to get different formating. A cell formatter must accept as arguments a cell (self) and an output format, one of ('html', 'txt', 'csv', 'latex'). It will generally respond to the datatype, ... |
errors = [0] * q | errors = [0] * p | def loglike_css(self, params): """ Conditional Sum of Squares likelihood function. """ p = self.p q = self.q k = self.k y = self.endog.copy() nobs = self.nobs # how to handle if empty? if self.transparams: newparams = self._transparams(params) else: newparams = params if k > 0: |
.. math:: \\left[\\frac{T+Kp+t}{T-Kp-t}\\right]^{K}$$\\left|\\Omega\\right| | .. math:: \\left[\\frac{T+Kp+t}{T-Kp-t}\\right]^{K}\\left|\\Omega\\right| | def fit(self, method="ols", structural=None, dfk=None, maxlag=None, ic=None, trend="c"): """ Fit the VAR model |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.