def plot_extreme_value_distribution(extremes, fitted_params=None, bins=50, ax=None): """ Plots the fitted extreme value distribution probability density function overlayed over a histogram of the empircal extreme values. Parameters: extremes : array_like Extreme values. fitted_params : tuple of floats parameters corresponding to the fitted distribution. bins : int Number of bins to use in histogram ax : matplotlib.axes.Axes Plotting axis. kwargs : (optional) Additional keyword arguments to pass to matplotlib. Returns: ax : matplotlib.axes.Axes Plotting axis. """ if ax is None: fig, ax = plt.subplots() if fitted_params is None: fitted_params = fit_distribution(extremes, fix_loc=True) # Plot histogram of extreme values ax.hist(extremes, bins=bins, density=True, label='Extreme values') # Plot MLE pdf quantiles = np.linspace( genpareto.ppf(0.01, *fitted_params), genpareto.ppf(0.99, *fitted_params), 99 ) fitted_pdf = genpareto.pdf(quantiles, *fitted_params) ax.plot(quantiles, fitted_pdf, label='Fitted GPD pdf') ax.set( title='Best fit generalized Pareto distribution to extremes', xlabel='Extreme values [m]', ylabel='Density' ) ax.legend(loc='upper right') return ax
def ppf_evt(x, ul, ur, tparams, gpdparams): ''' :param x: the value of the cdf :param ul: left-tail threshold :param ur: right-tail threshold :param tparams: parameters for the location-scale t distribution :param gpdparams: parameters for the generalized Pareto distribution :return: ''' if x >= ur: return genpareto.ppf(x, c = gpdparams[0], loc = gpdparams[2], scale = gpdparams[1]) elif x <= ul: return genpareto.ppf(x, c = gpdparams[3], loc = gpdparams[5], scale = gpdparams[4]) else: return t.ppf(x, df = tparams[2], loc = tparams[0], scale = tparams[1])
def magnitudes_resamples(self, quantity): dic_magns = {0.001: list(), 0.01: list(), 0.1: list(), 0.5: list(), 0.9: list(), 0.99: list(), 0.999: list() } for i in range(quantity): fit = self.fit_resample() for j in dic_magns: mag = genpareto.ppf(j, fit[0], fit[1], fit[2]) dic_magns[j].append(mag) return pd.DataFrame(dic_magns)
def GeneralizedPareto_ICDF(x, p): ''' Generalized Pareto fit Returns inverse cumulative probability function at p points ''' # fit a generalized pareto and get params shape, _, scale = genpareto.fit(x) # get percent points (inverse of CDF) icdf = genpareto.ppf(p, shape, scale=scale) return icdf
def getprob(): print("Probability: %s" % entryy1.get()) print("a Probability of: %s corresponds with a Return Period of %s") % ( (entryy1.get()), min(rplist) * (1 - float(entryy1.get()))**-1) problist.append(float(entryy1.get())) mentry.delete(0, 'end') mentry.insert(10, str(min(rplist) * (1 - float(entryy1.get()))**-1)) print 'Force = ' + str( genparetoquantile(1 - problist[len(problist) - 1], Threshold, Maxsigma, Maxxis)) print 'Force = ' + str( genpareto.ppf( problist[len(problist) - 1], Maxxis, loc=Threshold, scale=Maxsigma)) print '\n'
def EstimaMagnitudes(self, Parametros): Quantis = [] TRs = [1.000111,2,5,10,20,50] for TR in TRs: if self.tipoSerie == 'Parcial': Quantil = genpareto.ppf(1-(1/TR), Parametros[0], loc = Parametros[1], scale = Parametros[2]) Quantis.append(Quantil) print('Tempo de Retorno: %i '%TR) print('PARETO=> Magnitude: %.2f'%(Quantil)) elif self.tipoSerie == 'Anual': Quantil = genextreme.ppf(1-(1/TR), Parametros[0], loc = Parametros[1], scale = Parametros[2]) Quantis.append(Quantil) print('Tempo de Retorno: %i '%TR) print('GEV=> Magnitude: %.2f' % (Quantil)) return Quantis
def __init__(self, initial_wealth=25.0, edge_prior_alpha=7, edge_prior_beta=3, max_wealth_alpha=5.0, max_wealth_m=200.0, max_rounds_mean=300.0, max_rounds_sd=25.0, reseed=True, clip_distributions=False): # clip_distributions=True asserts that state and action space are not modified at reset() # store the hyper-parameters for passing back into __init__() during resets so # the same hyper-parameters govern the next game's parameters, as the user # expects: # TODO: this is boilerplate, is there any more elegant way to do this? self.initial_wealth = float(initial_wealth) self.edge_prior_alpha = edge_prior_alpha self.edge_prior_beta = edge_prior_beta self.max_wealth_alpha = max_wealth_alpha self.max_wealth_m = max_wealth_m self.max_rounds_mean = max_rounds_mean self.max_rounds_sd = max_rounds_sd self.clip_distributions = clip_distributions if reseed or not hasattr(self, 'np_random'): self.seed() # draw this game's set of parameters: edge = self.np_random.beta(edge_prior_alpha, edge_prior_beta) if self.clip_distributions: # (clip/resample some parameters to be able to fix obs/action space sizes/bounds) max_wealth_bound = round( genpareto.ppf(0.85, max_wealth_alpha, max_wealth_m)) max_wealth = max_wealth_bound + 1.0 while max_wealth > max_wealth_bound: max_wealth = round( genpareto.rvs(max_wealth_alpha, max_wealth_m, random_state=self.np_random)) max_rounds_bound = int( round(norm.ppf(0.99, max_rounds_mean, max_rounds_sd))) max_rounds = max_rounds_bound + 1 while max_rounds > max_rounds_bound: max_rounds = int( round(self.np_random.normal(max_rounds_mean, max_rounds_sd))) else: max_wealth = round( genpareto.rvs(max_wealth_alpha, max_wealth_m, random_state=self.np_random)) max_wealth_bound = max_wealth max_rounds = int( round(self.np_random.normal(max_rounds_mean, max_rounds_sd))) max_rounds_bound = max_rounds # add an additional global variable which is the sufficient statistic for the # Pareto distribution on wealth cap; alpha doesn't update, but x_m does, and # simply is the highest wealth count we've seen to date: self.max_ever_wealth = float(self.initial_wealth) # for the coinflip edge, it is total wins/losses: self.wins = 0 self.losses = 0 # for the number of rounds, we need to remember how many rounds we've played: self.rounds_elapsed = 0 # the rest proceeds as before: self.action_space = spaces.Discrete(int(max_wealth_bound * 100)) self.observation_space = spaces.Tuple(( spaces.Box(0, max_wealth_bound, shape=[1], dtype=np.float32), # current wealth spaces.Discrete(max_rounds_bound + 1), # rounds elapsed spaces.Discrete(max_rounds_bound + 1), # wins spaces.Discrete(max_rounds_bound + 1), # losses spaces.Box(0, max_wealth_bound, [1], dtype=np.float32))) # maximum observed wealth self.reward_range = (0, max_wealth) self.edge = edge self.wealth = self.initial_wealth self.max_rounds = max_rounds self.rounds = self.max_rounds self.max_wealth = max_wealth
import numpy as np from scipy.stats import genpareto import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) c = 0.1 mean, var, skew, kurt = genpareto.stats(c, moments='mvsk') x = np.linspace(genpareto.ppf(0.01, c), genpareto.ppf(0.99, c), 100) ax.plot(x, genpareto.pdf(x, c), 'r-', lw=5, alpha=0.6, label='genpareto pdf') rv = genpareto(c) ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') vals = genpareto.ppf([0.001, 0.5, 0.999], c) np.allclose([0.001, 0.5, 0.999], genpareto.cdf(vals, c)) r = genpareto.rvs(c, size=1000) ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2) ax.legend(loc='best', frameon=False) plt.show()
for i in range(1, len(yvalues['y' + str(threshposition)]) + 1) ] listofpercentsinverse = [ 1 - float(i) / (len(yvalues['y' + str(threshposition)]) + 1) for i in range(1, len(yvalues['y' + str(threshposition)]) + 1) ] #line1 = [x+Threshold for x in range(100000)] line1 = [Threshold, 100000000 + Threshold] quantilelist = [ genparetoquantile(percent, Threshold, Maxsigma, Maxxis) for percent in listofpercentsinverse ] quantilelist2 = [ genpareto.ppf(percent, Maxxis, loc=Threshold, scale=Maxsigma) for percent in listofpercents ] #User Input Axis for Quantile Plot print 'Input a plot range for the Quantile Plot' print 'Click "Display Plot" for various ranges if desired' print 'Click "Continue" when satisfied with your plot' print '\n' quantileaxisrange = [] quantileroot = tk.Tk() print 'If the graph pops up in a new window you must close out of the graph before displaying a new plot or continuing on with the program.' print '\n' def plot_quantile():
import numpy as np from scipy.stats import genpareto import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) c = 0.1 mean, var, skew, kurt = genpareto.stats(c, moments='mvsk') x = np.linspace(genpareto.ppf(0.01, c),genpareto.ppf(0.99, c), 100) ax.plot(x, genpareto.pdf(x, c),'r-', lw=5, alpha=0.6, label='genpareto pdf') rv = genpareto(c) ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') vals = genpareto.ppf([0.001, 0.5, 0.999], c) np.allclose([0.001, 0.5, 0.999], genpareto.cdf(vals, c)) r = genpareto.rvs(c, size=1000) ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2) ax.legend(loc='best', frameon=False) plt.show()