Example #1
0
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
Example #2
0
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 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)
Example #5
0
 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": []
     }
Example #6
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()
Example #7
0
    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)
Example #8
0
 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": []
     }
Example #9
0
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
Example #10
0
    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
Example #11
0
def main():
    agents, env, motivation = init_maze_task()
    #env,motivation = init_simple_task()
    #env,motivation = init_alter_task()

    strat = Strategy(motivation)
    ''' First envs'''
    #strat = OldStrategy()

    agent = DullAgent(strat, ["▲", "■", "▶", "◀"])
    #agent = TotalRecall(strat, ["▲", "■", "▶", "◀"])
    #agent = CartesianAgent(strat, ["▲", "■", "▶", "◀"])

    #Exécuter cet agent pour les premiers environnements (nombre d'actions différent)
    ''' Firsts Env'''
    #agent = SmartAgent(strat,100,  ["►", "◄"])

    i = 0

    while i < FLAGS.steps:
        if i > FLAGS.steps - 20:
            time.sleep(0.3)

        action = agent.chooseExperience(i, FLAGS.steps)
        #result = env.getResult(str(action)) # To use if the task is not a Maze
        result = env.step(agents[0], action)  # To use if the task is a  Maze
        reward = agent.get_reward(result)

        if agent._name != "cartesian":
            agent.memory(
            )  # TODO : ------- > comment this line to see memory usage efficiency
        #agent.tracer(reward, i)

        if FLAGS.debug:
            print("--------------------------")
            print("J'ai choisis : " + agent.symb[action])
            print("J'ai eu : r" + str(result))
            print("Pour : " + str(reward) + " pts")

        i += 1
    describe(agent)
