Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from statsmodels.compat.python import lrange 

2import numpy as np 

3import statsmodels.tsa.vector_ar.util as util 

4 

5 

6class MPLConfigurator(object): 

7 

8 def __init__(self): 

9 self._inverse_actions = [] 

10 

11 def revert(self): 

12 for action in self._inverse_actions: 

13 action() 

14 

15 def set_fontsize(self, size): 

16 import matplotlib as mpl 

17 old_size = mpl.rcParams['font.size'] 

18 mpl.rcParams['font.size'] = size 

19 

20 def revert(): 

21 mpl.rcParams['font.size'] = old_size 

22 

23 self._inverse_actions.append(revert) 

24 

25 

26#------------------------------------------------------------------------------- 

27# Plotting functions 

28 

29def plot_mts(Y, names=None, index=None): 

30 """ 

31 Plot multiple time series 

32 """ 

33 import matplotlib.pyplot as plt 

34 

35 k = Y.shape[1] 

36 rows, cols = k, 1 

37 

38 fig = plt.figure(figsize=(10, 10)) 

39 

40 for j in range(k): 

41 ts = Y[:, j] 

42 

43 ax = fig.add_subplot(rows, cols, j+1) 

44 if index is not None: 

45 ax.plot(index, ts) 

46 else: 

47 ax.plot(ts) 

48 

49 if names is not None: 

50 ax.set_title(names[j]) 

51 

52 return fig 

53 

54 

55def plot_var_forc(prior, forc, err_upper, err_lower, 

56 index=None, names=None, plot_stderr=True, 

57 legend_options=None): 

58 import matplotlib.pyplot as plt 

59 

60 n, k = prior.shape 

61 rows, cols = k, 1 

62 

63 fig = plt.figure(figsize=(10, 10)) 

64 

65 prange = np.arange(n) 

66 rng_f = np.arange(n - 1, n + len(forc)) 

67 rng_err = np.arange(n, n + len(forc)) 

68 

69 for j in range(k): 

70 ax = plt.subplot(rows, cols, j+1) 

71 

72 p1 = ax.plot(prange, prior[:, j], 'k', label='Observed') 

73 p2 = ax.plot(rng_f, np.r_[prior[-1:, j], forc[:, j]], 'k--', 

74 label='Forecast') 

75 

76 if plot_stderr: 

77 p3 = ax.plot(rng_err, err_upper[:, j], 'k-.', 

78 label='Forc 2 STD err') 

79 ax.plot(rng_err, err_lower[:, j], 'k-.') 

80 

81 if names is not None: 

82 ax.set_title(names[j]) 

83 

84 if legend_options is None: 

85 legend_options = {"loc": "upper right"} 

86 ax.legend(**legend_options) 

87 return fig 

88 

89 

90def plot_with_error(y, error, x=None, axes=None, value_fmt='k', 

91 error_fmt='k--', alpha=0.05, stderr_type = 'asym'): 

92 """ 

93 Make plot with optional error bars 

94 

95 Parameters 

96 ---------- 

97 y : 

98 error : array or None 

99 """ 

100 import matplotlib.pyplot as plt 

101 

102 if axes is None: 

103 axes = plt.gca() 

104 

105 x = x if x is not None else lrange(len(y)) 

106 plot_action = lambda y, fmt: axes.plot(x, y, fmt) 

107 plot_action(y, value_fmt) 

108 

109 #changed this 

110 if error is not None: 

111 if stderr_type == 'asym': 

112 q = util.norm_signif_level(alpha) 

113 plot_action(y - q * error, error_fmt) 

114 plot_action(y + q * error, error_fmt) 

115 if stderr_type in ('mc','sz1','sz2','sz3'): 

116 plot_action(error[0], error_fmt) 

117 plot_action(error[1], error_fmt) 

118 

119 

120def plot_full_acorr(acorr, fontsize=8, linewidth=8, xlabel=None, 

121 err_bound=None): 

122 """ 

123 

124 Parameters 

125 ---------- 

126 """ 

127 import matplotlib.pyplot as plt 

128 

129 config = MPLConfigurator() 

130 config.set_fontsize(fontsize) 

131 

132 k = acorr.shape[1] 

133 fig, axes = plt.subplots(k, k, figsize=(10, 10), squeeze=False) 

134 

135 for i in range(k): 

136 for j in range(k): 

137 ax = axes[i][j] 

138 acorr_plot(acorr[:, i, j], linewidth=linewidth, 

139 xlabel=xlabel, ax=ax) 

140 

141 if err_bound is not None: 

142 ax.axhline(err_bound, color='k', linestyle='--') 

143 ax.axhline(-err_bound, color='k', linestyle='--') 

