示例#1
0
 def setUp(self):
     self.player = Player("player")
     self.player.history.append(
         Action.put(1, 1, Position(Piece("a"), Player("a"))))
     self.player.history.append(
         Action.put(1, 2, Position(Piece("a"), Player("a"))))
     self.player.history.append(Action.see(1, 1))
示例#2
0
    def load_from_json(self, file_name: str) -> bool:
        """
       Loads a graph from a json file.
       @param file_name: The path to the json file
       @returns True if the loading was successful, False o.w.
       """
        try:
            with open(file_name, 'r') as file1:
                data1 = json.load(file1)
            for node in data1['Nodes']:
                if "pos" in node:
                    pos1 = node["pos"]
                    p = str(pos1)
                    p = p.replace("[", "")
                    p = p.replace("'", "")
                    p = p.replace("]", "")
                    p = p.replace("'", "")
                    p = tuple(p.split(","))
                    pos = Position(p)
                    self.graph.add_node(node['id'], pos)
                else:
                    self.graph.add_node(node['id'])
                for edge in data1['Edges']:
                    self.graph.add_edge(edge["src"], edge["dest"], edge["w"])
            return True

        except IOError as e:
            raise e
            return False
示例#3
0
def test_should_change_position_when_move_called():
    position = Position(X_POSITION_VALUE, Y_POSITION_VALUE)
    position.move_x(X_MOVE_BY)
    position.move_y(Y_MOVE_BY)

    assert position.x_position == X_POSITION_VALUE + X_MOVE_BY
    assert position.y_position == Y_POSITION_VALUE + Y_MOVE_BY
示例#4
0
    def generate_pairs(self, clustering_results: Dict[int,
                                                      Tuple[Tuple[Tickers]]],
                       hurst_exp_threshold: float, current_window: Window):
        # run cointegration_analysis on all poss combinations of pairs within the same cluster

        current_cointegrated_pairs = []
        n_cointegrated = 0
        tickers_per_cluster = [i for i in clustering_results.values()]

        for cluster in tickers_per_cluster:
            for pair in itertools.combinations(list(cluster), 2):
                t1 = current_window.get_data(tickers=[pair[0]],
                                             features=[Features.CLOSE])
                t2 = current_window.get_data(tickers=[pair[1]],
                                             features=[Features.CLOSE])
                try:
                    # sometimes there are no price data, in which case, skip
                    residuals, beta, reg_output = self.__logged_lin_reg(t1, t2)
                except ValueError:
                    continue
                adf_test_statistic, adf_critical_values = self.__adf(
                    residuals.flatten())
                hl_test = self.__hl(residuals)
                he_test = self.__hurst_exponent_test(residuals, current_window)
                ou_mean, ou_std, ou_diffusion_v, \
                recent_dev, recent_dev_scaled = self.__ou_params(residuals)
                ols_stdzed_residuals = (residuals - ou_mean) / ou_std
                is_cointegrated = self.__acceptance_rule(
                    adf_test_statistic,
                    adf_critical_values,
                    self.adf_confidence_level,
                    hl_test,
                    self.max_mean_rev_time,
                    he_test,
                    hurst_exp_threshold,
                    ols_stdzed_residuals,
                    at_least=int(current_window.window_length.days / 6))
                if is_cointegrated:
                    #a = pd.concat([t1, t2], axis=1).iplot(asFigure=True)
                    #b = pd.concat([np.log(t1), np.log(t2)], axis=1).iplot(asFigure=True)
                    #a.show()
                    #b.show()
                    n_cointegrated += 1
                    t1_most_recent = float(t1.iloc[-1, :])
                    t2_most_recent = float(t2.iloc[-1, :])
                    hedge_ratio = beta * t1_most_recent / t2_most_recent
                    scaled_beta = hedge_ratio / (hedge_ratio - 1)
                    recent_dev_scaled_hist = [recent_dev_scaled]
                    cointegration_rank = self.__score_coint(
                        adf_test_statistic, self.adf_confidence_level,
                        adf_critical_values, he_test, hurst_exp_threshold, 10)
                    #a = pd.DataFrame(ols_stdzed_residuals).iplot(asFigure=True)
                    #a.show()
                    position = Position(pair[0], pair[1])
                    current_cointegrated_pairs.append(
                        CointegratedPair(pair, reg_output, scaled_beta,
                                         hl_test, ou_mean, ou_std,
                                         ou_diffusion_v, recent_dev,
                                         recent_dev_scaled,
                                         recent_dev_scaled_hist,
                                         cointegration_rank,
                                         ols_stdzed_residuals, position))

                    if n_cointegrated == self.target_number_of_coint_pairs:
                        current_cointegrated_pairs = sorted(
                            current_cointegrated_pairs,
                            key=lambda coint_pair: coint_pair.
                            cointegration_rank,
                            reverse=True)
                        self.previous_cointegrated_pairs = current_cointegrated_pairs
                        return current_cointegrated_pairs

        self.previous_cointegrated_pairs = current_cointegrated_pairs
        return current_cointegrated_pairs
 def __init__(self, x_position: int, y_position: int):
     self.length = 0
     self.position = Position(x_position, y_position)