Example #12
0
    def __init__(self):
        self.time = 0

        self.cillioned = []  # log the collision agents
        self.deadTargets = []
        self.threshold = 0

        # add goods
        self.goods = [Models.good() for i in xrange(10 * 8)]
        # put goods in warehouse
        indexupleft = 0  # index the goods position  to mark letter
        indexupright = 0
        indexdownleft = 0
        indexdownright = 0

        for group in range(10):
            offset = (0, 0)
            if group % 2 == 0:  # upper row
                offset = ((3 * (group / 2) + 1) * L + margin_left,
                          margin_top + L)
            elif group % 2 == 1:  # lower row
                offset = ((3 * (group / 2) + 1) * L + margin_left,
                          margin_top + 6 * L)
            # print "for good in group ", group, " Offset: ", offset
            for i in range(8):
                if (i % 2 == 0):  # on left
                    self.goods[i + group * 8].status = 0
                    self.goods[i + group * 8].x = offset[0]
                    self.goods[i + group * 8].y = offset[1] + int(i / 2) * L
                    self.goods[i + group *
                               8].agentx = self.goods[i + group * 8].x - 25
                    self.goods[i + group *
                               8].agenty = self.goods[i + group * 8].y + 25
                    if group % 2 == 0:
                        self.goods[
                            i + group *
                            8].goodfindletter = GOOD_FIND_LETTER_UP_LEFT[
                                indexupleft]
                    else:
                        self.goods[
                            i + group *
                            8].goodfindletter = GOOD_FIND_LETTER_DOWN_LEFT[
                                indexdownleft]

                elif (i % 2 == 1):  # on right
                    self.goods[i + group * 8].status = 0
                    self.goods[i + group * 8].x = offset[0] + L
                    self.goods[i + group * 8].y = offset[1] + int(i / 2) * L
                    self.goods[i + group *
                               8].agentx = self.goods[i + group * 8].x + 75
                    self.goods[i + group *
                               8].agenty = self.goods[i + group * 8].y + 25
                    if group % 2 == 0:
                        self.goods[
                            i + group *
                            8].goodfindletter = GOOD_FIND_LETTER_UP_RIGHT[
                                indexupright]
                    else:
                        self.goods[
                            i + group *
                            8].goodfindletter = GOOD_FIND_LETTER_DOWN_RIGHT[
                                indexdownright]

            if group % 2 == 0:
                indexupleft += 1
                indexupright += 1
            else:
                indexdownleft += 1
                indexdownright += 1

        # change the good status ocuppied red colour
        for i in xrange(len(GOOD_NUM)):
            self.goods[GOOD_NUM[i]].status = 1

        # add boxes
        self.boxes = [Models.box() for i in xrange(50)]
        offset = (75, 675)
        for i in range(50):
            self.boxes[i].status = 0
            self.boxes[i].x = offset[0] + i * int(L / 4)
            self.boxes[i].y = offset[1]

        agents_theta = 270
        battery_theta = agents_theta - 135
        # add agents
        self.agents = [Models.agent() for i in xrange(num_agents)]
        for r in range(num_agents):
            if r < num_agents / 2:
                self.agents[r].x = world_width / 2 - r * L
            else:
                self.agents[r].x = world_width / 2 + r * L
            self.agents[r].y = L
            self.agents[r].r = L / 4
            self.agents[r].status = 3  # all dead
            self.agents[r].color = 3
            self.agents[r].angle = Models.angle(agents_theta)
            self.agents[r].lastangle = agents_theta
            self.agents[r].agent_id = r

            self.agents[r].batteryangle1 = Models.angle(battery_theta)
            self.agents[r].batteryangle2 = Models.angle(battery_theta - 90)
            self.agents[r].batterystatus = 1

        # genetate graph
        self.graph_nodes = Graph.generateGraphNodes()
        self.graph = Graph.generateGraph()

        self.startPoints = [Models.point() for i in xrange(num_areas)]
        R1 = 'ABCDEF'
        for r in range(num_areas):
            self.startPoints[r].x = Graph.graph_nodes[R1[r]].x
            self.startPoints[r].y = Graph.graph_nodes[R1[r]].y
            self.startPoints[r].r = L / 3

        self.endPoints = [Models.point() for i in xrange(num_areas)]
        R1 = 'MNOPQR'
        for r in range(num_areas):
            self.endPoints[r].x = Graph.graph_nodes[R1[r]].x
            self.endPoints[r].y = Graph.graph_nodes[R1[r]].y
            self.endPoints[r].r = L / 3

        self.chargePoints = [Models.point() for i in xrange(num_areas)]
        R1 = 'STUVWY'
        for r in range(num_areas):
            self.chargePoints[r].x = Graph.graph_nodes[R1[r]].x
            self.chargePoints[r].y = Graph.graph_nodes[R1[r]].y - 5
            self.chargePoints[r].r = L / 3

        # initial agents start and goal position letter
        self.initstartgoal = InitStartGoal(self.agents)

        # set the plan strategy
        self.strategy = Strategy.Strategy(self.boxes, self.goods, self.agents,
                                          self.graph_nodes, self.graph)

        # set agent charge
        self.agentcharge = ChargeThreshold.AgentCharge(self.agents,
                                                       self.graph,
                                                       self.goods,
                                                       self.graph_nodes,
                                                       thresholdenergy=3.5,
                                                       consumingrate=0.005,
                                                       chargingrate=0.05)
Example #13
0
 def __init__():
     self.strategy = Strategy()
     self.uav = UAV()
Example #14
0
import json
import time
import calendar

dataFinal = {}
import matplotlib.pyplot as plt
from Strategy import *

stuff = []
stamps = []
with open("filed.json", "r") as tsla:
    strat = Strategy()
    for i in enumerate(tsla):
        data = json.loads(i[1])  #figure out later
        timeStamp = data["query"]["created"]
        timeStamp = calendar.timegm(
            time.strptime(timeStamp, "%Y-%m-%dT%H:%M:%SZ"))
        print strat.mean_strategy(data)
        stamps.append(timeStamp)
        stuff.append(data["query"]["results"]["quote"][0]["Ask"])
        dataFinal[timeStamp] = data["query"]["results"]["quote"][0]["Ask"]