144 

145 adjust_subplots() 

146 config.revert() 

147 

148 return fig 

149 

150 

151def acorr_plot(acorr, linewidth=8, xlabel=None, ax=None): 

152 import matplotlib.pyplot as plt 

153 

154 if ax is None: 

155 ax = plt.gca() 

156 

157 if xlabel is None: 

158 xlabel = np.arange(len(acorr)) 

159 

160 ax.vlines(xlabel, [0], acorr, lw=linewidth) 

161 

162 ax.axhline(0, color='k') 

163 ax.set_ylim([-1, 1]) 

164 

165 # hack? 

166 ax.set_xlim([-1, xlabel[-1] + 1]) 

167 

168 

169def plot_acorr_with_error(): 

170 raise NotImplementedError 

171 

172 

173def adjust_subplots(**kwds): 

174 import matplotlib.pyplot as plt 

175 

176 passed_kwds = dict(bottom=0.05, top=0.925, 

177 left=0.05, right=0.95, 

178 hspace=0.2) 

179 passed_kwds.update(kwds) 

180 plt.subplots_adjust(**passed_kwds) 

181 

182 

183#------------------------------------------------------------------------------- 

184# Multiple impulse response (cum_effects, etc.) cplots 

185 

186def irf_grid_plot(values, stderr, impcol, rescol, names, title, 

187 signif=0.05, hlines=None, subplot_params=None, 

188 plot_params=None, figsize=(10,10), stderr_type='asym'): 

189 """ 

190 Reusable function to make flexible grid plots of impulse responses and 

191 comulative effects 

192 

193 values : (T + 1) x k x k 

194 stderr : T x k x k 

195 hlines : k x k 

196 """ 

197 import matplotlib.pyplot as plt 

198 

199 if subplot_params is None: 

200 subplot_params = {} 

201 if plot_params is None: 

202 plot_params = {} 

203 

204 nrows, ncols, to_plot = _get_irf_plot_config(names, impcol, rescol) 

205 

206 fig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, 

207 squeeze=False, figsize=figsize) 

208 

209 # fill out space 

210 adjust_subplots() 

211 

212 fig.suptitle(title, fontsize=14) 

213 

214 subtitle_temp = r'%s$\rightarrow$%s' 

215 

216 k = len(names) 

217 

218 rng = lrange(len(values)) 

219 for (j, i, ai, aj) in to_plot: 

220 ax = axes[ai][aj] 

221 

222 # HACK? 

223 if stderr is not None: 

224 if stderr_type == 'asym': 

225 sig = np.sqrt(stderr[:, j * k + i, j * k + i]) 

226 plot_with_error(values[:, i, j], sig, x=rng, axes=ax, 

227 alpha=signif, value_fmt='b', stderr_type=stderr_type) 

228 if stderr_type in ('mc','sz1','sz2','sz3'): 

229 errs = stderr[0][:, i, j], stderr[1][:, i, j] 

230 plot_with_error(values[:, i, j], errs, x=rng, axes=ax, 

231 alpha=signif, value_fmt='b', stderr_type=stderr_type) 

232 else: 

233 plot_with_error(values[:, i, j], None, x=rng, axes=ax, 

234 value_fmt='b') 

235 

236 ax.axhline(0, color='k') 

237 

238 if hlines is not None: 

239 ax.axhline(hlines[i,j], color='k') 

240 

241 sz = subplot_params.get('fontsize', 12) 

242 ax.set_title(subtitle_temp % (names[j], names[i]), fontsize=sz) 

243 

244 return fig 

245 

246 

247def _get_irf_plot_config(names, impcol, rescol): 

248 nrows = ncols = k = len(names) 

249 if impcol is not None and rescol is not None: 

250 # plot one impulse-response pair 

251 nrows = ncols = 1 

252 j = util.get_index(names, impcol) 

253 i = util.get_index(names, rescol) 

254 to_plot = [(j, i, 0, 0)] 

255 elif impcol is not None: 

256 # plot impacts of impulse in one variable 

257 ncols = 1 

258 j = util.get_index(names, impcol) 

259 to_plot = [(j, i, i, 0) for i in range(k)] 

260 elif rescol is not None: 

261 # plot only things having impact on particular variable 

262 ncols = 1 

263 i = util.get_index(names, rescol) 

264 to_plot = [(j, i, j, 0) for j in range(k)] 

265 else: 

266 # plot everything 

267 to_plot = [(j, i, i, j) for i in range(k) for j in range(k)] 

268 

269 return nrows, ncols, to_plot 

270 

271#------------------------------------------------------------------------------- 

272# Forecast error variance decomposition