def closeShortPosition(self, ax: plt, n: int, xpos: int, ypos: float,
                        sig_type: int) -> None:
     if self.plot is True:
         if sig_type == 0:
             marker = "*k"
         elif sig_type == 1:
             marker = "xk"
         else:
             raise ValueError("Wrong sig_type:" + sig_type)
         ax.plot([
             xpos,
         ], [
             ypos,
         ], marker, markersize=5)
         if ypos != self.short_start_price:
             color = "red" if ypos < self.short_start_price else "blue"
             x = self.xMl[self.short_start_pos]
             ax.plot([x, x + 0.001], [
                 self.short_start_price, 2 * self.short_start_price - ypos
             ],
                     color=color,
                     linewidth=1)
     # print("close at", "\tn:", n, "\txpos:", xpos, "\typos:", ypos, "\tslope:",self.slope_list[n], "\tnadir:", self.short_nadir_price)
     self.pnl += self.short_start_price - ypos
     self.update_stat_df(pos_type="short", close_price=ypos)
     self.initDailyParam(pos_type="short")
 def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str, sig_type: str) -> None:
     if sig_type == "NS1":
         color = "deepskyblue"
         shift = 3
     elif sig_type == "NS2":
         color = "deepskyblue"
         shift = 4
     elif sig_type == "NS3":
         color = "deepskyblue"
         shift = 4
     elif sig_type == "CON1":
         color = "goldenrod"
         shift = 3
     elif sig_type == "CON2":
         color = "goldenrod"
         shift = 4
     elif sig_type == "CON3":
         color = "goldenrod"
         shift = 4
     elif sig_type == "RAP":
         color = "violet"
         shift = 2
     else:
         raise ValueError("Wrong sig_type:" + sig_type)
     color = "gray"
     ax.plot(self.xMl[n - shift: n + 1], self.yMl[n - shift: n + 1], color=color, linewidth=1)
     # ax.text(xpos - 30, ypos - 0.004, sig, fontsize=12, color=color, fontweight="bold")
     ax.text(xpos - 120, ypos - 0.03, sig_type, fontsize=6, color=color, fontweight="bold")
Пример #3
0
def plot_data_distribution(plot: plt,
                           data,
                           feature_extractor,
                           num_classes=3,
                           small_points=False):
    features = feature_extractor.predict(data)
    labels = np.concatenate([y for x, y in data], axis=0)
    if small_points:
        marker_data = 'x'
        marker_colour = ['k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k']
        markersize = 3
        alpha = 0.3
    else:
        marker_data = 'x'
        marker_colour = [
            'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',
            'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'
        ]
        markersize = 3
        alpha = 0.7

    for class_id in range(num_classes):
        x_class = features[labels == class_id]
        plot.plot(x_class[:, 1],
                  x_class[:, 0],
                  marker_data,
                  color=marker_colour[class_id],
                  ms=markersize,
                  alpha=alpha)
Пример #4
0
 def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str, sig_type: str) -> None:
     if sig_type == "CON1":
         shift = 3
     elif sig_type == "CON3":
         shift = 4
     elif sig_type == "RAP":
         shift = 2
     else:
         raise ValueError("Wrong sig_type:" + sig_type)
     ax.plot(self.xMl[n - shift: n + 1], self.yMl[n - shift: n + 1], color="gray",linewidth=1)
     ax.text(xpos - 120, ypos - 0.03, sig_type, fontsize=6, color="gray", fontweight="bold")
Пример #5
0
 def closePosition(self, close_type: str, ax: plt, n: int, xpos: int, ypos: float, marker: str):
     start_price = self.long_start_price if close_type == "long" else self.short_start_price
     pos = self.long_start_pos if close_type == "long" else self.short_start_pos
     if self.plot is True:
         ax.plot([xpos, ], [ypos, ], marker, markersize=5)
         if ypos != start_price:
             color = "red" if ypos > start_price else "blue"
             x = self.xMl[pos]
             ax.plot([x, x + 0.0001], [start_price, ypos], color=color, linewidth =1)
     self.pnl += ypos - start_price
     self.update_stat_df(pos_type=close_type, close_price=ypos)
     self.initDailyParam(pos_type=close_type)
Пример #6
0
 def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str,
                sig_type: str) -> None:
     shift = 3 if sig_type == "CON1" else 2
     ax.plot(self.xMl[n - shift:n + 1],
             self.yMl[n - shift:n + 1],
             color="gray",
             linewidth=1)
     ax.text(xpos - 120,
             ypos - 0.03,
             sig_type,
             fontsize=6,
             color="gray",
             fontweight="bold")
def plot_ecdf(x_:ndarray,ax:pyplot=None,figsize:tuple=FIGSIZE,fontsize:int=FONTSIZE,grid:bool=False,
                            xlabel:str='x', ylabel:str='y',
                            lw:int=1,color:str=None,dots_marker:str=None,dots_color:str='red',dots_size:float=10,
                            zorder:float=None, plot_data_ticks:bool=True, plot_data_dots:bool=True) -> pyplot:
    x = dataseries(x_).value
    fig=[]
    if ax is None:
        fig,ax = pyplot.subplots(figsize=figsize)
        if grid: ax.grid()
        ax.set_xlabel(xlabel,fontsize=fontsize)
        ax.set_ylabel(ylabel,fontsize=fontsize)
        ax.tick_params(direction='out', grid_alpha=0.5, labelsize='large')
    x1,y1 = stairs(x)
    ax.plot(x1,y1,color=color,zorder=zorder,lw=lw)
    if plot_data_ticks: ax.scatter(x,[0]*len(x),marker='|',s=200) # https://matplotlib.org/stable/api/markers_api.html
    x2,p=ecdf(x)
    if plot_data_dots: ax.scatter(x2,p,s=dots_size,color=dots_color,marker=dots_marker,zorder=zorder)
    return fig, ax 