plt.plot(stamps, stuff)
plt.show()
Example #15
0
 def addStrategy(self, stratName, entryCond, exitCond):
     self.strategy = strat.Strategy(stratName, entryCond, exitCond)
 """ # These comments can be removed if you want to download the data
 nyse = se.Securities('ticker_universe.csv',mkt_cap_cutoff)
 total_df = nyse.get_stock_data(start_date,end_date,data_source)
 total_df.to_csv('all_stocks_mktcap.csv')
 
 market_data = nyse.get_market_data(start_date,end_date,data_source)
 market_data.to_csv('Market_Index.csv')
 market_data['Date'] = market_data.index; market_data = market_data.reset_index(drop=True)
 """
 
 # These two statements are used to load already downloaded stock and market index data
 market_data = pd.read_csv('Market_Index.csv',parse_dates=['Date']);
 total_df_main = pd.read_csv('all_stocks_mktcap.csv',parse_dates = ['Date']); del total_df_main['Unnamed: 0']
 #-----------------------------------------------------------------------
 
 strategy = st.Strategy(train_date_start,train_date_end,test_date_start,test_date_end)
 pnl_train = 0; adr_train = 0; sr_train = 0; mdd_train = 0
 count = 0
 for n in nvalues:
     for m in mvalues:
         for L in Lvalues:
             for U in Uvalues: 
                 total_df = strategy.compute_factors(n,m,L,total_df_main)
                 weights = strategy.compute_factor_weights(total_df)
                 total_df['MScore'] = np.matmul(total_df.iloc[:,4:-1],weights)
                 
                 portfolio = pf.Portfolio(nstocks,init_portfolio_value,avg_trading_vol,tcost)
                 
                 train_df = total_df[(total_df['Date']>=pd.to_datetime(train_date_start)) & \
                                     (total_df['Date']<=pd.to_datetime(train_date_end))].reset_index(drop=True)
                 portfolio_df_train = portfolio.compute_portfolio_normal(train_date_start,train_date_end,train_df,U)
Example #17
0
from Strategy import *


class k():
    def __init__(self):
        self.value = -1


