Example #1
0
    def doPredict(self, data: StockData) -> float:
        """
        Use the loaded trained neural network to predict the next stock value.
    
        Args:
          data: historical stock values of a company

        Returns:
          predicted next stock value for that company
        """
        #self.model.compile(loss='mean_squared_error', optimizer='sgd')
        tmp_data = data.get_from_offset(data.get_row_count() - 5)
        tmp = np.array([[
            tmp_data[0][1], tmp_data[1][1], tmp_data[2][1], tmp_data[3][1],
            tmp_data[4][1]
        ]])

        pred = self.model.predict(tmp)

        res = data.get_last()[1]

        if (pred <= 0.5):
            res = res * 0.9
        else:
            res = res * 1.1

        # TODO: extract needed data for neural network and predict result
        return res
Example #2
0
    def doPredict(self, data: StockData) -> float:
        """
        Use the loaded trained neural network to predict the next stock value.

        Args:
          data: The historical stock values of a company

        Returns:
          The predicted next stock value for that company
        """
        # Assumptions about data: at least INPUT_SIZE pairs of type (_, float)
        assert data is not None and data.get_row_count() >= INPUT_SIZE

        # Extract last INPUT_SIZE floats (here: stock values) as input for neural network
        # (format: numpy array of arrays)
        input_values = np.array([[x[1] for x in data.get_from_offset(-INPUT_SIZE)]])

        normalized_prices = []

        vector_min = np.min(input_values)
        vector_max = np.max(input_values)

        for price in input_values:
            normalized_prices.append((price - vector_min) / (vector_max - vector_min))

        input_values = np.asarray(normalized_prices)

        try:
            # Let network predict the next stock value based on last 100 stock values
            prediction = self.model.predict(input_values)[0][0]
            return data.get_last()[1] + calculate_delta(prediction)
        except:
            logger.error("Error in predicting next stock value.")
            assert False
Example #3
0
def learn_nn_and_save(training_data: StockData, test_data: StockData,
                      filename_to_save: str):
    network = create_model()

    # TODO: learn network and draw results

    #np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)

    x_train = np.array([])
    y_train = np.array([])

    i = 0
    batch = 5
    while i < training_data.get_row_count() - batch:
        tmp = np.array([])
        for j in range(0, batch):
            i = i + 1
            diff = training_data.get(i)[1] - training_data.get(i + 1)[1]
            tmp = np.insert(tmp, j, diff)

        diff_y = 0
        if (i < training_data.get_row_count() - 1):
            diff_y = training_data.get(i - 1)[1] - training_data.get(i)[1]

        if (diff_y > 0):
            y_train = np.append(y_train, 1)
        else:
            y_train = np.append(y_train, 0)

        x_train = np.append(x_train, tmp, axis=0)

    x_train = x_train.reshape((int(x_train.shape[0] / 5), 5))
    y_train = y_train.reshape((-1, 1))

    #for i in range(0, training_data.get_row_count() - 1):
    #    diff = training_data.get(i)[1] - training_data.get(i + 1)[1]

    #    if (diff < 0):
    #        y_train.append([1])
    #    else:
    #        y_train.append([0])

    network.compile(loss='mean_squared_error', optimizer='sgd')
    network.fit(x_train, y_train, epochs=10, batch_size=5)

    # Save trained model: separate network structure (stored as JSON) and trained weights (stored as HDF5)
    save_keras_sequential(network, RELATIVE_PATH, filename_to_save)
Example #4
0
    def doPredict(self, data: StockData) -> float:
        """ Use the loaded trained neural network to predict the next stock value.
    
        Args:
          data: The historical stock values of a company

        Returns:
          The predicted next stock value for that company
        """
        # Assumptions about data: at least 100 pairs of type (_, float)
        assert data is not None and data.get_row_count() >= 100

        # Extract last 100 floats (here: stock values) as input for neural network (format: numpy array of arrays)
        input_values = np.array([[x[1] for x in data.get_from_offset(-100)]])

        try:
            # Let network predict the next stock value based on last 100 stock values
            return self.model.predict(input_values)
        except:
            logger.error("Error in predicting next stock value.")
            assert False
Example #5
0
    def doPredict(self, data: StockData) -> float:
        """
        Use the loaded stock values to predict the next stock value.
    
        Args:
          data: historical stock values

        Returns:
          predicted next stock value for that company
        """
        # Assumptions about data: at least one pair of type (_, float)
        assert data is not None and data.get_row_count() > 0

        (current_date, current_value) = data.get_last()
        index = self.stock_data.index((current_date, current_value))
        if index is not None and index < self.stock_data.get_row_count() - 1:
            (_, next_value) = self.stock_data.get(index + 1)
            return next_value
        else:
            logger.error(
                f"Couldn't make a perfect prediction for the day after {current_date}"
            )
            assert False