示例#6
0
 def test_put(self):
     self.assertEqual(Action.put(1, 1, Position(Piece("a"), Player("a"))),
                      "put: (%d, %d, %s)" % (1, 1, "a"))
示例#7
0
 def MouseClick(self, x: int, y: int, button: Button, pressed) -> bool:
     mouseEvent = MouseEvent(button, Position(x, y), pressed)
     self.events.append(mouseEvent)
     if not pressed:
         return False  # Stop listener
示例#8
0
 def setUp(self):
     self.game = Game(Player("a"), Player("b"), Board("go"))
     self.game.player1.record(
         Action.put(1, 1, Position(Piece("a"), Player("a"))))
     self.game.player1.record(Action.see(1, 1))
示例#9
0
 def __init__(self, x: int, y: int):
     self.position = Position(x, y)
     self.murs = {'N': True, 'S': True, 'E': True, 'O': True}
示例#10
0
    def plot_graph(self) -> None:
        """
        this function plot a graph by the matplotlib of python.
        it plot the nodes according the positions, and if the node has no position the function choose random
        position according an algorithm, we wrote.
        """
        x1_vals = []
        y1_vals = []
        ax = plt.axes()
        plt.title("Graph")
        for key1 in self.graph.get_all_v().keys():
            pos1 = self.graph.get_vertex(key1).pos
            if pos1 is not None:  # if pos isn't exist
                x1 = pos1[0]
                y1 = pos1[1]
                x1_vals.append(float(x1))
                y1_vals.append(float(y1))

        for key1 in self.graph.get_all_v().keys():
            pos1 = self.graph.get_vertex(key1).pos
            if pos1 is None:
                list1 = []
                list2 = []
                if len(x1_vals) < 2 and len(y1_vals) < 2:  # if there is no bounding box
                    x1 = random.uniform(32.000, 33.000)
                    while x1 in list1:
                        x1 = random.uniform(32.000, 33.000)
                    list1.append(x1)
                    y1 = random.uniform(35.000, 36.000)
                    while y1 in list2:
                        y1 = random.uniform(35.000, 36.000)
                    list2.append(y1)
                    x1_vals.append(x1)
                    y1_vals.append(y1)
                else:
                    x1, y1 = self.pos_avr(x1_vals, y1_vals)
                    x1_vals.append(x1)
                    y1_vals.append(y1)
                pos4 = x1, y1, 0.0
                self.graph.get_vertex(key1).pos = Position(pos4)

        for i in range(len(x1_vals)):
            plt.plot(x1_vals[i], y1_vals[i], 'o', markersize=4, color='pink',
                     markerfacecolor='blue')  # TODO:SHOULD check implement
            print(x1_vals[i])
            print(y1_vals[i])

        for key1 in self.graph.get_all_v().keys():
            pos = self.graph.get_vertex(key1).pos
            x1 = pos[0]
            y1 = pos[1]
            for key2 in self.graph.all_out_edges_of_node(key1):
                if self.graph.get_vertex(key2) is not None:
                    pos1 = self.graph.get_vertex(key2).pos
                    x2 = pos1[0]
                    y2 = pos1[1]
                    plt.arrow(float(x1), float(y1), float(x2) - float(x1), float(y2) - float(y1),
                              width=0.00002, head_width=0.0001, linewidth=0.1)
        n = []
        for key in self.graph.get_all_v().keys():
            n.append(key)

        for i, txt in enumerate(n):
            ax.annotate(n[i], (x1_vals[i], y1_vals[i]))
        plt.show()
示例#11
0
def test_construct_position_object_with_passed_values():
    position = Position(X_POSITION_VALUE, Y_POSITION_VALUE)

    assert position.x_position == X_POSITION_VALUE
    assert position.y_position == Y_POSITION_VALUE