m = k()
b = Strategy()
b.best_strategy('.' * 27 + "ox......xo" + '.' * 27, '@', m)
print(m.value)
Example #18
0
    def __init__(self):

        #         self.goods_timestep_cnt = 0  # record the times
        self.collision_total_cnt = 0  # record the collisions
        self.collision_agents = []  # log the collision agents
        self.start_time_mark = 0
        self.stop_mark = 0
        self.start_time = 0

        # add shelves
        self.shelves = [Models.shelves() for i in xrange(21 * 8)]
        # put shelves in warehouse
        row1left = 0  # index the goods position  to mark letter
        row2left = 0
        row3left = 0
        row1right = 0
        row2right = 0
        row3right = 0

        for group in xrange(21):
            offset = (0, 0)
            if group % 3 == 0:  # row1
                offset = ((3 * (group / 3) + 1) * L + margin_left,
                          margin_top + L)
            elif group % 3 == 1:  # row2
                offset = ((3 * (group / 3) + 1) * L + margin_left,
                          margin_top + 6 * L)
            elif group % 3 == 2:  # row3
                offset = ((3 * (group / 3) + 1) * L + margin_left,
                          margin_top + 11 * L)

            # print "for good in group ", group, " Offset: ", offset
            for i in range(8):
                if (i % 2 == 0):  # on left
                    self.shelves[i + group * 8].id = i + group * 8
                    self.shelves[i + group * 8].status = 1
                    # every shelf has 10 class goods   goods_class_index
                    for goods_type in xrange(
                            self.shelves[i + group * 8].id * 10,
                            self.shelves[i + group * 8].id * 10 + 10):
                        self.shelves[i +
                                     group * 8].goods_class.append(goods_type)
                    self.shelves[i + group * 8].shelf_color = 'red'
                    self.shelves[i + group * 8].x = offset[0]
                    self.shelves[i + group * 8].y = offset[1] + int(i / 2) * L
                    self.shelves[i + group *
                                 8].agentx = self.shelves[i + group * 8].x - 25
                    self.shelves[i + group *
                                 8].agenty = self.shelves[i + group * 8].y + 25

                    if group % 3 == 0:  # row1
                        self.shelves[i + group *
                                     8].shelf_find_letter = ROW1_LEFT[row1left]
                    elif group % 3 == 1:  # row2
                        self.shelves[i + group *
                                     8].shelf_find_letter = ROW2_LEFT[row2left]
                    elif group % 3 == 2:  # row3
                        self.shelves[i + group *
                                     8].shelf_find_letter = ROW3_LEFT[row3left]

                elif (i % 2 == 1):  # on right
                    self.shelves[i + group * 8].id = i + group * 8
                    self.shelves[i + group * 8].status = 1
                    for goods_type in xrange(
                            self.shelves[i + group * 8].id * 10,
                            self.shelves[i + group * 8].id * 10 + 10):
                        self.shelves[i +
                                     group * 8].goods_class.append(goods_type)
                    self.shelves[i + group * 8].shelf_color = 'red'
                    self.shelves[i + group * 8].x = offset[0] + L
                    self.shelves[i + group * 8].y = offset[1] + int(i / 2) * L
                    self.shelves[i + group *
                                 8].agentx = self.shelves[i + group * 8].x + 75
                    self.shelves[i + group *
                                 8].agenty = self.shelves[i + group * 8].y + 25
                    if group % 3 == 0:  # row1
                        self.shelves[
                            i + group *
                            8].shelf_find_letter = ROW1_RIGHT[row1right]
                    elif group % 3 == 1:  # row2
                        self.shelves[
                            i + group *
                            8].shelf_find_letter = ROW2_RIGHT[row2right]
                    elif group % 3 == 2:  # row3
                        self.shelves[
                            i + group *
                            8].shelf_find_letter = ROW3_RIGHT[row3right]

            if group % 3 == 0:
                row1left += 1
                row1right += 1
            elif group % 3 == 1:
                row2left += 1
                row2right += 1
            elif group % 3 == 2:
                row3left += 1
                row3right += 1

        # generate graph
        self.graph_nodes = Graph.generateGraphNodes()
        self.graph = Graph.generateGraph()

        # the agent charging position and the box position
        self.chargePoints = [Models.point() for i in xrange(NUM_AGENTS)]

        agents_theta = -90
        battery_theta = agents_theta - 135
        # add agents
        self.agents = [Models.agent() for i in xrange(NUM_AGENTS)]
        for r in xrange(NUM_AGENTS):
            if r < NUM_AGENTS / 2:
                self.agents[r].x = world_width / 2 - r * L
            else:
                self.agents[r].x = world_width / 2 + r * L
            self.agents[r].y = L
            self.agents[r].r = L / 4
            self.agents[r].status = 3  # all dead
            self.agents[r].color = 3
            self.agents[r].angle = Models.angle(agents_theta)
            self.agents[r].last_angle = agents_theta
            self.agents[r].agent_id = r

            self.agents[r].battery_status = 1
            self.agents[r].battery_angle1 = Models.angle(battery_theta)
            self.agents[r].battery_angle2 = Models.angle(battery_theta - 90)

            self.chargePoints[r].x = Graph.graph_nodes[CHARGING_PARK[r]].x
            self.chargePoints[r].y = Graph.graph_nodes[CHARGING_PARK[r]].y
            self.chargePoints[r].r = L / 3

        # draw unloading mark
        self.orderPoints = [Models.point() for i in xrange(ORDER_NUM)]
        for r in xrange(ORDER_NUM):
            self.orderPoints[r].x = Graph.graph_nodes[UNLOADING_POSITION[r]].x
            self.orderPoints[r].y = Graph.graph_nodes[UNLOADING_POSITION[r]].y
            self.orderPoints[r].r = L / 3

        # draw the boxes
        self.orderBoxes = [Models.boxes() for i in xrange(ORDER_NUM)]
        for r in xrange(ORDER_NUM):
            offset = (self.orderPoints[r].x, self.orderPoints[r].y)
            self.orderBoxes[r].box_x = offset[0]
            self.orderBoxes[r].box_y = offset[1] + L

        # initial order
        self.orderGoods = [Models.orderGoods() for i in xrange(ORDER_NUM)]
        for r in xrange(ORDER_NUM):
            self.orderGoods[r].order_id = r
            self.orderGoods[r].order_class = GOODS_ORDER[r]
            self.orderGoods[r].unloading_position = UNLOADING_POSITION[r]

        # initial agents start and goal position letter task allocation
        self.initStartGoal = GA_allocate.GA_task_allocate(
            self.agents, self.shelves, self.orderGoods, self.graph_nodes,
            self.graph)

        # set the plan strategy
        self.strategy = Strategy.Strategy(self.shelves, self.agents,
                                          self.orderGoods, self.orderBoxes,
                                          self.graph_nodes, self.graph)

        # set agent charge
        self.agentCharge = ChargeThreshold.AgentCharge(self.agents,
                                                       self.graph,
                                                       self.shelves,
                                                       self.graph_nodes,
                                                       threshold_energy=3,
                                                       consuming_rate=0.0001,
                                                       charging_rate=0.05)
