Esempio n. 1
0
    def close_position(self, position: Position):
        cur_price = self.current_window.get_data(
            tickers=[position.asset1, position.asset2],
            features=[Features.CLOSE])
        if not (position in self.cur_positions):
            print("do not have this position open")
        else:
            print(
                f"{position.closingtype} threshold is passed for active pair {position.asset1}, "
                f"{position.asset2}. Closing position...")
            self.cur_positions.remove(position)

            asset1_value = cur_price.iloc[-1, 0] * position.quantity1
            asset2_value = cur_price.iloc[-1, 1] * position.quantity2
            commission = self.generate_commission(asset1_value, asset2_value)
            pair_residual_cash = asset1_value + asset2_value

            position.close_trade(pair_residual_cash, self.current_window)
            self.cur_cash += pair_residual_cash - commission
            self.active_port_value -= pair_residual_cash
            self.realised_pnl += position.pnl
            print(
                f'Asset 1: {position.asset1} @${round(cur_price.iloc[-1, 0], 2)}'
                f' Quantity: {int(position.quantity1)}')
            print(
                f'Asset 2: {position.asset2} @${round(cur_price.iloc[-1, 1], 2)} '
                f'Quantity: {int(position.quantity2)}')
            print(f'Realised PnL for position: {round(position.pnl, 2)}')
Esempio n. 2
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))
class Snake:
    def __init__(self, x_position: int, y_position: int):
        self.length = 0
        self.position = Position(x_position, y_position)

    def move_x(self, move_x: int):
        self.position.move_x(move_x)

    def move_y(self, move_y: int):
        self.position.move_y(move_y)
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
0
    def open_position(self, position: Position):
        cur_price = self.current_window.get_data(
            tickers=[position.asset1, position.asset2],
            features=[Features.CLOSE])
        # notional reference amount for each pair. Actual positions are scaled accordingly with respect to
        # maximum weight as per below formula
        pair_dedicated_cash = self.init_cash * self.single_pair_loading / max(
            abs(position.weight1), abs(position.weight2))
        position.quantity1 = int(pair_dedicated_cash * position.weight1 /
                                 cur_price.iloc[-1, 0])
        position.quantity2 = int(pair_dedicated_cash * position.weight2 /
                                 cur_price.iloc[-1, 1])
        asset1_value = cur_price.iloc[-1, 0] * position.quantity1
        asset2_value = cur_price.iloc[-1, 1] * position.quantity2
        commission = self.generate_commission(asset1_value, asset2_value)
        pair_dedicated_cash = asset1_value + asset2_value
        position.set_position_value(pair_dedicated_cash)
        if pair_dedicated_cash > self.cur_cash:
            print('No sufficient cash to open position')
        else:
            print(
                f"{position.asset1}, {position.asset2} "
                f"are cointegrated and zscore is in trading range. Opening position...."
            )
            self.cur_positions.append(position)
            self.hist_positions.append(position)

            self.cur_cash -= (pair_dedicated_cash + commission)
            self.active_port_value += pair_dedicated_cash
            print(
                f'Asset 1: {position.asset1} @${round(cur_price.iloc[-1, 0], 2)} '
                f'Quantity: {round(position.quantity1, 2)} Value: {round(asset1_value, 2)}'
            )
            print(
                f'Asset 2: {position.asset2} @${round(cur_price.iloc[-1, 1], 2)} '
                f'Quantity: {round(position.quantity2, 2)} Value: {round(asset2_value, 2)}'
            )
            print(f'Cash balance: ${self.cur_cash}')
Esempio n. 7
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)
Esempio n. 9
0
 def test_put(self):
     self.assertEqual(Action.put(1, 1, Position(Piece("a"), Player("a"))),
                      "put: (%d, %d, %s)" % (1, 1, "a"))
Esempio n. 10
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
Esempio n. 11
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))
Esempio n. 12
0
 def __init__(self, x: int, y: int):
     self.position = Position(x, y)
     self.murs = {'N': True, 'S': True, 'E': True, 'O': True}
Esempio n. 13
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()
Esempio n. 14
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