def closest_to_16(): game_para = [0.5, 0, 1, 0.2] total_turns = 100 total_res = 500 pop = [] types2 = [[0, 0, 0, 0], [1, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 1], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]] for i in range(34): pop.append( Strategy.M2_2(total_turns, [ random.random(), random.random(), random.random(), random.random() ])) for t in types2: pop.append(Strategy.M2_2(total_turns, t)) #print("********************************") r = Replicator(game_para, total_turns, total_res, pop) r.play_days(100, "all closest", total_res, 0.1)
def main(): print(50 * "#") print("Starting main process") Database.create_db() while True: status = itter() time = status[0] currency = status[1] rep = status[2] loopdone = status[3] timeloop = status[4] if loopdone: BinanceAPI.initiate() data = BinanceAPI.get_data(time, currency, rep, loopdone) if rep != 0: last_line = Stockstats.update_stockstats(data) Database.update_db(time, currency, last_line) print(time, markets[currency]) Strategy.MACD_crossover(time, currency, timeloop) Strategy.RSI(time, currency, timeloop) else: data2 = Stockstats.make_stockstats(data) Database.fill_new_db(time, currency, data2) print(time, markets[currency])
def get_output(self, packet): Procedure.pre_process(self, packet) Strategy.plan(self) Handling.execute(self) Procedure.feedback(self) self.LogAction(packet) return self
def start(self, team_name): lines = [] lines.append("register %s" % team_name) self.my_team._Team___set_players(Strategy.init_players()) x = ",".join(str(player) for player in self.my_team) formation = "formation %s" % x lines.append(formation) try: for each in lines: print(each, end='\n', flush=True, file=self.__output) except Exception as e: print(e) self.opp_team._Team___set_players(Strategy.init_players()) while True: try: lines = [] lines.append(self.__input.readline()) if str(lines[0]).strip('\n') == 'END': print("Finished") break lines.append(self.__input.readline()) lines.append(self.__input.readline()) lines.append(self.__input.readline()) except Exception as e: print("problem in getting response from server:") print('\t', e) return self.play_round(lines)
def __init__(self, game_data, strong_team=False, co_action=True): Strategy.__init__(self, game_data) self.result_dict['strategy_args'] = {'strong_team': strong_team} self.strong_team = strong_team self.co_action = co_action self.score = '0-0'
def learnOnSet(set_name=""): set_num = 1 i = 0 db.connect() strategy = Strategy.Strategy1() while i < set_num: strategy = learnVariant(strategy, 1) i = i + 1 with open("Strategy1.pickle", "wb") as f: pickle.dump(strategy, f) i = 0 strategy = Strategy.Strategy2() while i < set_num: strategy = learnVariant(strategy, 2) i = i + 1 with open("Strategy2.pickle", "wb") as f: pickle.dump(strategy, f) i = 0 strategy = Strategy.Strategy3() while i < set_num: strategy = learnVariant(strategy, 3) i = i + 1 with open("Strategy3.pickle", "wb") as f: pickle.dump(strategy, f) db.save("read.txt")
def strategy_run(tradingDays,symbols, dataPath, dataReadType, outputpath, signal, lbwindow, lawindow,paraset,Asset,Fee,Name): stats_ = list() for tradingDay in [(tradingDays)]: #print('hapi' + str(list(tradingDays))) #print(tradingDay) tradingDay = tradingDay.replace('-','') print('Processing tradingday = ', tradingDay) tradingSymbols = list(symbols[list( map(lambda symbol: CheckStockSuspend(symbol, dataPath, tradingDay,Asset), symbols.values.tolist()))]) if len(tradingSymbols) == 0: continue if Asset == 'Future': data = Data.Data(dataPath, '', tradingDay, futureSymbols=tradingSymbols, dataReadType=dataReadType, RAWDATA='True') signalTester = SignalTester.SignalTester(data, dailyData=pd.DataFrame, tradeDate=tradingDay, symbol=tradingSymbols,fee = Fee, dataSavePath=outputpath,type = 'Future') else: data = Data.Data(dataPath, tradingSymbols, tradingDay, dataReadType=dataReadType, RAWDATA='True') # todo signalTester signalTester = SignalTester.SignalTester(data, dailyData=pd.DataFrame, tradeDate=tradingDay,symbol=tradingSymbols, fee = Fee,dataSavePath=outputpath) # signalTester.CompareSectorAndStock(symbols[0], orderType='netMainOrderCashFlow') stsDf = list() strategyResult = list() for symbol in tradingSymbols: temp = signalTester.CheckSignal(symbol,signal,lbwindow,lawindow,paraset) if temp is not None: stsDf.append(temp) if Asset =='Future': quoteData = data.futureData[symbol] else: quoteData = data.quoteData[symbol] #print(quoteData) ##todo future strategy if Asset == 'Future': strategy = Strategy.Strategy(symbol, round(1000000/quoteData['midp'].iloc[-1],-2), quoteData, signal, tradingDay,lbwindow, lawindow,6, 'lawindow',fee = Fee,outputpath = './strategy/' + tradingDay, stockType = 'low',asset = 'Future') else: strategy = Strategy.Strategy(symbol, round(1000000/quoteData['midp'].iloc[-1],-2), quoteData, signal,tradingDay,lbwindow, lawindow,6, 'lawindow',fee = Fee,outputpath = './strategy/' + tradingDay, stockType = 'low') strategy.SummaryStrategy() strategy.Plot() #print(strategy.sts) strategyResult.append(strategy.sts) #print(len(stsDf)) if len(stsDf) > 0: ##保证至少有1 #print(tradingDay) pd.concat(stsDf,0).to_csv(outputpath+'./' + tradingDay +Name+ '.csv') pd.concat(strategyResult,0).to_csv('./strategy/' + tradingDay +Name+ '.csv') return 0
def run_strategy(): #moving average strategy strategy = Strategy() # get buy sell dataframe bs_df = strategy.handle_data() bs_df[['return_cum', 'strategy_return_cum']].dropna().plot(title='moving average', style=['--', '-']) plt.xticks(rotation=90) plt.legend() plt.show()
def start(): with open("white_list.txt", 'r') as f: sp500 = f.read() sp500_list = sp500.split(",") # Different strategies initiated with a number if sys.argv[1] == '1': earnings_map = Strategy.AM_strategy1(pull_list=sp500_list) elif sys.argv[1] == '2': if len(sys.argv) > 2: pull_list = Strategy.AM_PM_Change_Average(pull_list=[sys.argv[2]], additional_pull=True) else: earnings_map = Strategy.AM_PM_Change_Average(pull_list=sp500_list)
def Process(self, game, packet, info, lock): Procedure.pre_process(self, game, packet, lock) Procedure.rlu_pp(self, info) Strategy.plan(self) Handling.controls(self) Procedure.feedback(self) Procedure.finish(self) return Handling.output(self)
def Process(self, game): Procedure.pre_process(self, game) Strategy.plan(self) Handling.controls(self) Procedure.feedback(self) Procedure.finish(self) return Handling.output(self)
def agent_like_TFT(total_turns,threshold): #Threshold and Support are percentages agent_l=[Perceptron_strategy.Mperp(total_turns,0,0,1,[2],0), Perceptron_strategy.Mperp(total_turns,0,1,1,[2],0), Perceptron_strategy.Mperp(total_turns,0,0,2,[2],0), RM.Mperp(total_turns,0,0,1,[2],0), RM.Mperp(total_turns,0,1,1,[2],0), RM.Mperp(total_turns,0,0,2,[2],0), Memory_strategy.Mn(total_turns,0,0,1), Memory_strategy.Mn(total_turns,0,1,1), Memory_strategy.Mn(total_turns,0,0,2) ] for j in range(len(agent_l)): total=0 passed=0 for i in range(100000): agent_l=[Perceptron_strategy.Mperp(total_turns,0,0,1,[2],0), Perceptron_strategy.Mperp(total_turns,0,1,1,[2],0), Perceptron_strategy.Mperp(total_turns,0,0,2,[2],0), RM.Mperp(total_turns,0,0,1,[2],0), RM.Mperp(total_turns,0,1,1,[2],0), RM.Mperp(total_turns,0,0,2,[2],0), Memory_strategy.Mn(total_turns,0,0,1), Memory_strategy.Mn(total_turns,0,1,1), Memory_strategy.Mn(total_turns,0,0,2) ] p2=Strategy.TFT(total_turns) total+=1 if agent_similarity(agent_l[j],p2,total_turns,threshold): passed+=1 print(agent_l[j].type," -> ", passed*100/total)
def update_caches_with_latest(): try: strategy_name = sys.argv[1] except: strategy_name = "AM_PM_Change_Average_strat" # print("enter a valid strategy name") # exit(0) local_dir = os.getcwd() cp = CalendarParser("white_list.txt", "dates") cp.pullandStoreEarningsDates(append_new_data=True) cp.loadCached() strategy = Strategy.Strategy( strategy_name, None, None, None, difference_instructions_by_strategy[strategy_name], "am") strategy.pull_cache_data() strategy.gather_data(cp.earnings_map, None, yahoo_daily=True, write=True, append_cache=True) earnings_return_data_map = strategy.pull_cache_data() if strategy_name == "AM_PM_Change_Average_strat": strategy.generate_daily_csv_library(earnings_return_data_map, "earnings_call_difference_data", local_dir)
def __init__(self, market, year, month, transRecoder, lock, q): threading.Thread.__init__(self) self._market = market self._year = year self._month = month self._candles = Currency.Markets.candelOfMarket(self._market) self._types = Hunter.Type_Container(self._candles) self._pens = Hunter.Pen_Container(self._types) self._bucket = Strategy.Ten_Min_Bucket(self._candles) self._hubs = Hunter.Ten_Min_Hub_Container(self._pens, self._bucket) self._bucket.loadHubs(self._hubs) self._trans = Hunter.Tran_Container() self._bucket.loadTrans(self._trans) self._transRecorder = transRecoder self._lock = lock self._q = q
def scan(account, type, date): data = Data.get_stock_list() print(data) orders = [] totalEquity = (account.balances['combinedBalances'][1]['totalEquity']) #remove bought stocks print("Checking for stocks already bought") for currPos in account.positions['positions']: for stock in data: if currPos == stock: print(currPos + 'has been bought') data.remove(stock) # stock hasn't been bought and could be traded for stock in data: df = pd.read_csv('Data/' + stock + '.csv', index_col='Date') try: buy = s.strat2(stock, df, date) if buy: currPrice = si.get_live_price(stock) newOrder = o.Order(stock, currPrice, df, date) newOrder.setLong(df, totalEquity, date) orders.append(newOrder) except: print('Error Getting Stock Prices') pass if len(orders) == 0: print('Hold portfolio') else: print("Opportunities on {}".format(date)) rank_orders(orders, 'MACD') for order in orders: print(order.symbol, order.dEMA, order.rsi, order.dMACD)
def start_round(sock, team_id): game = Game(sock, team_id) game.register() with open("log.txt", "a+") as f: f.write("success register") while True: game.receive_msg() msg_name = game.get_msg_name() if msg_name == "round": game.round_start() control = Control(team_id, game.our_tank_id, game.maps, game.data) strategy = Strategy(game) # 操作函数 game.set_tank_msg() try: # AI_zx.start_zx(game,control) new_start.start_5_28(game, control, strategy) except Exception as e: log.log("start:") log.log(e) control.send_msg(sock) game.round_clear() elif msg_name == "leg_start": game.leg_start() elif msg_name == MSG_NAME_LEG_END: print(game.data["msg_data"]) game.leg_clear() elif msg_name == MSG_NAME_GAME_OVER: print("Game Over ...") break
def learnOnSet(set_name): sets = db.readSet(set_name) strategy = Strategy.Strategy() for i in sets: var = i self.learnVariant(strategy) db.save(strategy, "result.txt")
def main(): user_interface() # Set global time variables trading_day = 0 # Initialize performance data frame performance = [] # Start back-test account = acc.Account(INITIAL_CAPITAL) while trading_day <= DAYS: performance.append(daily_execution(trading_day, account)) trading_day = trading_day + 1 # Calculate net values and save back-test result to files print('****** Back-test finished, generating output data ******') columns = ['Account', 'HS300'] performance = pd.DataFrame(performance, columns=columns) performance_return = strt.get_return_data(performance) net_value = pd.DataFrame(np.ones((len(performance_return), 2)), columns=columns) net_value.iloc[0] = [1, 1] for i in range(1, len(net_value)): net_value.iloc[i] = net_value.iloc[i - 1] * ( net_value.iloc[0] + performance_return.iloc[i - 1]) performance.to_csv(OUTPUT_PATH + 'performance.csv') performance_return.to_csv(OUTPUT_PATH + 'return.csv') net_value.to_csv(OUTPUT_PATH + 'netValue.csv') # Print performance data performance_management(performance_return, net_value)
def cash_out(self, odds_set): """ Cash out all tickets when one team scored :param odds_set: list of odds """ if odds_set[-2] == 'Run' and odds_set[-1] == self.score: total = 0 for option in self.ticket_bucket: for ticket in self.ticket_bucket[option]: (odds, invest) = self.ticket_bucket[option][ticket] try: total += odds / odds_set[option] * invest percentage = Strategy.compute_changing_rate( odds, odds_set[option]) self.store_operation(0, option, odds, invest, odds_set[option], percentage) except Exception as e: print e print odds_set print self.result_dict exit(2) self.winning += total self.ticket_bucket = {0: {}, 1: {}, 2: {}}
def __init__(self): self.tb = TradeBook.TradeBook() self.all_strategy = Strategy.Strategy() self.cere = '' self.file = open("Result.json", "w") self.hisfile = open("History.txt", "w") self.json_obj = { "team": "RuntimeException", "destination": "*****@*****.**", "transactions": [] }
class StrategyPlayer(Player): def __init__(self, strategy, rules): self.strategy = Strategy(strategy, rules) name = strategy + " Strategy Player" Player.__init__(self, name) def Decision(self, hand, upCard): decision = self.strategy.Decision(hand, upCard) # print( self.name + " Chose to "+ decision + " " + str(hand.value) + " (", end = '' ) # printHand(hand, '') # print( ") vs Dealer " + upCard.face ) return decision
def diff_memory_types(): game_para=[0.5, 0, 1, 0.2] total_turns=100 total_res=500 pop=[] types2=[[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,0,1,1],[0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,1,1], [1,0,0,0],[1,0,0,1],[1,0,1,0],[1,0,1,1],[1,1,0,0],[1,1,0,1],[1,1,1,0],[1,1,1,1] ] types1=[[0,0],[0,1],[1,0],[1,1]] for i in range(5): for t in types1: pop.append(Strategy.M1(total_turns,t)) pop.append(Strategy.M1(total_turns,t)) for t in types2: pop.append(Strategy.M2(total_turns,t)) pop.append(Strategy.M2_2(total_turns,t)) r=Replicator(game_para,total_turns,total_res,pop) r.play_days(500,"types",total_res)
def __init__(self): self.pf = PriceFeed.PriceFeed() self.tb = TradeBook.TradeBook() self.ip = '127.0.0.1' self.port1 = 8211 self.port2 = 8212 self.all_strategy = Strategy.Strategy() self.file = open("Result.json", "w") self.json_obj = { "team": "RuntimeException", "destination": "*****@*****.**", "transactions": [] }
def start(self, strat, capital, commission): self.initDatabase() self.initPipelineTables() self.initStatisticsTables() self.initTradingTable() self.initBookTables() entryConditions, exitConditions = stratFuncs strat = stra.Strategy(stratName, entryConditions, exitConditions) self.databaseManager = dbm.DatabaseManager(self.dbRef, self.conn, strat, auth) self.databaseManager.setTradingParameters(self.exchange, self.ticker)
def __apply_strategy(self, sob): """For each method in the strategy, add it to the tail of the functions list. Create the functions list with our original method, if it's empty. """ for m in sob.methods: # Can't use setdefault() here, as getattr(self, m) is # different if _method_overrides already has a key for m # in it, and setdefault() evaluates all its parameters. if m not in self._method_overrides: orig_fn = getattr(self, m).im_func self._method_overrides[m] = [Strategy.override(orig_fn)] self._method_overrides[m].append(getattr(sob, m).im_func) sob.applied(self)
def mousePressed(app, event): if app.gamePage == True: if ((app.pvpX <= event.x <= app.pvpX+app.buttonWidth) and (app.buttonY <= event.y <= app.buttonY + app.buttonHeight)): app.pvpMode = True createMatrix(app) app.timerDelay = 0 app.gamePage = False elif ((app.spectateX <= event.x <= app.spectateX+app.buttonWidth) and (app.buttonY <= event.y <= app.buttonY + app.buttonHeight)): app.spectateMode = True app.timerDelay = 0 createSpectatorMatrix(app) app.gamePage = False elif ((app.aiOneX <= event.x <= app.aiOneX+app.buttonWidth) and (app.buttonY <= event.y <= app.buttonY + app.buttonHeight)): app.aiOneMode = True createMatrix(app) app.gamePage = False elif ((app.aiTwoX <= event.x <= app.aiTwoX+app.buttonWidth) and (app.buttonY <= event.y <= app.buttonY + app.buttonHeight)): app.aiTwoMode = True createMatrix(app) app.gamePage = False elif ((app.aiThreeX <= event.x <= app.aiThreeX+app.buttonWidth) and (app.buttonY <= event.y <= app.buttonY + app.buttonHeight)): app.aiThreeMode = True createMatrix(app) app.gamePage = False elif app.aiOneMode or app.aiThreeMode or app.aiTwoMode or app.pvpMode: row, col = event.y // app.cellSize, event.x // app.cellSize app.click = int(row), int(col) if not app.pvpMode: if not app.gameOver: if app.width-2*app.cellSize+4 <= event.x <= app.width-app.cellSize-2 and app.height-60 <= event.y <= app.height-10: s = Strategy.Strategy() helperMove = s.best_strategy(app.board, app.playerSymbol) helperBoard = move(app.board, app.playerSymbol, helperMove) for i in range(len(app.board)): if helperBoard[i] != app.board[i]: app.moveAssist = (i//10, i%10) if app.moveAssist in app.moves: break elif app.spectateMode: resetApp(app) app.spectateMode = True app.timerDelay = 0 createSpectatorMatrix(app) app.gamePage = False
def __init__(self, parent, tile_index, root): self.width = 0 self.height = 0 self.parent = parent self.tile_index = tile_index self.root = root self.strategy = Strategy() self.img = None self.draw(init=True) return
def perceptron_like_TFT(my_memory,opp_memory,total_turns,threshold): #Threshold and Support are percentages for layer_list in [[],[2],[3],[2,2],[3,2],[4],[3,3],[3,2,2],[2,2,2]]: total=0 passed=0 for i in range(10000): #if i%1000==0: # print(i," samples") #p1=Perceptron_strategy.Mperp(total_turns,0,my_memory,opp_memory,layer_list,0) p1=Perceptron_strategy.Mperp(total_turns,0,0,1,[2],0) #print(p1.weights," ",p1.bias) p2=Strategy.TFT(total_turns) total+=1 if agent_similarity(p1,p2,total_turns,threshold): passed+=1 print(layer_list," -> ", passed*100/total)
def play_round(self, lines): self_team = lines[0].split(',') opp_team = lines[1].split(',') for each, each_pos in zip(self.my_team, self_team): each.pos._Pos__x, each.pos._Pos__y = map(float, each_pos.split(":")) for each, each_pos in zip(self.opp_team, opp_team): each.pos._Pos__x, each.pos._Pos__y = map(float, each_pos.split(":")) self.ball.pos._Pos__x, self.ball.pos._Pos__y = map( float, lines[2].split(":")) self.my_team._Team__score, self.opp_team._Team__score, self.__cycle_no = map( int, lines[3].split(',')) self.kick(Strategy.do_turn(self))
def var_types(): game_para=[0.5, 0, 1, 0.2] total_turns=100 total_res=500 pop=[] types2=[[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,0,1,1],[0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,1,1], [1,0,0,0],[1,0,0,1],[1,0,1,0],[1,0,1,1],[1,1,0,0],[1,1,0,1],[1,1,1,0],[1,1,1,1] ] var_list=[0.0001,0.0003,0.0005,0.0007,0.001,0.005,0.01,0.05,0.1,0.2] for i in range(2): for var in var_list: for t in types2: pop.append(Strategy.Mp(total_turns,t,var)) r=Replicator(game_para,total_turns,total_res,pop) r.play_days(300,"var types",total_res)
def main(): rospy.init_node('ai', anonymous=False) # Create robot objects that store that current robot's state _create_robots() global _ball _ball = Ball() # Subscribe to Robot States rospy.Subscriber('my_state', RobotState, lambda msg: _handle_robot_state(msg, 'me')) rospy.Subscriber('ally_state', RobotState, lambda msg: _handle_robot_state(msg, 'ally')) rospy.Subscriber('opponent1_state', RobotState, lambda msg: _handle_robot_state(msg, 'opp1')) rospy.Subscriber('opponent2_state', RobotState, lambda msg: _handle_robot_state(msg, 'opp2')) rospy.Subscriber('ball_state', BallState, _handle_ball_state) # This message will tell us if we are to be playing or not right now rospy.Subscriber('/game_state', GameState, _handle_game_state) pub = rospy.Publisher('desired_position', Pose2D, queue_size=10) rate = rospy.Rate(100) #100 Hz while not rospy.is_shutdown(): # Was there a goal to tell Strategy about? if _game_state['us_goal']: goal = Strategy.G.US _game_state['us_goal'] = False elif _game_state['them_goal']: goal = Strategy.G.THEM _game_state['them_goal'] = False else: goal = Strategy.G.NO_ONE # We didn't name this well ha. So 'not' it one_v_one = not _game_state['two_v_two'] (x_c, y_c, theta_c) = Strategy.choose_strategy(_me, _ally, _opp1, _opp2, _ball, \ was_goal=goal, one_v_one=one_v_one) # Get a message ready to send msg = Pose2D() if _game_state['play']: # Run AI as normal msg.x = x_c msg.y = y_c msg.theta = theta_c else: # Send robot to home if _me.ally1: msg.x = Constants.ally1_start_pos[0] msg.y = Constants.ally1_start_pos[1] msg.theta = Constants.ally1_start_pos[2] elif _me.ally2: msg.x = Constants.ally2_start_pos[0] msg.y = Constants.ally2_start_pos[1] msg.theta = Constants.ally2_start_pos[2] # If it's not the first time, the robot will 'hold its ground' # even while paused. (See guidedog_node.py) if not _game_state['first_time']: pub.publish(msg) rate.sleep() # spin() simply keeps python from exiting until this node is stopped rospy.spin()
#!/usr/bin/env python from random import shuffle from ants import * from EskymoBot import * from Strategy import * if __name__ == '__main__': try: import psyco psyco.full() except ImportError: pass try: strategy = Strategy() strategy.run(EskymoBot(), AntsDriver()) except KeyboardInterrupt: print('ctrl-c, leaving ...')