def __init__(self , spot=100 , strike=99 , interest_rate=0.06 , volatility=0.2 , variance=None , tenor=1.0 , mean_reversion=1 , mean_variance=None , vol_of_variance=None , correlation=0): Option.__init__(self , spot=spot , strike=strike , interest_rate=interest_rate , variance=variance , volatility=volatility , tenor=tenor ) self.Type = "HestonOption" self.attrs += ['correlation'] self.variance.reversion = mean_reversion if mean_variance is not None: self.variance.mean = mean_variance else: self.variance.mean = self.variance.value if vol_of_variance is None: vol_of_variance = 0.4 self.variance.volatility = vol_of_variance self.correlation = correlation
def choosePair(self, bases_hand, styles_hand, action_name="play"): """ Choose a Pair consisting of a Base and Style from all cards in hand. Parameters: bases_hand (list of Card):Bases in hand (not the same as self.bases, as clashes happen). styles_hand (list of Card):Styles in hand. action_name (str):String containing user information to be shown if applicable in its strategy. Returns: Pair (Pair):The chosen Pair consisting of a Base and Style. """ base_options = {} for i, base in enumerate(bases_hand): base_options[i + 1] = Option(name=action_name, user_info=base.name, params=i) style_options = {} for i, style in enumerate(styles_hand): style_options[i + 1] = Option(name=action_name, user_info=style.name, params=i) chosen_option = self.strategy.chooseOption( base_options, header="Choose a base to {}".format(action_name)) chosen_base = base_options[chosen_option].params chosen_option = self.strategy.chooseOption( style_options, header="Choose a style to {}".format(action_name)) chosen_style = style_options[chosen_option].params return Pair(bases_hand[chosen_base], styles_hand[chosen_style])
def __init__(self, newView, newRecordColl=None): super(Controller, self).__init__() if not isinstance(newView, AbstractView): raise ViewException() self.prompt = "ERP " self._myView = newView self._options = {} self._options["AUTOID"] = Option( "Auto ID", "If an invalid or \ duplicate ID is specified when adding a record, that record is assigned \ an ID automatically (a blank ID is invalid)", "No automatic IDs will be \ used when adding records") self._options["OVERWRITE"] = Option( "Overwrite", "If a duplicate \ ID is specified when adding a record, the original record with the same \ ID is removed (this overpowers auto ID)", "No records will be removed \ when adding records") if (newRecordColl is not None and isinstance(newRecordColl, RecordCollection)): self._theColl = newRecordColl else: self._theColl = RecordCollection() self._selectedRecord = None self._selectedOption = None self._myView.show("EMPLOYEE RECORD PROGRAM - ")
def bonusAttack(self, players, active_player, my_pair, opp_pair, chosen_option=None): """Either returns the possibilities (Spend Time/Don't.) as options ([Option]), or applies the chosen_option and increments damage accordingly. """ luc = players[active_player] if chosen_option is None: if luc.time_tokens >= 3: options = [] options.append( Option(name=self.name, user_info="Do not spend Time Tokens.", params=0, function=self.bonusAttack)) options.append( Option( name=self.name, user_info= "Spend 3 Time Tokens to gain a bonus to Power equal to your printed Power.", params=1, function=self.bonusAttack)) return options return None else: if chosen_option == 1: luc.time_tokens -= 3 my_pair.attack += my_pair.base.attack
def startAdvance(self, players, active_player, my_pair, opp_pair, chosen_option=None): """Either returns the possible advances as options ([Option]), or applies the chosen_option and advances.""" p1 = players[active_player] if chosen_option is None: possible_moves = p1.getPossibleMoves([1, 2], players, active_player) if len(possible_moves) > 0: options = [] options.append( Option(name=self.name, user_info="Do not Advance.", params=0, function=self.startAdvance)) for move in possible_moves: options.append( Option(name=self.name, user_info="Advance {}".format(move), params=move, function=self.startAdvance)) return options return None else: if chosen_option != 0: p1.moveCharacter(chosen_option, players, active_player)
def dequeue(self): #complexity O(1) if self.size is 0: raise Exception("BufferUnderFlow") self.x = Option(self.container[self.begin]) self.size -= 1 self.begin += 1 return self.x
def delete(self, el): #complexity O(1) x = Option() if self.contains(el): x.setEl(el) self.__vector[el] = False return x print("Element is not in the set", el) return x
def __init__(self, spot=100, strike=99, interest_rate=0.06, volatility=0.2, variance=None, tenor=1.0): Option.__init__(self, spot, strike, interest_rate, volatility, variance, tenor)
def pop(self): #pops the first elment if possile #complexity O(1) x = Option() if self.__elements.emptyList(): raise Exception("Stack is Empty") #raises exception if list is empty else: x.setEl(self.__elements.getEl(0)); self.__elements.deletFirst() #deletes the First element if possible return x
def __init__(self , spot=100 , strike=99 , interest_rate=0.06 , volatility=0.2 , variance=None , tenor=1.0 ): Option.__init__(self, spot, strike, interest_rate, volatility, variance, tenor)
def get_raws( self, key: Key, metrics: List[MetricType] ) -> Option[Dict[MetricType, List[float]]]: result_map: Dict[MetricType, List[float]] = {} for metric in metrics: new_key = Key(key.benchmark, key.paradigm, key.language, metric) opt_res = self.get_result(new_key) if opt_res.has_value: result_map[metric] = opt_res.get().results if len(result_map.keys()) == len(metrics): return Option(result_map) else: return Option.empty()
def delete(self, n): #complexity O(n) x = Option() while self.__iter.hasNext(): if n is self.__iter.iter.getHead(): self.__iter.iter.deletFirst( ) #delets the element from the list self.__iter.init() x.setEl(n) return x self.__iter.Next() print("Element is not in the set", n) return x
def show_options(): Option.show_options(_options) optionNum = int(input("Choose option: ")) if 1 <= optionNum <= len(_options): _options[optionNum - 1].fun() else: clearScr() print("Error!!") print("Enter the number of an option.") show_options()
def onHitSoak(self, players, active_player, my_pair, opp_pair, chosen_option=None): """Either returns the possible soaks as options ([Option]), or applies the chosen_option and soaks.""" luc = players[active_player] if chosen_option is None: if luc.time_tokens > 0: options = [] options.append(Option(name=self.name, user_info="Do not spend Time Tokens.", params=0, function=self.onHitSoak)) for i in range(1, min(luc.time_tokens+1, opp_pair.attack)): options.append(Option(name=self.name, user_info="Spend {} Time Tokens for Soak {}.".format(i, i), params=i, function=self.onHitSoak)) return options return None else: luc.time_tokens -= chosen_option my_pair.soak += chosen_option
def gainForce(self, players, active_player, my_pair, opp_pair, chosen_option=None): """ Increments players' force at the end of turn. Parameters: players (list):list containing [player1, player2]. active_player (int):0 or 1, resembling which entry in players is gaining Force. my_pair (Pair):active_player's played Pair. opp_pair (Pair):other player's played Pair. chosen_option (int):Integer reflecting the updated force of this character. """ if chosen_option is None: return [ Option(name=self.name, user_info="Gain Force.", params=0, function=self.gainForce) ] else: force_to_gain = 2 if self.health <= 7 else 1 self.force = min(self.force + force_to_gain, 10)
class MainLoop: option = Option() quit = False userInput = UserInput() commandHandler = CommandHandler() output = Output() execInstrution = ExecInstruction() def __init__(self, option): self.option = option self.start_loop() def start_loop(self): while not self.quit: self.output.load_prompt() try: cmd = self.userInput.read_input() if cmd: self.option.payload = None self.commandHandler.command_handler(cmd, self.option) if self.option.payload: self.execInstrution.run(self.option) except KeyboardInterrupt: self.output.write_message("use " + Color.pink + "\"quit\"" + Color.reset + " to exit")
def add_option(self, option_name, option_value): """ Adds a new option with the given option and value, and return True. If option with that name already exists, the function ignores the call, and returns False. """ return self._add_option(Option(option_name, option_value))
def createOption(page: Page, titre_option: str): """Permet de creer les dossiers et sous dossiers d'une option""" lien_page = 0 titre = page.livre.titre numero_page = page.numero if projetExiste(titre): if pageExiste(titre, numero_page): if not optionExiste(titre, numero_page, titre_option): os.mkdir("livres/" + titre + "/pages/" + str(numero_page) + "/" + titre_option) else: print("Cette option existe deja") return else: print("La page a laquelle vous attachez cette option n'existe pas") return path = "livres/" + titre + "/pages/" + str( numero_page) + "/" + titre_option os.mkdir(path + "/condition") with open(path + "/gain_objet.txt", "w") as f: f.close() with open(path + "/modif_compteur.txt", "w") as f: f.close() Option(titre_option, page, lien_page, "")
class Buffer(Queue): def __init__(self, n): #complexity O(n) because of the creation of the container self.x = Option()#empty option self.capacity = n self.container = [self.x.getEl()]*n #lenght n list self.begin = self.size = 0 def enqueue(self, el): #complexity O(1) if self.size is self.capacity: raise Exception("BufferOverFlow") self.container.insert((self.begin+self.size)%self.capacity,el) self.size += 1 x = Unit() return x def dequeue(self): #complexity O(1) if self.size is 0: raise Exception("BufferUnderFlow") self.x = Option(self.container[self.begin]) self.size -= 1 self.begin += 1 return self.x def iterator(self): #complexity O(1) iter = Buffer_Iterator() iter.copy(self) return iter
def damage(self, players, active_player, my_pair, opp_pair, chosen_option=None): """Either returns dealing 2 damage as Option, or applies the chosen_option and deals 2 damage.""" if chosen_option is None: if players[1 - active_player].position == 0 or players[ 1 - active_player].position == 6: options = [] options.append( Option( name="{} 2".format(self.name), user_info= "If the opponent is at the edge of the board, they lose 2 life.", params=0, function=self.damage)) return options return None else: opp_pos = players[1 - active_player].position if opp_pos == 0 or opp_pos == 6: players[1 - active_player].health = max( players[1 - active_player].health - 2, 1)
def show_calculations(): Option.show_options(_calculations) calcNum = int(input("Choose calculation: ")) clearScr() if 1 <= calcNum < len(_calculations): _calculations[calcNum - 1].fun() print("---------------------------------------") back() elif calcNum == len(_calculations): back() else: print("Error!!") print("Enter the number of a calculation.") show_calculations()
def features(self): s = Option.features(self) s[0] = "HestonOption <%s>" % hex(id(self)) s.extend([ "Mean Reversion: %s" % self.variance.reversion , "Mean Variance: %s" % self.variance.mean , "Vol of Variance: %s" % self.variance.volatility , "Correlation %s" % self.correlation ]) return s
def find_available_rooms(self, date_of_reservation: date, seats: int, start_time: time, duration: time) -> list: start_time = validate_start_time(start_time) duration = validate_duration(duration) self.browser.find_element_by_id( 'ctl00_Main_PageMenu1_BookRoomLink').click() seat_form = Select( self.browser.find_element_by_id('ctl00_Main_Room1_ReqSize')) seat_form.select_by_value(str(seats)) location_select = Select( self.browser.find_element_by_id('ctl00_Main_Room1_ZoneList')) location_select.select_by_visible_text(self.location.name) self.browser.find_element_by_link_text(str( date_of_reservation.day)).click() start_time_select = Select( self.browser.find_element_by_id('startTimeTemp')) start_time_select.select_by_visible_text(format_time(start_time)) duration_select = Select(self.browser.find_element_by_id('durTemp')) duration_select.select_by_visible_text(format_time(duration)) self.browser.implicitly_wait(100) self.browser.find_element_by_id('ctl00_Main_ShowOptionsBtn').click() table = self.browser.find_element_by_id( 'ctl00_Main_OptionSelector_OptionsGrid') rows = table.find_elements_by_class_name('GridItem') rows.extend(table.find_elements_by_class_name('GridAlternateItem')) options = [] for row in rows: time_string = row.find_element_by_class_name( 'OptionTimeColumn').text room = row.find_element_by_class_name( 'OptionLocationNameColumn').text seats = int( row.find_element_by_class_name('OptionCapacityColumn').text) description = row.find_element_by_class_name( 'OptionLocationDescriptionColumn').text radio_button_class_name = row.find_element_by_xpath( "//td[contains(@class, 'OptionSelectColumn')]/input" ).get_attribute('id') option = Option(time_string, room, seats, description, radio_button_class_name=radio_button_class_name) options.append(option) return options
def __init__(self, env_dict, params): """ option_num, state_dim, action_dim, action_bound, gamma, learning_rate, replacement, buffer_capacity, epsilon gamma: (u_gamma, l_gamma) learning_rate: (lr_u_policy, lr_u_critic, lr_option, lr_termin, lr_l_critic) """ # session self.sess = tf.Session() # environment parameters self.sd = env_dict['state_dim'] self.ad = env_dict['action_dim'] a_bound = env_dict['action_scale'] assert a_bound.shape == (self.ad,), 'Action bound does not match action dimension!' # hyper parameters self.on = params['option_num'] epsilon = params['epsilon'] u_gamma = params['upper_gamma'] l_gamma = params['lower_gamma'] u_capac = params['upper_capacity'] l_capac = params['lower_capacity'] u_lrcri = params['upper_learning_rate_critic'] l_lrcri = params['lower_learning_rate_critic'] l_lrpol = params['lower_learning_rate_policy'] l_lrter = params['lower_learning_rate_termin'] # the frequency of training termination function if params['delay'] == 'inf': self.delay = -1 else: self.delay = params['delay'] # Upper critic and buffer self.u_critic = UCritic(session=self.sess, state_dim=self.sd, option_num=self.on, gamma=u_gamma, epsilon=epsilon, learning_rate=u_lrcri) self.u_buffer = Buffer(state_dim=self.sd, action_dim=1, capacity=u_capac) # Lower critic, options and buffer HER self.l_critic = LCritic(session=self.sess, state_dim=self.sd, action_dim=self.ad, gamma=l_gamma, learning_rate=l_lrcri) self.l_options = [Option(session=self.sess, state_dim=self.sd, action_dim=self.ad, ordinal=i, learning_rate=[l_lrpol, l_lrter]) for i in range(self.on)] self.l_buffers = [Buffer(state_dim=self.sd, action_dim=self.ad, capacity=l_capac) for i in range(self.on)] # Initialize all coefficients and saver self.sess.run(tf.global_variables_initializer()) self.saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=100) self.tc = 0 # counter for training termination self.mc = 0 # counter for model
def createOptiontxt(option: Option, texte: str): """Permet d'assigner un texte au paragrphe passé en argument""" page = option.page nom_projet = page.livre.titre numero_page = page.numero titre_para = option.titre path = "livres/" + nom_projet + "/pages/" + str( numero_page) + "/" + titre_para with open(path + "/texte.txt", "w") as fichier: fichier.write(texte) fichier.close() option.texte = texte
def sheetReader(sheet): themes = [] questions = {} qs = [] ptheme = "" for i in range(1, sheet.nrows): row = sheet.row_values(i) opts = [] for i in range(1, 5): if i == 4: op = Option(row[i], True) else: op = Option(row[i], False) opts.append(op) if row[6] not in themes: themes.append(row[6]) if row[6] != ptheme: qs = [] qs.append(Question(row[0], row[5], opts)) questions[row[6]] = qs ptheme = row[6] return [questions, themes]
def top(self): #returns the top element #complexity O(1) x = Option() if self.__elements.emptyList(): x.setOp(False) else: x.setEl(self.__elements.getEl(0)) return x #returns empty option if list is empty
def close(self, players, active_player, my_pair, opp_pair, chosen_option=None): """Either returns the possible closes as options ([Option]), or applies the chosen_option and closes.""" luc = players[active_player] enemy = players[1 - active_player] if chosen_option is None: time_tokens = luc.time_tokens possible_moves = luc.getPossibleMoves([ i + 1 for i in range( min( abs(luc.position - enemy.position) - 1, time_tokens, 3)) ], players, active_player) if len(possible_moves) > 0: options = [] options.append( Option(name=self.name, user_info="Do not advance.", params=0, function=self.close)) for move in possible_moves: options.append( Option(name=self.name, user_info="Spend {} time to advance {}.".format( move, move), params=move, function=self.close)) return options return None else: luc.moveCharacter(to_move=chosen_option, players=players, active_player=active_player) luc.time_tokens -= chosen_option
def getPossibleAntes(self, used_antes): """Creates a list containing all possible antes for the current Luc. Parameters: used_antes (dict):Dictionary containing as keys the name of used antes this beat, and as values True. Returns: possible_antes (list):List containing possible antes as Option. """ possible_antes = super().getDefaultAntes(used_antes) time_surge = LucTimeSurge() time_rush = LucTimeRush() if time_surge.name in used_antes.keys() or time_rush.name in used_antes.keys(): return possible_antes if self.time_tokens >= 1: possible_antes.append(Option(name=time_surge.name, user_info=time_surge.user_info, object=time_surge)) if self.time_tokens >= 3: possible_antes.append(Option(name=time_rush.name, user_info=time_rush.user_info, object=time_rush)) # if self.time_tokens == 5: # time_stop = LucTimeStop() # possible_antes.append(Option(name=time_stop.name, user_info=time_stop.user_info, object=time_stop)) return possible_antes
def showResults(): numSim = int(n.get()) k = float(strike.get()) riskFreeRate = float(r.get()) timeMadurity = float(T.get()) sr = str(source.get()) company = empresa.get() opt = Option(float(k),int(timeMadurity),int(numSim),float(riskFreeRate),company,sr) paths, endValues, priceOff = opt.simulateCall() print(priceOff) f = Figure(figsize=(6,2.8), dpi = 80) a = f.add_subplot(111) for path in paths: a.plot(path) a.set(xlabel = "Iteración", ylabel = "priceOff", title = "Cambio del precio en distintas simulaciones") a.grid() f2 = Figure(figsize=(6,2.8), dpi = 80) b = f2.add_subplot(111) for path in paths: b.hist(endValues, 40) b.set(title = "Histograma precio final") b.grid() ventana.geometry("950x450") canvas = FigureCanvasTkAgg(f, ventana) canvas.show() canvas.get_tk_widget().place(x=350,y=10) canvas2 = FigureCanvasTkAgg(f2, ventana) canvas2.show() canvas2.get_tk_widget().place(x=350,y=210) result = Label(ventana, text= "el valor de la opción es: " + str(priceOff)).place(x=10,y=310)
def __init__(self): super(Program, self).__init__() self.possible_options = [] self.possible_arguments = [] self.unknown_arguments = [] self.options = {} self.arguments = {} self.usage_str = '' self.name_str = '' self.description_str = '' self.allow_unknown_options = False self.help_opt = Option('-h, --help', 'Display this help and usage information.', None, None) self.display_help = self.default_help
def crytolist() : from Option import Option optionList = [] optionList.append(Option(11,"維吉尼亞加密")) optionList.append(Option(12,"維吉尼亞解密")) optionList.append(Option(13,"RSA加密")) optionList.append(Option(14,"RSA解密")) optionList.append(Option(15,"RSA建立金鑰")) optionList.append(Option(16,"線性亂數加解密")) optionList.append(Option(17,"木棒加密")) optionList.append(Option(18,"木棒解密")) print() while(True) : os.system('cls') for Option in optionList: print("[", Option.number-10, "] ", Option.descritpion) print("[", 99, "]", "返回") selection = input("請輸入需要的功能:").strip() os.system('cls') print() if(selection == "2"): cryto.decryp_Vige() elif(selection == "1"): cryto.encryp_Vige() elif(selection == "3"): cryto.rsa_send() elif(selection == "4"): cryto.rsa_read() elif(selection == "5"): cryto.Make_a_rsa() elif(selection == "6"): cryto.linr_radom() elif(selection == "7"): cryto.wood_encry() elif(selection == "8"): cryto.wood_decry() elif(selection == "99"): return else: print("輸入錯誤") input("\n按任意鍵繼續...")
def option(self, flags, description=None, default=None, parse=None): """ Adds an option to the program and initializes the value of the option to the specified default or to `None` """ opt = Option(flags, description, default, parse) self.possible_options.append(opt) if len(opt.arguments) > 0: self.options[opt.name] = {} for arg in opt.arguments: self.options[opt.name][arg.name] = default or None else: self.options[opt.name] = False return self
def __init__(self , Type , S , K , r , Volatility , T , t = 0.0 , DividendYield = 0.0 , c = 1.0): """ - Type: Option Class # 'Call' # 'Put' - c: is the Digital payment. Default = 1.0 - S: is the underlying asset current price - K: is the strike price of the call option - r: is the risk free for the call expiry date - Volatility: is the underlying asset annual standard deviation - T: is the call expiry date expressed in fraction of years - t: is the call evaluation date expressed in fraction of years. Default = 0.0, today - DividendYield: is the underlying asset annual dividend yield. Default = 0.0 """ # initial checks try: Type in ('Call', 'Put') except: ValueError('Option Type not recognized') # initialize base classes self.__Type = Type Option.__init__(self, 'Digital ' + self.__Type + ' Option') # initialize this class if self.__Type == 'Call': self.__I = 1 elif self.__Type == 'Put': self.__I = -1 self.__S = float(S) self.__K = float(K) self.__r = float(r) self.__sigma = float(Volatility) self.__T = float(T) self.__t = float(t) self.__q = float(DividendYield) self.__c = float(c) ## other measures self.__TimeToMaturity = self.__T - self.__t try: self.__sqrtT = sqrt(self.__TimeToMaturity) except: raise ValueError('Square Root with Negative Argument: Time To Maturity is negative') self.__sigmaSqrtT = self.__sigma * self.__sqrtT try: self.__d1 = d1(self.__S , self.__K , self.__TimeToMaturity , self.__r , self.__q , self.__sigma) except: raise ZeroDivisionError('Time To Maturity or Sigma Equal to Zero') self.__d2 = d2(self.__S , self.__K , self.__TimeToMaturity , self.__r , self.__q , self.__sigma) self.__Nd1 = self.__N(self.__d1) self.__Nd2 = self.__N(self.__d2) self.__Phid1 = self.__Phi(self.__d1) self.__Phid2 = self.__Phi(self.__d2) self.__RateDF = self.__MaturityDF(self.__r) self.__DividendYieldDF = self.__MaturityDF(self.__q)
def __init__(self, Type): self.ExerciseStyle = 'European' Option.__init__(self, self.ExerciseStyle + ' ' + Type + ' Option')