Example #19
0
def timerFired(app):
    if app.isPaused == False and app.gameOver == False and app.gamePage == False:
        if app.spectateMode == True:
            s = Strategy.Strategy()
            s2 = StrategyMed.Strategy()
            if "." in app.board:
                if len(possibleMoves(app.board, app.playerSymbol)) == 0:
                    createSpectatorMatrix(app)
                else:
                    if app.playerSymbol == "@":
                        cpu_move = s.best_strategy(app.board, app.playerSymbol)
                        app.board = move(app.board, app.playerSymbol, cpu_move)
                        score(app)
                        createSpectatorMatrix(app)
                    else:
                        app.board, index = randommove(app.board, app.playerSymbol)
                        score(app)
                        createSpectatorMatrix(app)
                app.playerSymbol = "o" if app.playerSymbol == "@" else "@"
            elif "." not in app.board:
                score(app)
                app.gameOver = True

        elif app.aiOneMode == True:
            if "." in app.board:
                if len(possibleMoves(app.board, app.playerSymbol)) == 0:
                    app.turnSwap = True
                    app.moveAssist = (-1, -1)
                    createMatrix(app)
                else:
                    if app.playerSymbol == "@":
                        #player's turn
                        moves = possibleMoves(app.board, app.playerSymbol)
                        player_move = app.click
                        
                        if player_move in app.moves:
                            app.turnSwap = True
                            app.moveAssist = (-1, -1)
                            app.board = move(app.board, app.playerSymbol, (player_move[0]*10) + player_move[1])
                            app.moves.clear()
                            score(app)
                            createMatrix(app)
                    elif app.playerSymbol == "o":
                        #ai's turn
                        app.board, index = randommove(app.board, app.playerSymbol)
                        app.moves.clear()
                        moves = possibleMoves(app.board, "@")
                        for i in range(len(moves)):
                            app.moves.append((moves[i]//10, moves[i]%10))
                        createMatrix(app)
                        app.turnSwap = True
                        app.moveAssist = (-1, -1)
                        score(app)
                if app.turnSwap:
                    app.playerSymbol = "o" if app.playerSymbol == "@" else "@"
                    app.turnSwap = False
            elif "." not in app.board:
                score(app)
                app.gameOver = True

        elif app.aiTwoMode:
            s = StrategyMed.Strategy()
            if "." in app.board:
                if len(possibleMoves(app.board, app.playerSymbol)) == 0:
                    app.turnSwap = True
                    app.moveAssist = (-1, -1)
                    createMatrix(app)
                else:
                    if app.playerSymbol == "@":
                        moves = possibleMoves(app.board, app.playerSymbol)
                        player_move = app.click
                        if player_move in app.moves:
                            app.turnSwap = True
                            app.board = move(app.board, app.playerSymbol, (player_move[0]*10) + player_move[1])
                            app.moveAssist = (-1, -1)
                            app.moves.clear()
                            score(app)
                            createMatrix(app)
                    if app.playerSymbol == "o":
                        cpu_move = s.best_strategy(app.board, app.playerSymbol)
                        app.board = move(app.board, app.playerSymbol, cpu_move)
                        app.moves.clear()
                        moves = possibleMoves(app.board, "@")
                        for i in range(len(moves)):
                            app.moves.append((moves[i]//10, moves[i]%10))
                        createMatrix(app)
                        app.turnSwap = True
                        app.moveAssist = (-1, -1)
                        score(app)
                if app.turnSwap:
                    app.playerSymbol = "o" if app.playerSymbol == "@" else "@"
                    app.turnSwap = False
            elif "." not in app.board:
                score(app)
                app.gameOver = True

        elif app.aiThreeMode:
            s = Strategy.Strategy()
            if "." in app.board:
                if len(possibleMoves(app.board, app.playerSymbol)) == 0:
                    app.turnSwap = True
                    app.moveAssist = (-1, -1)
                    createMatrix(app)
                else:
                    if app.playerSymbol == "@":
                        moves = possibleMoves(app.board, app.playerSymbol)
                        player_move = app.click
                        if player_move in app.moves:
                            app.turnSwap = True
                            app.board = move(app.board, app.playerSymbol, (player_move[0]*10) + player_move[1])
                            app.moveAssist = (-1, -1)
                            app.moves.clear()
                            score(app)
                            createMatrix(app)
                    if app.playerSymbol == "o":
                        cpu_move = s.best_strategy(app.board, app.playerSymbol)
                        app.board = move(app.board, app.playerSymbol, cpu_move)
                        app.moves.clear()
                        moves = possibleMoves(app.board, "@")
                        for i in range(len(moves)):
                            app.moves.append((moves[i]//10, moves[i]%10))
                        createMatrix(app)
                        app.turnSwap = True
                        app.moveAssist = (-1, -1)
                        score(app)
                if app.turnSwap:
                    app.playerSymbol = "o" if app.playerSymbol == "@" else "@"
                    app.turnSwap = False
            elif "." not in app.board:
                score(app)
                app.gameOver = True

        elif app.pvpMode:
            if "." in app.board:
                if len(possibleMoves(app.board, app.playerSymbol)) == 0:
                    #equivalent to passing if no legal moves
                    app.turnSwap = True
                    createMatrix(app)
                else:
                    if app.playerSymbol == "@":
                    #p1's (black) turn
                        player_move = app.click
                        if player_move in app.blackMoves:
                            app.turnSwap = True
                            app.board = move(app.board, app.playerSymbol, (player_move[0]*10) + player_move[1])
                            score(app)
                        app.whiteMoves.clear()
                        whiteMoves = possibleMoves(app.board, "o")
                        for i in range(len(whiteMoves)):
                            #clear previous white legal moves and calculate future white legal moves
                            app.whiteMoves.append((whiteMoves[i]//10, whiteMoves[i]%10))
                    elif app.playerSymbol == "o":
                    #p2's (white) turn
                        player_move = app.click
                        if player_move in app.whiteMoves:
                            app.turnSwap = True
                            app.board = move(app.board, app.playerSymbol, (player_move[0]*10) + player_move[1])
                            score(app)
                        app.blackMoves.clear()
                        blackMoves = possibleMoves(app.board, "@")
                        for i in range(len(blackMoves)):
                            #clear previous black legal moves and calculate future black legal moves
                            app.blackMoves.append((blackMoves[i]//10, blackMoves[i]%10))
                if app.turnSwap:
                    #swaps turns
                    if app.playerSymbol == "@":
                        app.playerSymbol = "o"
                    elif app.playerSymbol == "o":
                        app.playerSymbol = "@"
                    app.turnSwap = False
                    createPvPMatrix(app)
            elif "." not in app.board:
                #if no more spots
                score(app)
                app.gameOver = True
Example #20
0
"""
多单swap-12.09与空单swap6.527取自2019年2月某刻数据
"""
from Strategy import *
from Transactions import *
import pandas as pd

result = pd.DataFrame()
s = []
t = []
for i in range(0, 30):
    print(round((i + 1) * 0.1, 1))
    s.append(
        Strategy(
            pd.read_csv('D:/graduate/TheSecondElement/History/XAUUSD60.csv'),
            30, 100, -12.09, 6.527, 300000))
    s[i].setStrategyAugment((i + 1) * 0.1, 12, 26, 24)
    transactions = s[i].getTransactions()
    t.append(Transactions(transactions))
    t[i].caculateDetails()
    t[i].caculateAboutDrawDown()
    openTradesHistory = s[i].openTradesHistory
    days = t[i].days
    drawDown = t[i].drawDown
    result.at[i, 'R'] = (i + 1) * 0.1
    result.at[i, '年收益'] = t[i].netProfitPerYear
    result.at[i, '最大衰落金额'] = drawDown.describe().loc['max']['drawDown']
    result.at[i, 'MAR'] = result.at[i, '年收益'] / result.at[i, '最大衰落金额']
    result.at[i, '期望'] = t[i].expectedPayOff
    result.at[i, '最大衰落期'] = drawDown.describe().loc['max']['drawDownPeriod']
    result.at[i, '胜率'] = t[i].profitTradesRate
Example #21
0
                     Tools.sqlScale,
                     codeList,
                     csMap=None,
                     fieldNum=Tools.numScale,
                     label='scale')
mkt.CreateDataSource(connStr,
                     Tools.sqlBm, [2060002293],
                     csMap=None,
                     fieldNum=Tools.numBm,
                     label='INDEX')

random.shuffle(scaleStockCodeList[0])
random.shuffle(scaleStockCodeList[1])
random.shuffle(scaleStockCodeList[2])
random.shuffle(scaleStockCodeList[3])
allCode = []
allCode.extend(scaleStockCodeList[0])
allCode.extend(scaleStockCodeList[1])
allCode.extend(scaleStockCodeList[2])
random.shuffle(allCode)

# ssc = allCode
ssc = allCode[0:100]
# ssc = scaleStockCodeList[0]
# ssc = scaleStockCodeList[1][0 : 100]
# ssc = scaleStockCodeList[2][0 : 100]

stg = Strategy.Strategy(codeList, csMap, 200, mkt, ssc)
mkt.AddAfterCloseReceiver(stg.NewDayHandler)
mkt.AddAfterCloseReceiver(stg.da.NewDayHandler)
Example #22
0
"""
多单swap-12.09与空单swap6.527取自2019年2月某刻数据
"""
from Strategy import *
from Transactions import *
import pandas as pd

result = pd.DataFrame()
s = []
t = []
for i in range(0, 30):
    print(round((i + 1) * 0.1, 1))
    s.append(
        Strategy(pd.read_csv('F:/小宇宙/R/History/GBPUSD60.csv'), 30, 100000,
                 -7.44, 3.37, 300000))
    s[i].setStrategyAugment((i + 1) * 0.1, 12, 26, 24)
    transactions = s[i].getTransactions()
    t.append(Transactions(transactions))
    t[i].caculateDetails()
    t[i].caculateAboutDrawDown()
    openTradesHistory = s[i].openTradesHistory
    days = t[i].days
    drawDown = t[i].drawDown
    result.at[i, 'R'] = (i + 1) * 0.1
    result.at[i, '年收益'] = t[i].netProfitPerYear
    result.at[i, '最大衰落金额'] = drawDown.describe().loc['max']['drawDown']
    result.at[i, 'MAR'] = result.at[i, '年收益'] / result.at[i, '最大衰落金额']
    result.at[i, '期望'] = t[i].expectedPayOff
    result.at[i, '最大衰落期'] = drawDown.describe().loc['max']['drawDownPeriod']
    result.at[i, '胜率'] = t[i].profitTradesRate
    result.at[i, '盈利月占比'] = len(
Example #23
0
import gongcq.Market as Market
import gongcq.CodeSymbol as CodeSymbol
import Strategy
import datetime as dt

root = 'E:\\TEMP\\l2_sample_day'
connStr = 'reader/[email protected]:1521/dbcenter'
sqlPrc = "SELECT TRADE_DATE, STK_UNI_CODE, CLOSE_PRICE, CLOSE_PRICE_RE, RISE_DROP_RANGE_RE / 100, OPEN_PRICE, OPEN_PRICE_RE, STK_TOT_VALUE,  TRADE_AMUT, STK_CIR_VALUE, TURNOVER_RATE " \
         "FROM UPCENTER.STK_BASIC_PRICE_MID " \
         "WHERE ISVALID = 1 AND TRADE_VOL > 0 AND TRADE_DATE = TO_DATE('{TRADE_DATE}', 'YYYY-MM-DD') "
sqlCld = "SELECT MIN(C.END_DATE) " \
         "FROM UPCENTER.PUB_EXCH_CALE C " \
         "WHERE C.IS_TRADE_DATE = 1 AND C.SEC_MAR_PAR = 1 AND " \
         "      C.END_DATE > TO_DATE('{LAST_DATE}', 'YYYY-MM-DD') " \
         "ORDER BY END_DATE"
csMap = CodeSymbol.CodeSymbol(connStr)
codeList, symbolList, nameList, mktList = CodeSymbol.GetAllCode(connStr)
mkt = Market.Market(connStr, sqlCld, dt.datetime(2017, 4, 4))
mkt.CreateDataSource(connStr, sqlPrc, codeList, csMap, 11)
mkt.CreateDataSource(root, None, codeList, csMap, 198)
mkt.CreateAccount(0, 1000000)
stg = Strategy.Strategy(codeList, csMap, 50)
mkt.AddAfterCloseReceiver(stg.da.NewDayHandler)
mkt.AddAfterCloseReceiver(stg.NewDayHandler)
Example #24
0
#!/bin/env python2.6
import json
import time
import calendar
dataFinal = {}
import matplotlib.pyplot as plt
from Strategy import *
stuff = []
stamps = []
with open("filed.json","r") as tsla:
    amount = 1000
    strat = Strategy(amount)
    print "Start with $"+str(amount)
    final_val = 0
    for i in enumerate(tsla):
	try:
            data = json.loads(i[1]) #figure out later
	except ValueError:
	    pass
        strat.mean_strategy(data)
        timeStamp = data["query"]["created"]
        timeStamp = calendar.timegm(time.strptime(timeStamp,"%Y-%m-%dT%H:%M:%SZ"))
       # print strat.mean_strategy(data)
        final_val = data
    strat.sellAll(data)
    print "Ended with $"+str(strat.printDatMoney())
Example #25
0
 def __init__(self, strategy, rules):
     self.strategy = Strategy(strategy, rules)
     name = strategy + " Strategy Player"
     Player.__init__(self, name)
Example #26
0
 def __init__(self):
     arr = [random.randint(0, 1) for _ in range(70)]
     self.genes = Strategy(arr)
     self.fitness = 0