Beispiel #1
0
def showPlot(root, statistics=None, canvas=None):
    global ARRAY_LENGTHS, ARRAY_TIMES
    figure = Figure(figsize=(5, 4), dpi=100)
    if len(ARRAY_TIMES) == 0:
        statistics = [0, 0]
    else:
        statistics = [ARRAY_LENGTHS, ARRAY_TIMES]
    figure.add_subplot(111).plot(statistics[0],
                                 statistics[1],
                                 color='black',
                                 linestyle='dashed',
                                 marker='o',
                                 markerfacecolor='red',
                                 markersize=7)
    figure.add_subplot(111).set_xlabel('количество N')
    figure.add_subplot(111).set_ylabel('время t')
    if canvas is None:
        canvas = FigureCanvasTkAgg(figure, master=root)
        canvas.draw()
        canvas.get_tk_widget().grid(row=1, column=4, rowspan=2)
    else:
        canvas.figure = figure
        canvas.draw()
        canvas.get_tk_widget().update()
    return canvas
    def trainFunction():

        global df
        global dates_list
        global model
        global graph

        graph1 = FigureCanvasTkAgg(fig, master=root)
        graph1.get_tk_widget().place(x=0, y=20)

        with graph.as_default():
            commission = commission_value.get()

            gain = gain_value.get()
            loss = loss_value.get()
            n_day = nday_value.get()
            epochs = epochs_value.get()

            df = func_utils.add_features(df)
            df = func_utils.add_label(df,
                                      gain=gain,
                                      loss=loss,
                                      n_day=n_day,
                                      commission=commission)

            start_train_date = getDate(start_year_train.get(),
                                       start_month_train.get(),
                                       start_day_train.get())
            end_train_date = getDate(end_year_train.get(),
                                     end_month_train.get(),
                                     end_day_train.get())
            start_test_date = getDate(start_year_test.get(),
                                      start_month_test.get(),
                                      start_day_test.get())
            end_test_date = getDate(end_year_test.get(), end_month_test.get(),
                                    end_day_test.get())

            df_train, df_test, X_train, X_test, y_train, y_test = func_utils.split_df_date(
                df, start_train_date, end_train_date, start_test_date,
                end_test_date)

            # ------------ Normalizamos los datos ------------ #

            sc = StandardScaler()
            X_train = preprocessing.scale(X_train)
            X_test = preprocessing.scale(X_test)

            # Ponemos los datos en formato correcto para usarlos en keras
            X_train = np.reshape(X_train,
                                 (X_train.shape[0], X_train.shape[1], 1))
            X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

            # ------------ Obtenemos el modelo de predicción ------------ #

            print("Entrenando red neuronal...")

            clf = model.NeuralNetwork()
            clf.build_model(input_shape=(X_train.shape[1], 1))
            clf.train(X_train, y_train, epochs=epochs)

            # ------------ Comenzar la simulación ------------ #

            clf.init_memory(X_train[len(X_train) - 15:len(X_train)],
                            y_train[len(y_train) - 15:len(y_train)])

            dates_list = df.index.strftime('%Y-%m-%d')

            print("Realizando simulación...")

            predictions = []

            #n_steps = 1
            n_steps = int(len(X_test) / 4)

            for k in range(1, n_steps + 1):
                # Creamos la instancia cerebro
                cerebro = myCerebro.MyCerebro()

                tam = (int)(k * 1.0 * len(X_test) / n_steps)
                start_to_predict = (int)((k - 1) * 1.0 * len(X_test) / n_steps)
                #tam = k

                # Creamos una instancia de la clase TestStrategy
                ts = testStrategyInteractive.TestStrategy
                ts.X_test = X_test[0:tam]
                ts.y_test = y_test[0:tam]
                ts.model = clf
                ts.n_day = n_day
                ts.dates_list = df.index.strftime('%Y-%m-%d')
                ts.start_to_predict = start_to_predict
                ts.predictions = predictions

                # Añadimos la estrategia al cerebro
                cerebro.addstrategy(ts)

                # Añadimos los datos al cerebro
                data = bt.feeds.PandasData(dataname=df_test[0:tam])
                cerebro.adddata(data)

                # Fijamos el dinero inicial y la comisión
                cerebro.broker.setcash(cash_value.get())
                cerebro.broker.setcommission(commission=commission)

                result = cerebro.run()

                predictions = result[0].predictions
                clf = result[0].model

                if k == n_steps:
                    fig_cerebro = cerebro.getFig(iplot=False)[0][0]
                else:
                    fig_cerebro = cerebro.getFig(iplot=False,
                                                 start=max(tam - 60, 0),
                                                 end=tam)[0][0]

                fig_cerebro.set_figheight(figure_h)
                fig_cerebro.set_figwidth(figure_w)

                plt.subplots_adjust(top=0.98,
                                    bottom=0.1,
                                    left=0.05,
                                    right=0.95,
                                    hspace=0.0,
                                    wspace=0.0)

                graph1.figure = fig_cerebro
                graph1.draw()

            print("Simulación realizada con éxito...")
Beispiel #3
0
def draw_figure(canvas: FigureCanvasTkAgg, figure: Figure) -> None:
    canvas.figure = figure
    canvas.draw()