Exemple #1
0
def toggleAgentSubscription(modelData):
    """Method to subscribe and unsubscribe to agents

    Parameters
    ----------
    modelData: dict
        The specifications of the agent
    """

    template = "{}/{}"
    with open(template.format(modelData["savePath"], "AgentInfo.json")) as f:
        agentInfo = json.load(f)
    if modelData["subscribe"]:
        # TODO: Implement subscribe methods
        agentInfo["subscribed"] = modelData["subscribe"]
        job = sj(modelData["agentName"], modelData["savePath"])
        job.save()
        job.scheduleJob()
        message = ("Successfully subscribed"
                   " to {}").format(modelData["agentName"])
        tbot.sendMessage(message)
    else:
        # TODO: Implement unsubscribe methods
        agentInfo["subscribed"] = modelData["subscribe"]
        baseClass = modelData["savePath"].split("/")[-2]
        subscriptionName = "{}.{}".format(baseClass, modelData["agentName"])
        jobs.deleteSubscription(subscriptionName)
        message = ("Successfully unsubscribed"
                   " from {}").format(modelData["agentName"])
        tbot.sendMessage(message)

    with open(template.format(modelData["savePath"], "AgentInfo.json"),
              "w+") as f:
        json.dump(agentInfo, f)
Exemple #2
0
def afterTrainProcedure(history, modelData):
    """Method to ask user if the model is to be retrained

    Sometimes when the callback is triggered, the model wouldn't have really
    reached the optimum. It may be beneficial to train once more till the
    call back is triggered again.

    Parameters
    ----------
    history: dict
        The values of the specified metrics after training.
        Metrics may include MSE, Loss etc,...
    modelData: dict
        The model parameters as specified in the UI
    """
    global lastTrainedModelData

    try:
        if "mse" in history.keys():
            key = "mse"
        else:
            key = "mean_squared_error"
        valMSE = history["val_{}".format(key)][-1]
        trainMSE = history[key][-1]
        message = ("The early stop callback was triggered for {}. The final "
                   "trainMSE = {:.3} and valMSE = {:.3}. Do you want to "
                   "retrain the model? (yes/no)")
        tbot.sendMessage(
            message.format(modelData["modelName"], trainMSE, valMSE))
        tbot.retrainFilter.toggleRetrain = True
        lastTrainedModelData = modelData
    except Exception:
        message = "The early stop callback was triggered for {}"
        tbot.sendMessage(message.format(modelData["modelName"]))
        traceback.print_exc()
Exemple #3
0
    def task(self):
        """Defines the tasks to be done when subscribed

        The set of tasks include,
            1. Downloading and saving the new ticker data
            2. Inferencing
            3. Messaging the root about the action
        """
        self.updateStockData()
        tickerActions = {}
        for ticker in self.tickers:
            data = self.getTickerData(ticker,
                                      self.agent.dataProcessor.interval)
            context = {"ticker": ticker, "isTrain": False}
            buy, sell, hold = self.agent.getAllActions(data, context)
            if buy[0] == 1:
                # buy action
                action = "Buy"
            elif sell[0] == 1:
                # sell action
                action = "Sell"
            elif hold[0] == 1:
                # hold action
                action = "Hold"
                continue
            tickerActions[ticker] = {}
            tickerActions[ticker]["action"] = action
            tickerActions[ticker]["price"] = data["Close"].values[-1]

        message = self.generateMessage(self.name, tickerActions)
        if message:
            bot.sendMessage(message)
Exemple #4
0
def retrainForecaster():
    """Method to retrain the model
    """
    moduleLoc = lastTrainedModelData["moduleLoc"]
    model = lastTrainedModelData["model"]
    modelName = lastTrainedModelData["modelName"]
    model = getModelClass(moduleLoc, model)
    model = model()
    model.loadModel(modelName)
    tbot.sendMessage("Retraining {}".format(modelName))
    history = trainAndSaveForecaster(model, lastTrainedModelData["modelName"])

    afterTrainProcedure(history, lastTrainedModelData)
Exemple #5
0
def createForecaster(modelData):
    """Method to create the forecaster specified by the UI

    Parameters
    ----------
    modelData: dict
        The details of the forecaster as specified from
        the UI
    """
    try:
        model = getModelClass(modelData["moduleLoc"], modelData["model"])
    except Exception:
        # TODO: Implementing a logger
        message = "There was an error creating {}. Please check logs"
        tbot.sendMessage(message.format(modelData["modelName"]))
        traceback.print_exc()
        return

    model = model()

    try:
        model = buildForecaster(modelData, model)
    except Exception:
        # TODO: Implement logger
        message = "There was an error creating {}. Please check logs"
        tbot.sendMessage(message.format(modelData["modelName"]))
        traceback.print_exc()
        return

    tbot.sendMessage("{} is now training".format(modelData["modelName"]))
    try:
        history = trainAndSaveForecaster(model, modelData["modelName"])
    except Exception:
        message = ("There was an error while training {}. Please check"
                   "logs.")
        tbot.sendMessage(message.format(modelData["modelName"]))
        traceback.print_exc()
        return

    afterTrainProcedure(history, modelData)