def __init__(self, status): Strategy.__init__(self, status) self.bolingerband = 0 self.bol_std = 0 self.bol_mean = 0 self.bol_mean_period = 25
def __init__(self, status): Strategy.__init__(self, status) self.knn_train_period = 100 self.knn_pred_period = 100 self.knn_neighbors = 10 self.predict = 0 self.now = 0 self.beta = 0 self.knn_ts = pd.DataFrame()
def __init__(self, status): Strategy.__init__(self, status) self.beta = 0 self.beta_pre = 0 self.mean_period_short = 20 self.mean_period_long = 40 self.sma_short_ts = pd.DataFrame() self.sma_long_ts = pd.DataFrame()
def __init__(self, status): Strategy.__init__(self, status) self.beta = 0 self.mean_period_short = 20 self.mean_period_long = 40 self.buy_threshold = 1.0 self.sell_threshold = 1.0 self.sma_short_ts = pd.DataFrame() self.sma_long_ts = pd.DataFrame()
def start_ui(): board = Board(6, 6) strategy = Strategy() p1 = Human('x', board) p2 = Computer("0", board, strategy) minimax = Minimax() game = Game(p1, p2, board, minimax) game.start()
def start_gui(): board = GuiBoard(9, 9) strategy = Strategy() p1 = GuiHuman('x', board) p2 = Computer('0', board, strategy) game = GuiGame(p1, p2, board) root = tkinter.Tk() my_gui = Gui(root, game) root.mainloop()
def __init__(self, status): Strategy.__init__(self, status) self.beta_pre = 0 self.beta = 0 self.mean_period_short = 20 self.mean_period_long = 40 self.buy_threshold = 1.0 self.sell_threshold = 1.0 self.sma_short_ts = pd.DataFrame() self.sma_long_ts = pd.DataFrame() self.sma_ols_ts = pd.DataFrame() self.mean_for_ols_period = 20 self.ols_period = 40 self.a = 0 self.b = 0 self.pre_b = 0
def main(): pygame.init() # Set the width and height of the screen [width, height] size = (int(settings.WIDTH * ZOOM), int(settings.HEIGHT * ZOOM)) screen = pygame.display.set_mode(size) pygame.display.set_caption("Simulator") royal_manager = RoyalManager() room = royal_manager.room strategy = Strategy(room) done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True strategy.run_tick() royal_manager.run_simulation_tick() Serializer.serialize(room, screen) clock.tick(60)
def __init__(self, market: Market): self.logger = logging.getLogger(__name__) self.configs = Utility.get_config(market) self.strategies = [] for strategy_name in self.configs.strategy.list: strategy = Strategy.get_strategy(strategy_name, self.configs.strategy) if strategy is not None: self.strategies.append(strategy) self.logger.info("Strategy %s added for market %s" % (strategy.name, market.value)) else: self.logger.error("Cannot find Strategy %s for market %s" % (strategy_name, market.value)) # set history folder self.history_folder = Utility.get_data_folder(market=market, folder=DataFolder.Stock_History)
def run(self, date, strategy_name, log): """ Run strategy and update wallet """ if self.stocks[0].getDateValue(date): if strategy_name == "naive": strategy = StrategyNaive( self.stocks, date, self.initial_account, self.lower, self.upper) else: strategy = Strategy(self.stocks, date, 1000, 0.7, 0.3) strats = strategy.run() self.wallet.save_last_account() for i, strat in enumerate(strats): # if the strategie says "buy" and the amount is available if strat[0] == "buy" and strat[1] > 0 and self.wallet.buying_autorisation(i, strat[1], date): if log: print( "Buy " + str(strat[1]) + " stock(s) of " + self.stocks[i].getName()) self.wallet.buy(i, date, int(strat[1])) self.stocks[i].buy( int(strat[1]), self.stocks[i].getDateValue(date)) # if the strategie says "sell" elif strat[0] == "sell" and self.stocks[i].getQuantity() > 0 and strat[1] > 0: sell = self.stocks[i].sell(int(strat[1])) if sell is not None: self.wallet.sell(i, date) if log: print( "Sell " + str(self.stocks[i].getQuantity()) + " stock(s) of " + self.stocks[i].getName()) else: if log: print("No go") self.wallet.update(date) self.last_account = self.wallet.virtual_account self.total_commission = self.wallet.total_commission self.total_transaction = self.wallet.total_transaction if log: print("Date : ", date, "Wallet account : ", self.wallet.virtual_account, ", Stocks amount : ", self.wallet.stocks_amount, ", Available cash : ", self.wallet.available_cash, "\nVariation with previous day : ", int(10000*(self.wallet.virtual_account-self.wallet.last_account)/self.wallet.virtual_account)/100)
def __init__(self): IDABot.__init__(self) self.workers = [] self.building_manager = BuildingManager(self) self.resource_manager = ResourceManager(self.minerals, self.gas, self.current_supply, self) self.unit_manager = UnitManager(self) self.strategy_network = Strategy(self) self.assignment_manager = AssignmentManager(self) self.scout_manager = ScoutingManager(self) self.building_strategy = BuildingStrategy(self, self.resource_manager, self.assignment_manager) self.print_debug = PrintDebug(self, self.building_manager, self.unit_manager, self.scout_manager, self.building_strategy, True) self.first = True self.counter = 0 self.left = True self.dance = 0 # Last time that strategy was handled by generating tasks etc self.last_handled_strategy = 0
def strategy(self): if not self._strategy: self._strategy = Strategy() return self._strategy
class MyAgent(IDABot): def __init__(self): IDABot.__init__(self) self.minerals_in_base = {} self.building_manager = BuildingManager(self) self.resource_manager = ResourceManager(self.minerals, self.gas, self.current_supply, self) self.unit_manager = UnitManager(self) self.strategy_network = Strategy(self) self.assignment_manager = AssignmentManager(self) self.scout_manager = ScoutingManager(self) self.building_strategy = BuildingStrategy(self, self.resource_manager, self.assignment_manager) self.print_debug = PrintDebug(self, self.building_manager, self.unit_manager, self.scout_manager, self.building_strategy, True) self.our_building_placer = None # Last time that strategy was handled by generating tasks etc self.last_handled_strategy = 0 self.first_tick = True self.block = False self.base_right = None self.choke_points_right = { (24.25, 28.5): Point2D(57, 73), (56.25, 130.5): Point2D(53, 118), (58.75, 99.0): Point2D(47, 92), (129.25, 54.5): Point2D(113, 58), (63.75, 51.0): Point2D(57, 73), (93.25, 69.0): Point2D(76, 84), (88.25, 117.0): Point2D(73, 115), (92.5, 143.5): Point2D(77, 134), (26.5, 137.5): Point2D(30, 133), (22.75, 113.5): Point2D(31, 118), (59.5, 24.5): Point2D(57, 73), (95.75, 37.5): Point2D(88, 49), (24.25, 83.5): Point2D(44, 95), (127.75, 139.5): Point2D(115, 135), (127.75, 84.5): Point2D(76, 84), (127.75, 28.5): Point2D(116, 44) } self.choke_points_left = { (58.75, 99.0): Point2D(58, 80), (24.25, 139.5): Point2D(36, 124), (127.75, 139.5): Point2D(95, 90), (92.5, 143.5): Point2D(95, 90), (56.25, 130.5): Point2D(64, 120), (22.75, 113.5): Point2D(38, 110), (127.75, 84.5): Point2D(113, 77), (24.25, 28.5): Point2D(37, 32), (24.25, 83.5): Point2D(58, 80), (88.25, 117.0): Point2D(76, 84), (93.25, 69.0): Point2D(108, 71), (59.5, 24.5): Point2D(71, 31), (95.75, 37.5): Point2D(98, 49), (63.75, 51.0): Point2D(79, 53), (129.25, 54.5): Point2D(121, 50), (127.75, 28.5): Point2D(117, 37) } self.messages = [ "We estimate the probability of winning to be over 95%", "Eslöööööööv" ] def on_game_start(self): self.our_building_placer = BuildingPlacer(self.start_location, self) IDABot.on_game_start(self) def on_step(self): IDABot.on_step(self) # Sync minerals available only sometimes if self.current_frame % 100 == 0: self.minerals_in_base.clear() for base in self.base_location_manager.get_occupied_base_locations( PLAYER_SELF): self.minerals_in_base[base] = [ mineral for mineral in self.get_mineral_fields(base) ] # first sync units, buildings and resources self.resource_manager.sync() self.unit_manager.on_step(self.get_all_units()) self.building_manager.on_step(self.get_my_units()) self.building_strategy.action() #if self.current_frame % 5000 == 0: #self.send_chat(random.choice(self.messages[1:])) # then run specific AI parts self.scout_manager.on_step() self.assignment_manager.on_step() #self.print_debug.on_step() # Generate jobs depending on strategy self.handle_strategy() def get_mineral_fields(self, base_location: BaseLocation): """ Given a base_location, this method will find and return a list of all mineral fields (Unit) for that base """ mineral_fields = [] for mineral_field in base_location.mineral_fields: for unit in self.get_all_units(): if unit.unit_type.is_mineral \ and mineral_field.tile_position.x == unit.tile_position.x \ and mineral_field.tile_position.y == unit.tile_position.y: mineral_fields.append(unit) return mineral_fields def get_geysers(self, base_location: BaseLocation): geysers = [] for geyser in base_location.geysers: for unit in self.get_all_units(): if unit.unit_type.is_geyser \ and geyser.tile_position.x == unit.tile_position.x \ and geyser.tile_position.y == unit.tile_position.y: geysers.append(unit) return geysers def handle_strategy(self): """ Generates jobs depending on our chosen strategy """ curr_seconds = self.current_frame // 24 # Only look at new strategy and generate new tasks every now and then if curr_seconds - self.last_handled_strategy < HANDLE_STRATEGY_DELAY: return # The previous tasks generated have not yet been assigned, don't create new tasks if self.assignment_manager.military_assignments.tasks: return # Calculate new predicted strategy strategy = self.strategy_network.get_strategy() # Now handling a strategy decision self.last_handled_strategy = curr_seconds # Get all of our command centers base_location_manager: BaseLocationManager = self.base_location_manager commandcenters = self.building_manager.get_total_buildings_of_type( UnitType(UNIT_TYPEID.TERRAN_COMMANDCENTER, self)) #command_centers = self.building_manager.get_buildings_of_type(UnitType(UNIT_TYPEID.TERRAN_COMMANDCENTER, self)) + \ # self.building_manager.get_under_construction_of_type(UnitType(UNIT_TYPEID.TERRAN_COMMANDCENTER, self)) commandcenters = list(reversed(list(commandcenters))) if strategy == StrategyName.OFFENSIVE: offensive_groups = 1 defensive_groups = 0 if not self.block: self.block = True self.send_chat(self.messages[0]) closest_enemy = self.get_closest_enemy_building() if not closest_enemy: attack_pos = self.scout_manager.get_enemy_target() else: attack_pos = closest_enemy.position else: # strategy == StrategyName.DEFENSIVE offensive_groups = 0 if len(commandcenters) <= 2: defensive_groups = 1 elif len(commandcenters) <= 3: defensive_groups = 2 else: defensive_groups = 3 # Generate all offensive tasks offensive_tasks = [ Task(task_type=TaskType.ATTACK, pos=attack_pos) for i in range(offensive_groups) ] # Generate all defensive tasks defensive_tasks = [ Task(task_type=TaskType.DEFEND, pos=self.get_choke_point( commandcenters[i].get_unit().position)) # Loop through all bases we have and for i in range(defensive_groups) if commandcenters ] # Add all generated tasks to assignment_manager for task in [*offensive_tasks, *defensive_tasks]: self.assignment_manager.add_task(task) def get_closest_enemy_building(self): enemies = [ unit for unit in self.get_all_units() if unit.player == PLAYER_ENEMY and unit.unit_type.is_combat_unit ] if not enemies: enemies = [ unit for unit in self.get_all_units() if unit.player == PLAYER_ENEMY ] return self.get_closest_enemy(enemies) def get_closest_enemy(self, unit_list): """ gets the closest enemy :return: closest unit """ own_pos = self.base_location_manager.get_player_starting_base_location( PLAYER_SELF).position if len(unit_list) == 0: return None closest_enemy = unit_list[0] closest_distance = self.get_distance_to(own_pos, closest_enemy.position) for enemy in unit_list: distance = self.get_distance_to(own_pos, closest_enemy.position) if distance < closest_distance: closest_distance = distance closest_enemy = enemy return closest_enemy def get_distance_to(self, pos1, pos2): """ Return the distance to a unit, if units is none 10 will be returned :param unit: :return: """ return math.sqrt((pos1.x - pos2.x)**2 + (pos1.y - pos2.y)**2) def get_choke_point(self, position: Point2D): if self.base_right is None: self.base_right = self.base_location_manager.get_player_starting_base_location( PLAYER_SELF).position.x > 50 # Choke points are based on base_location.position and :param: position is the command center position so # we choose the base_location position that is closest to our command center locations = list( map( lambda x: x.position, self.base_location_manager.get_occupied_base_locations( PLAYER_SELF))) closes_pos = None shortest_distance = 9999 for loc in locations: dist = ((position.x - loc.x)**2 + (position.y - loc.y)**2)**0.5 if dist < shortest_distance: closes_pos = loc shortest_distance = dist tPos = (closes_pos.x, closes_pos.y) return self.choke_points_right[ tPos] if self.base_right else self.choke_points_left[tPos]
def __init__(self, status): Strategy.__init__(self, status) self.period_back = 30 self.momentum = 0 self.beta = 0
def main(): print "------ System online -------", datetime.now() parser = argparse.ArgumentParser() common.config.add_argument(parser) parser.add_argument('--instrument', "-i", type=common.args.instrument, required=True, action="append", help="Instrument to get prices for") parser.add_argument('--snapshot', action="store_true", default=True, help="Request an initial snapshot") parser.add_argument('--no-snapshot', dest="snapshot", action="store_false", help="Do not request an initial snapshot") parser.add_argument('--show-heartbeats', "-s", action='store_true', default=False, help="display heartbeats") args = parser.parse_args() account_id = args.config.active_account api = args.config.create_streaming_context() account_api = args.config.create_context() response = api.pricing.stream(account_id, snapshot=args.snapshot, instruments=",".join(args.instrument)) dfD = PivotImports(sys.argv[2]).daily() # dfW = p.weekly() balance = Balance(account_api, account_id).balance() df = pd.DataFrame([]) for msg_type, msg in response.parts(): if msg_type == 'pricing.Heartbeat' and args.show_heartbeats: print(heartbeat_to_string(msg)) if msg_type == "pricing.Price": sd = StreamingData(datetime.now(), instrument_string(msg), mid_string(msg), account_api, account_id, 's', '1min', balance) df = df.append(sd.df()) ''' Re-sample is based on time parameter set in StreamingData(). i.e., 1min, 5min, 15min, etc. ''' sd.resample(df) ''' This following output is information on the streaming data that has been collected. df.shape[0]: represents the current/cumulative rows of streaming data that has come in. sd.shape[0]: represents the current/cumulative rows related to the time frame being evaluated. ''' # print "df:", df.shape[0], "minuteData:", sd.minuteData().shape[0] print sd.minuteData(), '\n' if sd.minuteData().shape[0] < 20: continue else: client = oandapyV20.API(settings.ACCESS_TOKEN) r = openPos.OpenPositions(accountID=account_id) client.request(r) ''' Declare array to store open trades so multiple positions aren't established on a single currency. ''' openTrades = [] for i in r.response['positions']: trades = i['instrument'] openTrades.append(trades) print('Open Trades', openTrades) if instrument_string(msg) in openTrades: continue else: try: breakout = Breakout(sd.minuteData(), mid_string(msg)) breakout_units = breakout.breakout() if breakout_units is None: pass else: spread = Spreads(dfD, mid_string(msg)) pivot, rl1, rl2, rl3, sl1, sl2, sl3 = spread.spreads() rate1, rate2 = spread.spreadRates() strategy = Strategy( instrument_string(msg), dfD, mid_string(msg), breakout_units, pivot, rl1, rl2, rl3, sl1, sl2, sl3, rate1, rate2 ) if strategy.resistance_check() is None: continue else: units, stop_loss, profit = strategy.resistance_check() try: resistance_execute = Execute( account_api, account_id, instrument_string(msg), units, stop_loss, profit ) resistance_execute.trade() except Exception as e: print(e) if strategy.support_check() is None: continue else: units, stop_loss, profit = strategy.support_check() try: support_execute = Execute( account_api, account_id, instrument_string(msg), units, stop_loss, profit ) support_execute.trade() except Exception as e: print(e) except Exception as e: print(e)
def __init__(self): IDABot.__init__(self) self.minerals_in_base = {} self.building_manager = BuildingManager(self) self.resource_manager = ResourceManager(self.minerals, self.gas, self.current_supply, self) self.unit_manager = UnitManager(self) self.strategy_network = Strategy(self) self.assignment_manager = AssignmentManager(self) self.scout_manager = ScoutingManager(self) self.building_strategy = BuildingStrategy(self, self.resource_manager, self.assignment_manager) self.print_debug = PrintDebug(self, self.building_manager, self.unit_manager, self.scout_manager, self.building_strategy, True) self.our_building_placer = None # Last time that strategy was handled by generating tasks etc self.last_handled_strategy = 0 self.first_tick = True self.block = False self.base_right = None self.choke_points_right = { (24.25, 28.5): Point2D(57, 73), (56.25, 130.5): Point2D(53, 118), (58.75, 99.0): Point2D(47, 92), (129.25, 54.5): Point2D(113, 58), (63.75, 51.0): Point2D(57, 73), (93.25, 69.0): Point2D(76, 84), (88.25, 117.0): Point2D(73, 115), (92.5, 143.5): Point2D(77, 134), (26.5, 137.5): Point2D(30, 133), (22.75, 113.5): Point2D(31, 118), (59.5, 24.5): Point2D(57, 73), (95.75, 37.5): Point2D(88, 49), (24.25, 83.5): Point2D(44, 95), (127.75, 139.5): Point2D(115, 135), (127.75, 84.5): Point2D(76, 84), (127.75, 28.5): Point2D(116, 44) } self.choke_points_left = { (58.75, 99.0): Point2D(58, 80), (24.25, 139.5): Point2D(36, 124), (127.75, 139.5): Point2D(95, 90), (92.5, 143.5): Point2D(95, 90), (56.25, 130.5): Point2D(64, 120), (22.75, 113.5): Point2D(38, 110), (127.75, 84.5): Point2D(113, 77), (24.25, 28.5): Point2D(37, 32), (24.25, 83.5): Point2D(58, 80), (88.25, 117.0): Point2D(76, 84), (93.25, 69.0): Point2D(108, 71), (59.5, 24.5): Point2D(71, 31), (95.75, 37.5): Point2D(98, 49), (63.75, 51.0): Point2D(79, 53), (129.25, 54.5): Point2D(121, 50), (127.75, 28.5): Point2D(117, 37) } self.messages = [ "We estimate the probability of winning to be over 95%", "Eslöööööööv" ]
def run(self, date, strategy_name, log): """ Run strategy and update wallet """ if log: print("\nOpen : \nWallet account : " + str(self.wallet.virtual_account) + "\nStocks amount : " + str(self.wallet.stocks_amount) + "\nAvailable cash : " + str(self.wallet.available_cash) + "\n") if self.stocks[0].getDateValue(date): if strategy_name == "naive": strategy = StrategyNaive(self.stocks, date, self.initial_account, self.lower, self.upper) elif strategy_name == "ml": strategy = StrategyML(self.stocks, date, 3000) else: strategy = Strategy(self.stocks, date, 1000, 0.7, 0.3, self.wallet.available_cash) strats = strategy.run() self.wallet.save_last_account() for i, strat in enumerate(strats): # if the strategie says "buy" and the amount is available stock = self.stocks[i] if strat[0] == "buy" and strat[ 1] > 0 and self.wallet.buying_autorisation( i, strat[1], date): stock.buy(int(strat[1]), self.wallet, stock.getDateValue(date)) if log: print(stock.getName() + " (" + str(stock.getQuantity()) + "|" + str(stock.getDateValue(date)) + ")" + " : Buy " + str(strat[1]) + " stock(s)" + " -> +" + str(strat[1] * stock.getDateValue(date)) + " euros") # if the strategie says "sell" elif strat[0] == "sell" and stock.getQuantity( ) > 0 and strat[1] > 0: sell = stock.sell(self.wallet, stock.getDateValue(date), quantity=int(strat[1])) if sell is not None: if log: print(stock.getName() + " (" + str(stock.getQuantity()) + "|" + str(stock.getDateValue(date)) + ")" + " : Sell " + str(strat[1]) + " stock(s)" + " -> -" + str(strat[1] * stock.getDateValue(date)) + " euros") else: if log: print(stock.getName() + " (" + str(stock.getQuantity()) + "|" + str(stock.getDateValue(date)) + ")" + " : No go") self.wallet.update(date) self.last_account = self.wallet.virtual_account self.total_commission = self.wallet.total_commission self.total_transaction = self.wallet.total_transaction if log: print("\nClose : \nWallet account : " + str(self.wallet.virtual_account) + "\nStocks amount : " + str(self.wallet.stocks_amount) + "\nAvailable cash : " + str(self.wallet.available_cash) + "\nVariation with previous day : " + str(100 * ((self.wallet.virtual_account - self.wallet.last_account) / self.wallet.virtual_account)) + "\n")
def apply_strategy_to_stock_list(evaluate_date: date, stock_ids: List[str], strategy: Strategy) -> Dict[str, bool]: return { stock_id: strategy.evaluate(evaluate_date, stock_id) for stock_id in stock_ids }
def main(): print "------ System online -------", datetime.now() parser = argparse.ArgumentParser() common.config.add_argument(parser) parser.add_argument('--instrument', "-i", type=common.args.instrument, required=True, action="append", help="Instrument to get prices for") parser.add_argument('--snapshot', action="store_true", default=True, help="Request an initial snapshot") parser.add_argument('--no-snapshot', dest="snapshot", action="store_false", help="Do not request an initial snapshot") parser.add_argument('--show-heartbeats', "-s", action='store_true', default=False, help="display heartbeats") args = parser.parse_args() # print sys.argv[2] account_id = args.config.active_account api = args.config.create_streaming_context() account_api = args.config.create_context() response = api.pricing.stream(account_id, snapshot=args.snapshot, instruments=",".join(args.instrument)) dfD = PivotImports(sys.argv[2]).daily() # dfW = p.weekly() balance = Balance(account_api, account_id).balance() df = pd.DataFrame([]) for msg_type, msg in response.parts(): if msg_type == "pricing.Heartbeat" and args.show_heartbeats: print heartbeat_to_string(msg) if msg_type == "pricing.Price": sd = StreamingData(datetime.now(), instrument_string(msg), mid_string(msg), account_api, account_id, 's', '5min', balance) df = df.append(sd.df()) sd.resample(df) print "df:", df.shape[0], "minuteData:", sd.minuteData().shape[0] # print sd.minuteData(),'\n' if sd.minuteData().shape[0] < 20: continue else: client = oandapyV20.API(settings.ACCESS_TOKEN) r = openPos.OpenPositions(accountID=account_id) client.request(r) openTrades = [] for i in r.response['positions']: trades = i['instrument'] openTrades.append(trades) print 'Open Trades', openTrades if instrument_string(msg) in openTrades: continue else: try: b = Breakout(sd.minuteData()) breakout = b.breakout() # print 'Breakout Units:',breakout s = Spreads(dfD, mid_string(msg)) pivot, rl1, rl2, rl3, sl1, sl2, sl3 = s.spreads() rate1, rate2 = s.spreads_out() strat = Strategy(account_api, account_id, instrument_string(msg), dfD, mid_string(msg), breakout, pivot, rl1, rl2, rl3, sl1, sl2, sl3, rate1, rate2) strat.res_check() strat.sup_check() except Exception as e: print e
def __init__(self, status): Strategy.__init__(self, status) self.beta = 0 self.period = 30
def __init__(self, status): Strategy.__init__(self, status) self.rsi = 50 self.rsi_period = 40