Пример #8
0
def plot3D(ax: plt, sub3d: plt, X: np.ndarray, y: np.ndarray, w: np.ndarray,
           name: str) -> None:
    '''
    Visualize decision boundary and data classes in 3D
    :param ax:  matplotlib
    :param sub3d: fig.add_subplot(XXX, projection='3d')
    :param X: data
    :param y: data labels
    :param w: model parameters
    :param name: plot name identifier
    :return:
    '''
    x1 = np.array(X[1, :])  # note: X_train[0,:] is the added row of 1s (bias)
    x2 = np.array(X[2, :])
    posterior1 = LOGREG().activationFunction(w, X)
    posterior1 = np.squeeze(np.asarray(posterior1))
    markers = ['o', '+']
    groundTruthLabels = np.unique(y)
    for li in range(len(groundTruthLabels)):
        x1_sub = x1[y[:] == groundTruthLabels[li]]
        x2_sub = x2[y[:] == groundTruthLabels[li]]
        m_sub = markers[li]
        posterior1_sub = posterior1[y[:] == groundTruthLabels[li]]
        sub3d.scatter(x1_sub,
                      x2_sub,
                      posterior1_sub,
                      c=posterior1_sub,
                      vmin=0,
                      vmax=1,
                      marker=m_sub,
                      label='ground truth label = ' + str(li))
    ax.legend()
    x = np.arange(x1.min(), x1.max(), 0.1)
    pms = [[0.1, 'k:'], [0.25, 'k--'], [0.5, 'r'], [0.75, 'k-.'], [0.9, 'k-']]
    for (p, m) in pms:
        yp = (-np.log((1 / p) - 1) - w[1] * x - w[0]) / w[2]
        yp = np.squeeze(np.asarray(yp))
        z = np.ones(yp.shape) * p
        sub3d.plot(x, yp, z, m, label='p = ' + str(p))
        ax.legend()
    ax.xlabel('feature 1')
    ax.ylabel('feature 2')
    ax.title(name + '\n Posterior for class labeled 1')
    def generate(self, plot: pyplot, data: Any) -> None:
        # [('low-end-laptop', 0, 'mceliece', '6960119f', 'clang', 'ref-optimized', 'keypair', 666.1022, 999, 665165462)]
        # clang, ref-optimized: [1, 2, 3, ...]
        series: Dict[str, Dict[int, float]] = {}
        # run_index: average duration
        baseline_average_durations: Dict[int, int] = {}
        # label: run_index: iteration: duration
        sum_per_label: Dict[str, Dict[int, Dict[int, int]]] = {}

        # Find values
        for row in data:
            compiler = row[4]
            features = row[5]
            run_index = row[1]
            if compiler == "gcc" and features == "ref":
                average_duration = row[7]
                baseline_average_durations[run_index] = average_duration
            else:
                label = "{} {}".format(compiler, features)
                if label not in sum_per_label:
                    sum_per_label[label] = {}

                if run_index not in sum_per_label[label]:
                    sum_per_label[label][run_index] = {}

                iteration = row[8]
                duration = row[9]
                sum_per_label[label][run_index][iteration] = duration

        baseline_avarage_duration = sum(baseline_average_durations.values()
                                        ) / len(baseline_average_durations)
        print("Baseline runs:", baseline_average_durations)
        print("Baseline average duration:", baseline_avarage_duration)

        for label in sum_per_label.keys():
            max_length = max([
                len(value.items()) for value in sum_per_label[label].values()
            ])
            for i in range(max_length):
                relevant_items = [
                    items[i] for items in sum_per_label[label].values()
                    if i in items
                ]
                duration = sum(relevant_items) / len(relevant_items)
                percentual_duration = (duration /
                                       1e6) / baseline_avarage_duration
                if label not in series:
                    series[label] = {}
                series[label][i] = (1 / percentual_duration - 1.0)

        colors = [
            "#e6194B", "#3cb44b", "#4363d8", "#f58231", "#800000", "#9A6324",
            "#000075", "#469990"
        ]
        for i, key in enumerate(series.keys()):
            # TODO: may be wrong if there are gaps in data as it does not care about the acutal indexing
            values = series[key].values()
            plot.plot(values, label=key, color=colors[i])
        plot.title("")
        plot.ylabel("Speedup")
        plot.xlabel("Iteration")
        plot.legend(bbox_to_anchor=(0.5, 1.05),
                    loc="lower center",
                    fontsize=8,
                    ncol=len(series))
Пример #10
0
 def generate(self, plot: pyplot, data: Any) -> None:
   plot.plot(data)
   plot.ylabel("Some numbers")