Exemplo n.º 1
0
 def add_line(self,
              list,
              x1,
              x2,
              y1,
              y2,
              color='red',
              width=2,
              number_of_steps=200,
              label='kikuchi_line'):
     pen = QtGui.QPen(QtCore.Qt.SolidLine)
     pen.setColor(QtGui.QColor(color))
     pen.setWidth(width)
     series = QtChart.QLineSeries()
     series.setPen(pen)
     for x, y in zip(np.linspace(x1, x2, number_of_steps),
                     np.linspace(y1, y2, number_of_steps)):
         series.append(x, y)
     self.plot.profileChart.addSeries(series)
     for ax in self.plot.profileChart.axes():
         series.attachAxis(ax)
     if label == 'kikuchi_line':
         self.kikuchi_line_series[list] = series
     self.plot.profileChart.axisY().setRange(-0.5, self.plot_range.value())
Exemplo n.º 2
0
    def update_stripchart(self):
        # get new data point
        new_a = self.data[len(self.data) - 1].a
        new_b = self.data[len(self.data) - 1].b
        new_ra = self.data[len(self.data) - 1].timestamp

        # add new data point to both series
        self.stripchart_series_a.append(new_a, new_ra)
        self.stripchart_series_b.append(new_b, new_ra)

        # magical song and dance in an attempt to appease the Qt gods
        self.chart.removeSeries(self.stripchart_series_b)
        self.chart.removeSeries(self.stripchart_series_a)
        self.chart.addSeries(self.stripchart_series_b)
        self.chart.addSeries(self.stripchart_series_a)

        axis_y = QtChart.QValueAxis()
        axis_y.setMin(self.clock.get_sidereal_seconds() - self.stripchart_display_seconds)
        axis_y.setMax(self.clock.get_sidereal_seconds())
        axis_y.setVisible(False)

        self.chart.setAxisY(axis_y)
        self.stripchart_series_a.attachAxis(axis_y)
        self.stripchart_series_b.attachAxis(axis_y)
Exemplo n.º 3
0
    def SetLineSeries(self, data_x, data_y, data_y_2=None, chart_name=''):
        self.chart = QtChart.QChart()
        #self.chart.setTheme(QtChart.QChart.ChartThemeDark)

        series = QtChart.QLineSeries()
        for index in range(len(data_y)):
            series.append(index, data_y[index])
        self.chart.addSeries(series)

        axisX = QtChart.QCategoryAxis()
        axisX.setRange(-1, len(data_y) + 1)
        axisX.setStartValue(0)
        for index in range(0, len(data_x)):
            axisX.append(data_x[index], index)
        axisX.setLabelsAngle(90)
        #axisX.setTickCount(10)
        axisX.setLabelsPosition(
            QtChart.QCategoryAxis.AxisLabelsPositionOnValue)
        #self.chart.setAxisX(axisX,series)
        self.chart.addAxis(axisX, QtCore.Qt.AlignBottom)

        series.attachAxis(axisX)

        axisY = QtChart.QValueAxis()
        axisY.setRange(data_y.min(), data_y.max())
        axisY.setTickCount(10)
        self.chart.addAxis(axisY, QtCore.Qt.AlignLeft)
        #self.chart.setAxisY(axisY,series)
        series.attachAxis(axisY)

        if data_y_2 is not None:
            axisY2 = QtChart.QValueAxis()
            axisY2.setRange(data_y_2.min(), data_y_2.max())
            axisY2.setTickCount(10)
            self.chart.addAxis(axisY2, QtCore.Qt.AlignRight)
            series2 = QtChart.QLineSeries()
            for index in range(len(data_y_2)):
                series2.append(index, data_y_2[index])
            self.chart.addSeries(series2)
            series2.attachAxis(axisX)
            series2.attachAxis(axisY2)

        self.chart.setTitle(chart_name)
Exemplo n.º 4
0
    def __init__(self,
                 parent,
                 value_label_format="%i",
                 date_time_format="hh:mm"):
        super().__init__(parent)

        self.chart = QtChart.QChart()
        self.chart.setTheme(QtChart.QChart.ChartThemeDark)
        self.chart.setMargins(QtCore.QMargins(0, 0, 0, 0))
        self.chart.setBackgroundVisible(False)
        self.chart.legend().hide()

        self.value_series = QtChart.QLineSeries()
        self.lower_series = QtChart.QLineSeries()
        area_series = QtChart.QAreaSeries(self.value_series, self.lower_series)
        self.chart.addSeries(area_series)

        axis_x = QtChart.QDateTimeAxis()
        axis_x.setFormat(date_time_format)
        axis_x.setTitleText("Time")
        self.chart.addAxis(axis_x, QtCore.Qt.AlignBottom)
        area_series.attachAxis(axis_x)

        axis_y = QtChart.QValueAxis()
        axis_y.setLabelFormat(value_label_format)
        axis_y.setTitleText("Value")
        self.chart.addAxis(axis_y, QtCore.Qt.AlignLeft)
        area_series.attachAxis(axis_y)

        self.chart_view = QtChart.QChartView(self.chart)
        self.chart_view.setRenderHint(QtGui.QPainter.Antialiasing)

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.chart_view)
        self.setLayout(layout)

        self.resize(800, 500)
    def __init__(self, log_file: Path, sensor_value_unit: str, main_ui):
        QtWidgets.QWidget.__init__(self)

        # set up  window style and size
        # frameless modal window fullscreen (same as main ui)
        self.setWindowFlags(
            Qt.WindowType(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint))
        self.setWindowModality(Qt.WindowModal)
        self.setGeometry(main_ui.geometry())

        if not log_file.exists():
            self.not_enough_values_dialog()
            return

        # read log backwards, until we hit the time barrier from TIME_WINDOW_SECONDS - performance!
        current_time = datetime.now()
        self._time_value_pairs: List[Tuple[datetime, float]] = []
        try:
            with FileReadBackwards(str(log_file), encoding="utf-8") as fp:
                # log has format 2021-03-12 18:51:16=55\n...
                for line in fp:
                    time_value_pair = line.split("=")
                    timestamp = datetime.fromisoformat(time_value_pair[0])
                    if (current_time - timestamp) > timedelta(
                            minutes=self.TIME_WINDOW_MINUTES):
                        break
                    self._time_value_pairs.append(
                        (timestamp, float(time_value_pair[1].strip())))
        except Exception:
            # delete when file is corrupted
            os.remove(log_file)

        if len(self._time_value_pairs) < 2:  # insufficient data
            self.not_enough_values_dialog()
            return

        # add values to qt graph
        # time values are converted to "- <Minutes>" format
        series = QtChart.QLineSeries()
        series.setPen(QtGui.QPen(Qt.white))
        series.setColor(Qt.white)
        for timestamp, value in self._time_value_pairs:
            if (current_time - timestamp).days == 0:
                series.append(
                    QtCore.QPointF(
                        -1 * (current_time - timestamp).seconds / 60, value))

        chart = QtChart.QChart()
        chart.addSeries(series)
        chart.setAnimationOptions(QtChart.QChart.SeriesAnimations)
        chart.createDefaultAxes()
        chart.axisY(series).setTitleText(sensor_value_unit)
        chart.axisX(series).setTitleText("Minutes")
        chart.axisX(series).setMin(-180)
        chart.axisX(series).setGridLineVisible(False)
        chart.axisY(series).setGridLineVisible(False)
        chart.layout().setContentsMargins(0, 6, 0, 6)

        chart.legend().setVisible(False)

        gradient = QtGui.QLinearGradient(0, 0, 0, self.height())
        gradient.setColorAt(0, QtGui.QColor(13, 119, 167))
        gradient.setColorAt(1, QtGui.QColor(115, 158, 201))
        pen = QtGui.QPen()
        pen.setColor(QtGui.QColor(Qt.transparent))
        brush = QtGui.QBrush(gradient)
        brush.setStyle(Qt.LinearGradientPattern)
        chart.setBackgroundBrush(brush)

        # calculate delta of last hour
        last_hour_time_val_pairs = list(
            filter(
                lambda time_value_pair:
                (current_time - time_value_pair[0]) < timedelta(minutes=60),
                self._time_value_pairs))
        last_hour_values: List[float] = [
            time_value_pair[1] for time_value_pair in last_hour_time_val_pairs
        ]

        delta_label = QtWidgets.QLabel(self)
        if last_hour_values:
            delta_label.setText(
                f"Change: {max(last_hour_values) - min(last_hour_values):.2f} {sensor_value_unit}/hour"
            )

        # chart needs a chartview to be displayed
        sensor_chart_view = QtChart.QChartView(chart)
        sensor_chart_view.setRenderHint(QtGui.QPainter.Antialiasing)
        sensor_chart_view.setSizeAdjustPolicy(
            QtChart.QChartView.AdjustToContents)
        sensor_chart_view.setMaximumSize(2000, 2000)
        sensor_chart_view.setMinimumSize(600, 300)
        sensor_chart_view.setBackgroundBrush(brush)

        # Button to close
        ok_button = QtWidgets.QPushButton("OK", self)
        ok_button.clicked.connect(self.close)

        # add everything to the qt layout
        self._layout = QtWidgets.QVBoxLayout(self)
        self._layout.setSizeConstraint(QtWidgets.QLayout.SetMinAndMaxSize)
        self._layout.addWidget(sensor_chart_view)
        self._layout.addWidget(delta_label)
        self._layout.addWidget(ok_button)

        # event filter handles closing - one click/touch closes the window
        self.installEventFilter(self)

        self.show()
Exemplo n.º 6
0
 def plot_results(self, x0, y0, Kperp, nimg):
     if not self.file_has_been_created:
         if self.BGCheck.isChecked() and self.saveResult.isChecked():
             self.map_without_background = np.array([0, 0, 0, 0])
             self.save_path_without_background = self.currentDestination + "/2D_map_without_background.txt"
             self.file_has_been_created = True
     self.chart.add_chart(x0, y0)
     total = np.full(len(x0), float(self.offset.get_value()))
     total_min = 100
     for i in range(self.table.rowCount()):
         if self.fitFunctionCombo.currentText() == 'Gaussian':
             center = float(self.table.item(i, 0).text())
             height = float(self.table.item(i, 3).text())
             width = float(self.table.item(i, 6).text())
             offset = float(self.offset.get_value())
             fit = self.fit_function(x0, height, center, width, offset)
             fit0 = self.fit_function(x0, height, center, width, 0)
             total = np.add(total, fit0)
             maxH = self.fit_function(center, height, center, width, offset)
             minH1 = self.fit_function(x0[0], height, center, width, offset)
             minH2 = self.fit_function(x0[-1], height, center, width,
                                       offset)
         elif self.fitFunctionCombo.currentText() == 'Voigt':
             center = float(self.table.item(i, 0).text())
             amplitude = float(self.table.item(i, 3).text())
             width_L = float(self.table.item(i, 6).text())
             width_G = float(self.table.item(i, 9).text())
             offset = float(self.offset.get_value())
             fit = self.fit_function(x0, center, amplitude, width_L,
                                     width_G, offset)
             fit0 = self.fit_function(x0, center, amplitude, width_L,
                                      width_G, 0)
             total = np.add(total, fit0)
             maxH = self.fit_function(center, center, amplitude, width_L,
                                      width_G, offset)
             minH1 = self.fit_function(x0[0], center, amplitude, width_L,
                                       width_G, offset)
             minH2 = self.fit_function(x0[-1], center, amplitude, width_L,
                                       width_G, offset)
         if min(minH1, minH2) < total_min:
             total_min = min(minH1, minH2)
         pen = QtGui.QPen(QtCore.Qt.DotLine)
         pen.setColor(QtGui.QColor(self.COLOR[i]))
         pen.setWidth(2)
         series_fit = QtChart.QLineSeries()
         series_fit.setPen(pen)
         for x, y in zip(x0, fit):
             series_fit.append(x, y)
         self.chart.profileChart.addSeries(series_fit)
         for ax in self.chart.profileChart.axes():
             series_fit.attachAxis(ax)
         self.chart.profileChart.axisY().setRange(
             min(minH1, minH2, min(y0)), max(maxH, max(y0)))
         if i == self.table.rowCount() - 1:
             if self.BGCheck.isChecked() and self.saveResult.isChecked():
                 maxPos = np.argmax(y0)
                 phi = np.full(len(x0), nimg * 1.8)
                 radius = np.abs(x0 - x0[maxPos])
                 for iphi in range(0, maxPos):
                     phi[iphi] = nimg * 1.8 + 180
                 K = np.full(len(x0), Kperp)
                 self.map_without_background = np.vstack(
                     (self.map_without_background,
                      np.vstack((radius, phi, K, y0 - fit)).T))
     if self.BGCheck.isChecked() and self.saveResult.isChecked():
         np.savetxt(self.save_path_without_background,
                    np.delete(self.map_without_background, 0, 0),
                    fmt='%4.3f')
     pen = QtGui.QPen(QtCore.Qt.DotLine)
     pen.setColor(QtGui.QColor('red'))
     pen.setWidth(2)
     series_total = QtChart.QLineSeries()
     series_total.setPen(pen)
     for x, y in zip(x0, total):
         series_total.append(x, y)
     self.chart.profileChart.addSeries(series_total)
     for ax in self.chart.profileChart.axes():
         series_total.attachAxis(ax)
     self.chart.profileChart.axisY().setRange(
         min(total[0], total[-1], np.amin(y0), total_min),
         max(np.amax(total), np.amax(y0)))
     QtCore.QCoreApplication.processEvents()
Exemplo n.º 7
0
 def append_data_and_plot(self, d):
     '''Append and update the plot'''
     num, o, h, l, c, m = d
     self.series.append(QtChart.QCandlestickSet(o, h, l, c))
     self.ui.show()
Exemplo n.º 8
0
 def __init__(self):
     self.series = QtChart.QSplineSeries()
     pen = QtGui.QPen(QtCore.Qt.SolidLine)
     pen.setWidthF(0.5)
     pen.setColor(QtGui.QColor(255, 255, 0))
     self.series.setPen(pen)
Exemplo n.º 9
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        if not parent:
            self.setWindowTitle(self.title)

        chart = QtChart.QChart(title=self.title)
        self.setChart(chart)
        self.memoryName = "memória "
        self.freeMemoryName = "memoria livre "
        self.swapAreaName = 'area de swap '

        xAxis = QtChart.QValueAxis()
        xAxis.setRange(0, self.numDataPonints)
        xAxis.setLabelsVisible(False)
        chart.setAxisX(xAxis)

        yAxis = QtChart.QValueAxis()
        memory = psutil.virtual_memory()
        self.memory['average'] = memory.total - memory.available
        yAxis.setRange(0, 100)
        chart.setAxisY(yAxis)

        fisicalMemorySpline = QtChart.QSplineSeries()
        fisicalMemorySpline.setName(self.memoryName)
        chart.addSeries(fisicalMemorySpline)
        fisicalMemorySpline.attachAxis(xAxis)
        fisicalMemorySpline.attachAxis(yAxis)
        self.fisicalMemorySpline = fisicalMemorySpline

        freeMemorySpline = QtChart.QSplineSeries()
        freeMemorySpline.setName(self.freeMemoryName)
        chart.addSeries(freeMemorySpline)
        freeMemorySpline.attachAxis(xAxis)
        freeMemorySpline.attachAxis(yAxis)
        self.freeMemorySpline = freeMemorySpline

        swapMemorySpline = QtChart.QSplineSeries()
        swapMemorySpline.setName(self.swapAreaName)
        chart.addSeries(swapMemorySpline)
        swapMemorySpline.attachAxis(xAxis)
        swapMemorySpline.attachAxis(yAxis)
        self.swapMemorySpline = swapMemorySpline

        self.setRenderHint(QtGui.QPainter.Antialiasing)
        chart.setTheme(QtChart.QChart.ChartThemeBlueCerulean)

        self.memoryData = deque([int(psutil.virtual_memory().percent)] *
                                self.numDataPonints,
                                maxlen=self.numDataPonints)
        self.swapData = deque([int(psutil.swap_memory().percent)] *
                              self.numDataPonints,
                              maxlen=self.numDataPonints)
        self.freeMemoryData = deque(
            [100 - int(psutil.virtual_memory().percent)] * self.numDataPonints,
            maxlen=self.numDataPonints)

        self.fisicalMemorySpline.append(
            [QtCore.QPoint(x, y) for x, y, in enumerate(self.memoryData)])
        self.swapMemorySpline.append(
            [QtCore.QPoint(x, y) for x, y, in enumerate(self.swapData)])
        self.freeMemorySpline.append(
            [QtCore.QPoint(x, y) for x, y, in enumerate(self.freeMemoryData)])

        self.timer = QtCore.QTimer(interval=200, timeout=self.upadeData)
        self.timer.start()
        self.show()
Exemplo n.º 10
0
    def updateIndicator(self, data, candles_visible):
        """
        The calculation for Chaikin Money Flow (CMF) has three distinct steps
        (for this example we will use a 21 Period CMF):
        1. Find the Money Flow Multiplier
           [(Close  -  Low) - (High - Close)] /(High - Low) = Money Flow Multiplier
        2. Calculate Money Flow Volume
           Money Flow Multiplier x Volume for the Period = Money Flow Volume
        3. Calculate The CMF
           21 Period Sum of Money Flow Volume / 21 Period Sum of Volume = 21 Period CMF

        """
        volume = data[5]
        # 1. Find the Money Flow Multiplier
        mf = ((data[4] - data[3]) - (data[2] - data[4])) / (data[2] - data[3])
        # 2. Calculate Money Flow Volume
        mf_volume = mf * data[5]
        # use auxiliary numpy arrays for period window accumulation (21 in this case)
        mf_period = np.zeros(np.shape(mf_volume))
        volume_period = np.zeros(np.shape(mf_volume))
        # set all elements at the beginning of the arrays to the first period accumulation
        mf_period[0:21] = np.sum(mf_volume[0:21])
        volume_period[0:21] = np.sum(volume[0:21])
        # find all other accumulation using the rolling window approach to reduce the number of operations
        for i in range(21, len(mf_volume)):
            mf_period[i] = mf_period[i - 1] - mf_volume[i - 21] + mf_volume[i]
            volume_period[i] = volume_period[i - 1] - volume[i -
                                                             21] + volume[i]
        # 3. Calculate The CMF
        cmf = mf_period / volume_period
        cmf = cmf[-candles_visible:]

        self.moneyFlow.clear()
        for i in range(candles_visible):
            self.moneyFlow.append(i + 0.5, cmf[i])

        # detach and remove old axes
        for ax in self.moneyFlow.attachedAxes():
            self.moneyFlow.detachAxis(ax)
        for ax in self.axes():
            self.removeAxis(ax)

        # set x axes
        ax = QtChart.QValueAxis()
        ax.setRange(0, candles_visible)
        ax.hide()

        # set x axes
        ay = QtChart.QValueAxis()
        bound = max(abs(min(cmf)), max(cmf))
        ay.setRange(-bound, bound)
        ay.setGridLinePen(QtGui.QPen(QtGui.QColor(80, 80, 80), 0.5))
        ay.setLinePen(QtGui.QPen(QtGui.QColor(0, 0, 0), 0.5))
        ay.applyNiceNumbers()
        ay.setTickCount(3)

        # add and attach new axes
        self.addAxis(ax, QtCore.Qt.AlignBottom)
        self.addAxis(ay, QtCore.Qt.AlignRight)
        self.moneyFlow.attachAxis(ax)
        self.moneyFlow.attachAxis(ay)
Exemplo n.º 11
0
 def __init__(self):
     super().__init__()
     self.true_range_line = QtChart.QLineSeries()
     self.true_range_line.setColor(QtCore.Qt.yellow)
     self.addSeries(self.true_range_line)
Exemplo n.º 12
0
    def updateCandleChart(self, data, N):
        """Update candle chart display.
        :param data:  numpy array representing candles
        :param N:     number of candles in the array
        """
        if data is None or data == []:
            return

        timestamps = data[0, -N:].astype(int).tolist()
        open = data[1, -N:].tolist()
        high = data[2, -N:].tolist()
        low = data[3, -N:].tolist()
        close = data[4, -N:].tolist()

        # remove candlestick data
        if self.candlestickSeries.count() > 0:
            self.candlestickSeries.remove(self.candlestickSeries.sets())

        # add new candlestick data
        for i, ts in enumerate(timestamps):
            candle_set = QtChart.QCandlestickSet(open[i],
                                                 high[i],
                                                 low[i],
                                                 close[i],
                                                 timestamp=ts)
            self.setCandleColors(candle_set)
            self.candlestickSeries.append(candle_set)

        # set candlestick time axes (hidden)
        axisXtime = QtChart.QBarCategoryAxis()
        axisXtime.setCategories([str(int(x / 1000)) for x in timestamps])
        axisXtime.setGridLineVisible(False)
        axisXtime.hide()

        self.ax = QtChart.QValueAxis()
        self.ax.setRange(0, len(axisXtime))
        self.ax.setGridLineVisible(False)
        self.ax.hide()

        # set pen for lines and grid lines
        line_pen = QtGui.QPen(QtGui.QColor(0, 0, 0), 0.5)
        grid_line_pen = QtGui.QPen(QtGui.QColor(80, 80, 80), 0.5)

        # set visible time axes with selected time ticks
        axisXticks = QtChart.QCategoryAxis()
        axisXticks.setLabelsPosition(
            QtChart.QCategoryAxis.AxisLabelsPositionOnValue)
        for ts, index in self.extractNiceCategories(timestamps):
            axisXticks.append(ts, index)
        axisXticks.setGridLineVisible(True)
        axisXticks.setGridLinePen(grid_line_pen)
        axisXticks.setLinePen(line_pen)
        axisXticks.setStartValue(-1)

        # set y axes (prices)
        max_val = max(high)
        min_val = min(low)
        self.ay = QtChart.QValueAxis()
        self.ay.setGridLinePen(grid_line_pen)
        self.ay.setLinePen(line_pen)
        self.ay.setMax(max_val)
        self.ay.setMin(min_val)
        self.ay.applyNiceNumbers()

        # set y axes font
        font = self.ay.labelsFont()
        font.setPointSize(8)
        self.ay.setLabelsFont(font)

        # remove old axes
        for axis in self.candlestickSeries.attachedAxes():
            self.candlestickSeries.detachAxis(axis)
            self.removeAxis(axis)

        # add updated axes
        self.addAxis(axisXtime, QtCore.Qt.AlignTop)
        self.addAxis(axisXticks, QtCore.Qt.AlignBottom)
        self.addAxis(self.ax, QtCore.Qt.AlignBottom)
        self.addAxis(self.ay, QtCore.Qt.AlignRight)

        # attach updated axes to data series
        self.candlestickSeries.attachAxis(axisXtime)
        self.candlestickSeries.attachAxis(axisXticks)
        self.candlestickSeries.attachAxis(self.ay)

        # update hover line x axes
        for axis in self.hoverLine.attachedAxes():
            self.hoverLine.detachAxis(axis)
        self.hoverLine.attachAxis(self.ay)
Exemplo n.º 13
0
 def set_xlim(self, min, max):
     x_axis = qtch.QValueAxis()
     x_axis.setRange(min, max)
     self.chart.setAxisX(x_axis, self.series)
    def setupUi(
        self, Dialog, flist, clist, attList
    ):  # setting up the widgets inside the window, receiving file list, category list, and
        self.dialog = Dialog  # selected attribute list from main window when initialized
        Dialog.setObjectName("Dialog")
        Dialog.resize(600, 400)
        self.fl = flist
        self.cl = clist

        self.gridLayout_2 = QtWidgets.QGridLayout(Dialog)
        self.gridLayout_2.setObjectName("gridLayout_2")

        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")

        self.techselector1 = QtWidgets.QComboBox(
            Dialog
        )  # drop down selectable list/combobox to select which technology/set of data is shown
        self.techselector1.setObjectName("techselector1")
        self.techselector1.activated.connect(
            self.showChart
        )  # when drop down is activated (changed or not) the chart shown is changed accordingly
        self.gridLayout.addWidget(self.techselector1, 0, 0, 1, 2)

        self.techselector2 = QtWidgets.QComboBox(
            Dialog
        )  # same as techselector1, to make a comparison between the two technology
        self.techselector2.setObjectName("techselector2")
        self.techselector2.activated.connect(self.showChart)
        self.gridLayout.addWidget(self.techselector2, 1, 0, 1, 2)

        self.attselector = QtWidgets.QComboBox(
            Dialog
        )  # drop down selectable list for selecting which attribute to compare on
        self.attselector.setObjectName("comboBox_3")
        self.attselector.activated.connect(self.showChart)
        self.gridLayout.addWidget(self.attselector, 2, 0, 1, 2)

        for file in flist:  # adding items to the drop down lists according to file list and attribute list
            for sheet in file.fl:
                self.techselector1.addItem(
                    sheet.sheet_name)  # temporary change
                self.techselector2.addItem(sheet.sheet_name)
        if attList:
            self.attselector.addItem(
                'Sum'
            )  # adding a special item to attribute to let user compare total of each category
        for att in attList:
            self.attselector.addItem(att)

        self.chartView = QtChart.QChartView(
            Dialog
        )  # chartView to show chart on window (responsive and simultaneous)
        self.chartView.setObjectName("chartView")
        self.gridLayout.addWidget(self.chartView, 3, 0, 6, 1)

        self.selectedCharts = QtWidgets.QListWidget(
            Dialog
        )  # maintain a list of user selected chart specification for user to see, save, add, and remove
        self.selectedCharts.setSelectionMode(
            QtWidgets.QAbstractItemView.ExtendedSelection)
        self.selectedCharts.setObjectName("selectedCharts")
        for file in flist:
            if file.baseline is not None:  # only adds comparison between baseline and other technologies on the sum if baseline data
                for sheet in file.fl:  # exists. Comparison chart for these are added automatically by program, but user can still
                    if 'Baseline' not in sheet.sheet_name:  # delete them
                        item = QtWidgets.QListWidgetItem()
                        item.setFlags(QtCore.Qt.ItemIsSelectable
                                      | QtCore.Qt.ItemIsUserCheckable
                                      | QtCore.Qt.ItemIsEnabled)
                        self.selectedCharts.addItem(item)
                        _translate = QtCore.QCoreApplication.translate
                        item.setText(
                            _translate(
                                "Dialog",
                                file.building_name + ' - ' + 'Baseline' +
                                ", " + sheet.sheet_name + ", " + 'Sum')
                        )  # text in the list is set 'tech1, tech2, att'

        self.gridLayout.addWidget(self.selectedCharts, 3, 1, 6, 1)

        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.
            Save  # four buttons exists 'Save, Discard, Cancel, Apply'
            | QtWidgets.QDialogButtonBox.Discard
            | QtWidgets.QDialogButtonBox.Apply)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayout.addWidget(self.buttonBox, 9, 0, 1, 2)

        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)

        self.retranslateUi(Dialog)
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Apply
        ).clicked.connect(
            self.saveChart
        )  # apply the user selected entry from drop down lists as a new entry in selected list
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Cancel
        ).clicked.connect(
            Dialog.reject
        )  # closes the window, does not destroy it, all data is saved but not added to main window
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Discard).clicked.connect(
                self.discardChart
            )  # remove an entry from selected list selected by the user
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Save).clicked.connect(
            Dialog.accept
        )  # same as cancel, but main window grabs the data from this window for saving to xlsx

        QtCore.QMetaObject.connectSlotsByName(Dialog)
Exemplo n.º 15
0
    def plot_results(self, x0, guess):
        if len(self.fit_chart.profileChart.series()) > 1:
            for series in self.fit_chart.profileChart.series()[1:]:
                self.fit_chart.profileChart.removeSeries(series)
        if self.function == 'gaussian' or self.function == 'voigt':
            total = np.full(len(x0), float(self.OffsetSlider.value()))
        elif self.function == 'translational_antiphase_domain_model':
            total = np.full(len(x0), float(0))
        total_min = 100
        for i in range(len(guess)):
            if self.function == 'gaussian':
                center = float(guess[i][0])
                height = float(guess[i][1])
                width = float(guess[i][2])
                offset = float(self.OffsetSlider.value())
                fit = self.fit_function(x0, height, center, width, offset)
                fit0 = self.fit_function(x0, height, center, width, 0)
                total = np.add(total, fit0)
                maxH = self.fit_function(center, height, center, width, offset)
                minH1 = self.fit_function(x0[0], height, center, width, offset)
                minH2 = self.fit_function(x0[-1], height, center, width,
                                          offset)
            elif self.function == 'voigt':
                center = float(guess[i][0])
                amplitude = float(guess[i][1])
                width_L = float(guess[i][2])
                width_G = float(guess[i][3])
                offset = float(self.OffsetSlider.value())
                fit = self.fit_function(x0, center, amplitude, width_L,
                                        width_G, offset)
                fit0 = self.fit_function(x0, center, amplitude, width_L,
                                         width_G, 0)
                total = np.add(total, fit0)
                maxH = self.fit_function(center, center, amplitude, width_L,
                                         width_G, offset)
                minH1 = self.fit_function(x0[0], center, amplitude, width_L,
                                          width_G, offset)
                minH2 = self.fit_function(x0[-1], center, amplitude, width_L,
                                          width_G, offset)
            elif self.function == 'translational_antiphase_domain_model':
                if i == len(guess) - 1:
                    center = float(guess[i][0])
                    height = float(guess[i][1])
                    width = float(guess[i][2])
                    offset = 0
                    fit = self.fit_worker.gaussian(x0, height, center, width,
                                                   offset)
                    fit0 = self.fit_worker.gaussian(x0, height, center, width,
                                                    0)
                    total = np.add(total, fit0)
                    maxH = self.fit_worker.gaussian(center, height, center,
                                                    width, offset)
                    minH1 = self.fit_worker.gaussian(x0[0], height, center,
                                                     width, offset)
                    minH2 = self.fit_worker.gaussian(x0[-1], height, center,
                                                     width, offset)
                else:
                    center = float(guess[len(guess) - 1][0])
                    height = float(guess[len(guess) - 1][1])
                    width = float(guess[len(guess) - 1][2])
                    fit0 = self.fit_worker.gaussian(x0, height, center, width,
                                                    0)
                    fit0_normalized = fit0 / np.amax(fit0)

                    gamma = float(guess[i][0])
                    height = float(guess[i][1])
                    offset = float(guess[i][2])
                    fit = self.fit_function(x0, self.lattice_constant, gamma,
                                            height, offset) * fit0_normalized
                    total = np.add(total, fit)
                    maxH = 1
                    minH1 = self.fit_function(x0[0], self.lattice_constant,
                                              gamma, height, offset)
                    minH2 = self.fit_function(x0[-1], self.lattice_constant,
                                              gamma, height, offset)
            if min(minH1, minH2) < total_min:
                total_min = min(minH1, minH2)
            pen = QtGui.QPen(QtCore.Qt.DotLine)
            pen.setColor(QtGui.QColor(self.COLOR[i]))
            pen.setWidth(2)
            self.series_fit = QtChart.QLineSeries()
            self.series_fit.setPen(pen)
            for x, y in zip(x0, fit):
                self.series_fit.append(x, y)
            self.fit_chart.profileChart.addSeries(self.series_fit)
            for ax in self.fit_chart.profileChart.axes():
                self.series_fit.attachAxis(ax)
            self.fit_chart.profileChart.axisY().setRange(
                min(minH1, minH2, self.minIntensity),
                max(maxH, self.maxIntensity))
        pen = QtGui.QPen(QtCore.Qt.DotLine)
        pen.setColor(QtGui.QColor('red'))
        pen.setWidth(2)
        series_total = QtChart.QLineSeries()
        series_total.setPen(pen)
        for x, y in zip(x0, total):
            series_total.append(x, y)
        self.fit_chart.profileChart.addSeries(series_total)
        for ax in self.fit_chart.profileChart.axes():
            series_total.attachAxis(ax)
        self.fit_chart.profileChart.axisY().setRange(
            min(total[0], total[-1], self.minIntensity, total_min),
            max(np.amax(total), self.maxIntensity))
 def showChart(
     self
 ):  # function to show the chart of data of user selected tech and attribute on QChartView
     file1 = self.techselector1.currentText()
     current_building1, current_tech1 = file1.split(' - ')
     current_buildingI1, current_buildingI2, current_techI1, current_techI2 = 0, 0, 0, 0
     for index, file in enumerate(self.fl):
         if file.building_name == current_building1:
             current_buildingI1 = index
     file2 = self.techselector2.currentText()
     current_building2, current_tech2 = file2.split(' - ')
     for index, file in enumerate(self.fl):
         if file.building_name == current_building2:
             current_buildingI2 = index
     att = self.attselector.currentText(
     )  # assign user selected texts from drop down lists to parameters
     series = QtChart.QBarSeries(
     )  # the lines below creates the bar chart with the 2 tech selected as the categories (x-axis) with data from
     chart = QtChart.QChart(
     )  # filelist dfSumDiff (summary of sum of each attributes in all dataframes)
     axis = QtChart.QBarCategoryAxis(chart)
     categories = [file1, file2]
     if att != 'Sum':
         set0 = QtChart.QBarSet(
             att
         )  # use only the user-specified attribute sum value attained from dataframe as one set of bars
         set0.append([
             self.fl[current_buildingI1].dfSumDiff.at[file1, att],
             self.fl[current_buildingI2].dfSumDiff.at[file2, att]
         ])
         series.append(set0)
     else:
         for cat in self.cl.cl:  # add different set of bars for different category total
             set0 = QtChart.QBarSet(att + '(' + cat.name + ')')
             df_temp = self.fl[current_buildingI1].dfSumDiff[
                 self.fl[current_buildingI1].dfSumDiff.columns.intersection(
                     cat.members)]
             if current_buildingI1 != current_buildingI2:
                 df_temp = df_temp.append(
                     self.fl[current_buildingI2].dfSumDiff[self.fl[
                         current_buildingI2].dfSumDiff.columns.intersection(
                             cat.members)])
             if cat.name != 'Cooling load':
                 df_temp = df_temp.T.append(df_temp.loc[:, [
                     col for col in df_temp.columns if 'DX' not in col
                 ]].sum(axis='columns').to_frame(
                 ).T)  # add the sum of the category as a new column
             else:
                 df_temp = df_temp.T.append(df_temp.loc[:, [
                     'Ap Sys chillers load (kWh)',
                     'ApHVAC chillers load (kWh)'
                 ]].sum(axis='columns').to_frame().T)
             df_temp.rename({0: 'Sum'}, axis='index', inplace=True)
             df_temp = df_temp.T
             set0.append(
                 [df_temp.at[file1, 'Sum'], df_temp.at[file2, 'Sum']])
             series.append(set0)
     series.setLabelsVisible()
     chart.addSeries(series)
     axis.append(categories)
     chart.createDefaultAxes()
     chart.setAxisX(axis, series)
     self.chartView.setChart(chart)
Exemplo n.º 17
0
 def __init__(self):
     super().__init__()
     self.aroon = QtChart.QLineSeries()
     self.aroon.setColor(QtCore.Qt.magenta)
     self.addSeries(self.aroon)
Exemplo n.º 18
0
    def setupUi(self, MainWindow):
        """ The following code is initially generated by Qt Designer to init the window
            Some modifications have been done
        """
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1920, 1080)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
        MainWindow.setStatusTip("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.listNews = QtWidgets.QListWidget(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.listNews.sizePolicy().hasHeightForWidth())
        self.listNews.setSizePolicy(sizePolicy)
        self.listNews.setProperty("showDropIndicator", False)
        self.listNews.setObjectName("listNews")
        self.gridLayout_2.addWidget(self.listNews, 0, 1, 1, 1)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.EURUSD = QtWidgets.QLabel(self.centralwidget)
        self.EURUSD.setObjectName("EURUSD")
        self.horizontalLayout_2.addWidget(self.EURUSD)
        self.chartView = QtChart.QChartView(self.centralwidget)
        self.chartView.setObjectName("chartView")
        self.horizontalLayout_2.addWidget(self.chartView)
        self.init_chart(self.chartView, "EUR/USD")

        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.USDJPY = QtWidgets.QLabel(self.centralwidget)
        self.USDJPY.setObjectName("USDJPY")
        self.horizontalLayout_3.addWidget(self.USDJPY)
        self.chartView_2 = QtChart.QChartView(self.centralwidget)
        self.chartView_2.setObjectName("chartView_2")
        self.horizontalLayout_3.addWidget(self.chartView_2)
        self.init_chart(self.chartView_2, "USD/JPY")

        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.GBPUSD = QtWidgets.QLabel(self.centralwidget)
        self.GBPUSD.setObjectName("GBPUSD")
        self.horizontalLayout_4.addWidget(self.GBPUSD)
        self.chartView_3 = QtChart.QChartView(self.centralwidget)
        self.chartView_3.setObjectName("chartView_3")
        self.horizontalLayout_4.addWidget(self.chartView_3)
        self.init_chart(self.chartView_3, "GBP/USD")

        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.EURGBP = QtWidgets.QLabel(self.centralwidget)
        self.EURGBP.setObjectName("EURGBP")
        self.horizontalLayout_5.addWidget(self.EURGBP)
        self.chartView_4 = QtChart.QChartView(self.centralwidget)
        self.chartView_4.setObjectName("chartView_4")
        self.horizontalLayout_5.addWidget(self.chartView_4)
        self.init_chart(self.chartView_4, "EUR/GBP")

        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.USDCHF = QtWidgets.QLabel(self.centralwidget)
        self.USDCHF.setObjectName("USDCHF")
        self.horizontalLayout_6.addWidget(self.USDCHF)
        self.chartView_5 = QtChart.QChartView(self.centralwidget)
        self.chartView_5.setObjectName("chartView_5")
        self.horizontalLayout_6.addWidget(self.chartView_5)
        self.init_chart(self.chartView_5, "USD/CHF")

        self.verticalLayout.addLayout(self.horizontalLayout_6)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.EURJPY = QtWidgets.QLabel(self.centralwidget)
        self.EURJPY.setObjectName("EURJPY")
        self.horizontalLayout_7.addWidget(self.EURJPY)
        self.chartView_6 = QtChart.QChartView(self.centralwidget)
        self.chartView_6.setObjectName("chartView_6")
        self.horizontalLayout_7.addWidget(self.chartView_6)
        self.init_chart(self.chartView_6, "EUR/JPY")

        self.verticalLayout.addLayout(self.horizontalLayout_7)
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.EURCHF = QtWidgets.QLabel(self.centralwidget)
        self.EURCHF.setObjectName("EURCHF")
        self.horizontalLayout_8.addWidget(self.EURCHF)
        self.chartView_7 = QtChart.QChartView(self.centralwidget)
        self.chartView_7.setObjectName("chartView_7")
        self.horizontalLayout_8.addWidget(self.chartView_7)
        self.init_chart(self.chartView_7, "EUR/CHF")

        self.verticalLayout.addLayout(self.horizontalLayout_8)
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")
        self.USDCAD = QtWidgets.QLabel(self.centralwidget)
        self.USDCAD.setObjectName("USDCAD")
        self.horizontalLayout_9.addWidget(self.USDCAD)
        self.chartView_8 = QtChart.QChartView(self.centralwidget)
        self.chartView_8.setObjectName("chartView_8")
        self.horizontalLayout_9.addWidget(self.chartView_8)
        self.init_chart(self.chartView_8, "USD/CAD")

        self.verticalLayout.addLayout(self.horizontalLayout_9)
        self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_10.setObjectName("horizontalLayout_10")
        self.AUDUSD = QtWidgets.QLabel(self.centralwidget)
        self.AUDUSD.setObjectName("AUDUSD")
        self.horizontalLayout_10.addWidget(self.AUDUSD)
        self.chartView_9 = QtChart.QChartView(self.centralwidget)
        self.chartView_9.setObjectName("chartView_9")
        self.horizontalLayout_10.addWidget(self.chartView_9)
        self.init_chart(self.chartView_9, "AUD/USD")

        self.verticalLayout.addLayout(self.horizontalLayout_10)
        self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_11.setObjectName("horizontalLayout_11")
        self.GBPJPY = QtWidgets.QLabel(self.centralwidget)
        self.GBPJPY.setObjectName("GBPJPY")
        self.horizontalLayout_11.addWidget(self.GBPJPY)
        self.chartView_10 = QtChart.QChartView(self.centralwidget)
        self.chartView_10.setObjectName("chartView_10")
        self.horizontalLayout_11.addWidget(self.chartView_10)
        self.init_chart(self.chartView_10, "GBP/JPY")

        self.verticalLayout.addLayout(self.horizontalLayout_11)
        self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.worker = Worker()
        self.worker.signal_rate.connect(self.update_rates)
        self.worker.signal_news.connect(self.update_news)
        self.worker.start()
 def __init__(self):
     super().__init__()
     self.apo = QtChart.QLineSeries()
     self.apo.setColor(QtCore.Qt.yellow)
     self.addSeries(self.apo)
Exemplo n.º 20
0
    def __init__(self):
        super().__init__()
        
        self.setLayout(qtw.QVBoxLayout())
            
        grpbxwidgt = qtw.QGroupBox()
        grpbxwidgt.setTitle("Visualization of Data")
        grpbxwidgt.setLayout(qtw.QVBoxLayout())

        # BAR GRAPH

        self.series = qtch.QBarSeries() 
        self.chart = qtch.QChart()      
        self.chart.addSeries(self.series) 
        self.chart.setTitle("<h5>Daily Income & Expense</h5>")
        self.chart.setAnimationOptions(qtch.QChart.SeriesAnimations)
        self.axis = qtch.QBarCategoryAxis() 
        self.chart.createDefaultAxes()
        self.chart.setAxisX(self.axis,self.series)
        self.chart.axisY(self.series).setRange(0,10000)
        self.chart.axisY(self.series).setTitleText("Money (LKR)")
        self.chart.legend().setVisible(True)
        self.chart.legend().setAlignment(qtc.Qt.AlignBottom)
        self.chartview = qtch.QChartView(self.chart)
        self.chartview.setRenderHint(qtg.QPainter.Antialiasing)


        # PIE CHART
        
        self.pieseries = qtch.QPieSeries()
        self.piechart = qtch.QChart()
        self.piechart.addSeries(self.pieseries)
        self.piechart.setTitle("Item's Sold  and Remaining")
        self.piechart.setAnimationOptions(qtch.QChart.AllAnimations)
        self.piechartview = qtch.QChartView(self.piechart)
        self.piechartview.setRenderHint(qtg.QPainter.Antialiasing)


        # selection widget
        
        product_widget = qtw.QGroupBox()
        product_widget.setTitle("Item Selection")
        product_layout = qtw.QHBoxLayout()
        product_widget.setLayout(product_layout)
        
        pushbutton = qtw.QPushButton("Filter",clicked = self.update_piechart)
        self.combobox = qtw.QComboBox(currentText = "select an item") 
        
        self.c = ComboboxModel() #comboxlist model
        self.combobox.setModel(self.c.model)

        product_layout.addWidget(self.combobox) 
        product_layout.addWidget(pushbutton)
        # calendar widget

        calendar_widget = qtw.QGroupBox()
        calendar_widget.setTitle("Date Selection")
        
        calendar_layout = qtw.QHBoxLayout()
        calendar_widget.setLayout(calendar_layout)
        # calculating the current month and current year
        
        current_month = int(datetime.now().month)
        current_year  = int(datetime.now().year)
        
        date = qtc.QDate(current_year,current_month,1)
        
        self.to_date = qtw.QDateEdit()
        to_label = qtw.QLabel("To")
        self.to_date.setCalendarPopup(True)
        
        self.to_date.setDate(date)
        
        self.from_date = qtw.QDateEdit()
        from_label = qtw.QLabel("From")
        self.from_date.setCalendarPopup(True)
        self.from_date.setDate(qtc.QDate.currentDate())
        
        pushbtn = qtw.QPushButton("Filter",clicked =self.update_data)

        
        calendar_layout.addWidget(to_label)
        calendar_layout.addWidget(self.to_date)
        calendar_layout.addWidget(from_label)
        calendar_layout.addWidget(self.from_date)
        calendar_layout.addWidget(pushbtn)
        # end of calendar widget
        
        self.chartview.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)

        self.piechartview.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        
        grpbxwidgt.layout().addWidget(calendar_widget)
        
        grpbxwidgt.layout().addWidget(self.chartview)
        
        grpbxwidgt.layout().addWidget(product_widget)

        grpbxwidgt.layout().addWidget(self.piechartview)
        self.layout().addWidget(grpbxwidgt)
Exemplo n.º 21
0
    def __init__(self):
        super().__init__()

        ################
        # Create Chart #
        ################

        # Create qchart object
        chart = qtch.QChart(title=self.chart_title)
        self.setChart(chart)

        # Setup series
        series = qtch.QStackedBarSeries()
        chart.addSeries(series)
        self.phys_set = qtch.QBarSet("Physical")
        self.swap_set = qtch.QBarSet("Swap")
        series.append(self.phys_set)
        series.append(self.swap_set)

        # Setup Data
        self.data = deque([(0, 0)] * self.num_data_points,
                          maxlen=self.num_data_points)
        for phys, swap in self.data:
            self.phys_set.append(phys)
            self.swap_set.append(swap)

        # Setup Axes
        x_axis = qtch.QValueAxis()
        x_axis.setRange(0, self.num_data_points)
        x_axis.setLabelsVisible(False)
        y_axis = qtch.QValueAxis()
        y_axis.setRange(0, 100)
        chart.setAxisX(x_axis, series)
        chart.setAxisY(y_axis, series)

        # Start refresh timer
        self.timer = qtc.QTimer(interval=1000, timeout=self.refresh_stats)
        self.timer.start()

        ###################
        # Style the chart #
        ###################
        chart.setAnimationOptions(qtch.QChart.AllAnimations)

        chart.setAnimationEasingCurve(
            qtc.QEasingCurve(qtc.QEasingCurve.OutBounce))
        chart.setAnimationDuration(1000)

        # Add shadow around the chart area
        chart.setDropShadowEnabled(True)

        # Set the theme
        chart.setTheme(qtch.QChart.ChartThemeBrownSand)

        # Configure a background brush
        gradient = qtg.QLinearGradient(chart.plotArea().topLeft(),
                                       chart.plotArea().bottomRight())
        gradient.setColorAt(0, qtg.QColor("#333"))
        gradient.setColorAt(1, qtg.QColor("#660"))
        chart.setBackgroundBrush(qtg.QBrush(gradient))

        # Background Pen draws a border around the chart
        chart.setBackgroundPen(qtg.QPen(qtg.QColor('black'), 5))

        # Set title font and brush
        chart.setTitleBrush(qtg.QBrush(qtc.Qt.white))
        chart.setTitleFont(qtg.QFont('Impact', 32, qtg.QFont.Bold))

        # Set axes fonts and brushes
        axis_font = qtg.QFont('Mono', 16)
        axis_brush = qtg.QBrush(qtg.QColor('#EEF'))
        y_axis.setLabelsFont(axis_font)
        y_axis.setLabelsBrush(axis_brush)

        # Grid lines
        grid_pen = qtg.QPen(qtg.QColor('silver'))
        grid_pen.setDashPattern([1, 1, 0, 1])
        x_axis.setGridLinePen(grid_pen)
        y_axis.setGridLinePen(grid_pen)
        y_axis.setTickCount(11)

        #Shades
        y_axis.setShadesVisible(True)
        y_axis.setShadesColor(qtg.QColor('#884'))

        # Styling the legend
        legend = chart.legend()

        # Background
        legend.setBackgroundVisible(True)
        legend.setBrush(qtg.QBrush(qtg.QColor('white')))

        # Font
        legend.setFont(qtg.QFont('Courier', 14))
        legend.setLabelColor(qtc.Qt.darkRed)

        # Markers
        legend.setMarkerShape(qtch.QLegend.MarkerShapeCircle)
Exemplo n.º 22
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(720, 500)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.view_gambar_asli = QtWidgets.QGraphicsView(self.centralwidget)
        self.view_gambar_asli.setGeometry(QtCore.QRect(0, 80, 251, 211))
        self.view_gambar_asli.setObjectName("view_gambar_asli")

        self.button_brightness = QtWidgets.QPushButton(self.centralwidget)
        self.button_brightness.setGeometry(QtCore.QRect(60, 40, 101, 32))
        self.button_brightness.setObjectName("button_brightness")
        self.button_brightness.clicked.connect(self.setBrightness)

        self.button_contrast = QtWidgets.QPushButton(self.centralwidget)
        self.button_contrast.setGeometry(QtCore.QRect(280, 40, 101, 32))
        self.button_contrast.setObjectName("button_contrast")
        self.button_contrast.clicked.connect(self.setContrast)

        self.button_grayscale = QtWidgets.QPushButton(self.centralwidget)
        self.button_grayscale.setGeometry(QtCore.QRect(110, 0, 101, 32))
        self.button_grayscale.setObjectName("button_grayscale")
        self.button_grayscale.clicked.connect(self.setGrayscale)

        self.button_invers = QtWidgets.QPushButton(self.centralwidget)
        self.button_invers.setGeometry(QtCore.QRect(220, 0, 101, 32))
        self.button_invers.setObjectName("button_invers")
        self.button_invers.clicked.connect(self.setInvers)

        self.button_auto_level = QtWidgets.QPushButton(self.centralwidget)
        self.button_auto_level.setGeometry(QtCore.QRect(330, 0, 101, 32))
        self.button_auto_level.setObjectName("button_auto_level")
        self.button_auto_level.clicked.connect(self.setAutolevel)

        self.button_load = QtWidgets.QPushButton(self.centralwidget)
        self.button_load.setGeometry(QtCore.QRect(0, 0, 101, 32))
        self.button_load.setObjectName("button_load")
        self.button_load.clicked.connect(self.loadImage)

        self.view_gambar_edit = QtWidgets.QGraphicsView(self.centralwidget)
        self.view_gambar_edit.setGeometry(QtCore.QRect(0, 290, 251, 211))
        self.view_gambar_edit.setObjectName("view_gambar_edit")

        self.value_brightness = QtWidgets.QLineEdit(self.centralwidget)
        self.value_brightness.setGeometry(QtCore.QRect(0, 40, 61, 30))
        self.value_brightness.setObjectName("value_brightness")

        self.value_contrast = QtWidgets.QLineEdit(self.centralwidget)
        self.value_contrast.setGeometry(QtCore.QRect(220, 40, 61, 30))
        self.value_contrast.setObjectName("value_contrast")

        self.chartview = QtChart.QChartView(self.centralwidget)
        self.chartview.setGeometry(QtCore.QRect(250, 80, 471, 421))
        self.chartview.setObjectName("chartview")

        MainWindow.setCentralWidget(self.centralwidget)
        self.actionLoad = QtWidgets.QAction(MainWindow)
        self.actionLoad.setObjectName("actionLoad")

        self.actionGrayscale = QtWidgets.QAction(MainWindow)
        self.actionGrayscale.setObjectName("actionGrayscale")

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Exemplo n.º 23
0
 def __init__(self):
     super().__init__()
     self.moneyFlow = QtChart.QLineSeries()
     self.moneyFlow.setColor(QtCore.Qt.red)
     self.addSeries(self.moneyFlow)
Exemplo n.º 24
0
 def setChart(self):
     cv = QtChart.QChartView()
     cv.setParent(self)
     cv.setGeometry(0, 7, self.width - 7, self.height - 16)
     cv.setChart(PublicChart())
     cv.setRenderHint(True)
Exemplo n.º 25
0
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1550, 750)

        self.gridLayout_2 = QtWidgets.QGridLayout(Form)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        # -------------------
        self.chart1 = QtChart.QChart()
        self.chart1.setMargins(QMargins(0, 0, 0, 0))
        self.chart1.setBackgroundVisible(False)
        self.chartView = QtChart.QChartView(self.chart1)
        self.chart1.legend().setVisible(False)
        self.gridLayout.addWidget(self.chartView, 1, 0, 1, 1)

        self.chart2 = QtChart.QChart()
        self.chart2.setMargins(QMargins(0, 0, 0, 0))
        self.chart2.setBackgroundVisible(False)
        self.chart2.legend().setVisible(False)
        self.chartView2 = QtChart.QChartView(self.chart2)
        self.gridLayout.addWidget(self.chartView2, 3, 0, 1, 1)

        self.chart3 = QtChart.QChart()
        self.chart3.setMargins(QMargins(0, 0, 0, 0))
        self.chart3.setBackgroundVisible(False)
        self.chart3.legend().setVisible(False)
        self.chartView3 = QtChart.QChartView(self.chart3)
        self.gridLayout.addWidget(self.chartView3, 5, 0, 1, 1)

        self.chart4 = QtChart.QChart()
        self.chart4.setMargins(QMargins(0, 0, 0, 0))
        self.chart4.setBackgroundVisible(False)
        self.chart4.legend().setVisible(False)
        self.chartView4 = QtChart.QChartView(self.chart4)
        self.gridLayout.addWidget(self.chartView4, 7, 0, 1, 1)
        #-------------------
        self.label = QtWidgets.QLabel()
        self.label.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)

        self.label_GAIN = QtWidgets.QLabel('15')
        self.label_GAIN.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.label_GAIN.setFont(font)
        self.label_GAIN.setAlignment(QtCore.Qt.AlignCenter)

        self.gridLayout.addWidget(self.label_GAIN, 0, 1, 1, 2)
        self.gridLayout.addWidget(self.label, 0, 0, 1, 2)

        self.label2 = QtWidgets.QLabel()
        self.label2.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label2.setFont(font)
        self.label2.setAlignment(QtCore.Qt.AlignCenter)

        self.label_2GAIN = QtWidgets.QLabel('15')
        self.label_2GAIN.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.label_2GAIN.setFont(font)
        self.label_2GAIN.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout.addWidget(self.label_2GAIN, 2, 1, 1, 2)
        self.gridLayout.addWidget(self.label2, 2, 0, 1, 2)

        self.label3 = QtWidgets.QLabel()
        self.label3.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label3.setFont(font)
        self.label3.setAlignment(QtCore.Qt.AlignCenter)

        self.label_3GAIN = QtWidgets.QLabel('15')
        self.label_3GAIN.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.label_3GAIN.setFont(font)
        self.label_3GAIN.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout.addWidget(self.label_3GAIN, 4, 1, 1, 2)

        self.gridLayout.addWidget(self.label3, 4, 0, 1, 2)

        self.label4 = QtWidgets.QLabel()
        self.label4.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label4.setFont(font)
        self.label4.setAlignment(QtCore.Qt.AlignCenter)

        self.label_4GAIN = QtWidgets.QLabel('15')
        self.label_4GAIN.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.label_4GAIN.setFont(font)
        self.label_4GAIN.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout.addWidget(self.label_4GAIN, 6, 1, 1, 2)
        self.gridLayout.addWidget(self.label4, 6, 0, 1, 2)
        # -------------------

        self.verticalSlider = QtWidgets.QSlider()
        self.verticalSlider.setSliderPosition(15)
        self.verticalSlider.setMaximum(40)
        self.verticalSlider.setMinimum(10)
        self.verticalSlider.setSingleStep(1)
        self.verticalSlider.setOrientation(QtCore.Qt.Vertical)
        self.verticalSlider.setObjectName("verticalSlider")
        self.verticalSlider.setEnabled(False)
        # self.verticalSlider.setTickInterval(10)
        # self.verticalSlider.setTracking(False)
        self.gridLayout.addWidget(self.verticalSlider, 1, 1, 1, 1)

        self.verticalSlider2 = QtWidgets.QSlider()
        self.verticalSlider2.setSingleStep(1)
        self.verticalSlider2.setSliderPosition(15)
        self.verticalSlider2.setMaximum(40)
        self.verticalSlider2.setMinimum(10)
        self.verticalSlider2.setOrientation(QtCore.Qt.Vertical)
        self.verticalSlider2.setObjectName("verticalSlider")
        self.verticalSlider2.setEnabled(False)
        self.gridLayout.addWidget(self.verticalSlider2, 3, 1, 1, 1)

        self.verticalSlider3 = QtWidgets.QSlider()
        # self.verticalSlider3.setTickInterval(10)
        self.verticalSlider3.setSingleStep(1)
        self.verticalSlider3.setSliderPosition(15)
        self.verticalSlider3.setMaximum(40)
        self.verticalSlider3.setMinimum(10)
        self.verticalSlider3.setOrientation(QtCore.Qt.Vertical)
        self.verticalSlider3.setObjectName("verticalSlider")
        self.verticalSlider3.setEnabled(False)
        self.gridLayout.addWidget(self.verticalSlider3, 5, 1, 1, 1)

        self.verticalSlider4 = QtWidgets.QSlider()
        self.verticalSlider4.setSingleStep(1)
        self.verticalSlider4.setSliderPosition(15)
        self.verticalSlider4.setMaximum(40)
        self.verticalSlider4.setMinimum(10)
        self.verticalSlider4.setOrientation(QtCore.Qt.Vertical)
        self.verticalSlider4.setObjectName("verticalSlider")
        self.verticalSlider4.setEnabled(False)
        self.gridLayout.addWidget(self.verticalSlider4, 7, 1, 1, 1)

        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
Exemplo n.º 26
0
    def updateIndicator(self, data, candles_visible):
        # fastk, fastd = STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
        fastK, fastD = talib.STOCHRSI(data[4],
                                      timeperiod=14,
                                      fastk_period=5,
                                      fastd_period=3,
                                      fastd_matype=0)
        firstNotNan = np.where(np.isnan(fastK))[0][-1] + 1
        fastK[:firstNotNan] = fastK[firstNotNan]
        firstNotNan = np.where(np.isnan(fastD))[0][-1] + 1
        fastD[:firstNotNan] = fastD[firstNotNan]

        fastK = fastK[-candles_visible:]
        fastD = fastD[-candles_visible:]

        self.fastK.clear()
        self.fastD.clear()
        for i in range(candles_visible):
            self.fastK.append(i + 0.5, fastK[i])
            self.fastD.append(i + 0.5, fastD[i])

        self.top_line.clear()
        self.bottom_line.clear()
        self.top_line.append(0, 80)
        self.top_line.append(candles_visible, 80)
        self.bottom_line.append(0, 20)
        self.bottom_line.append(candles_visible, 20)

        # detach and remove old axes
        for ax in self.fastK.attachedAxes():
            self.fastK.detachAxis(ax)
        for ax in self.fastD.attachedAxes():
            self.fastD.detachAxis(ax)
        for ax in self.area.attachedAxes():
            self.area.detachAxis(ax)
        for ax in self.axes():
            self.removeAxis(ax)

        # set x axes
        ax = QtChart.QValueAxis()
        ax.setRange(0, candles_visible)
        ax.hide()

        # set y axes
        ay = QtChart.QValueAxis()
        ay.setRange(0, 100)
        ay.setGridLinePen(QtGui.QPen(QtGui.QColor(80, 80, 80), 0.5))
        ay.setLinePen(QtGui.QPen(QtGui.QColor(0, 0, 0), 0.5))
        ay.applyNiceNumbers()
        ay.setTickCount(3)

        # add and attach new axes
        self.addAxis(ax, QtCore.Qt.AlignBottom)
        self.addAxis(ay, QtCore.Qt.AlignRight)
        self.fastK.attachAxis(ax)
        self.fastK.attachAxis(ay)
        self.fastD.attachAxis(ax)
        self.fastD.attachAxis(ay)

        self.area.attachAxis(ax)
        self.area.attachAxis(ay)
Exemplo n.º 27
0
 def add_chart(self, radius, profile, preset, fontname, fontsize, color,
               switchXY, kwargs):
     if self.type == 'Polar':
         pen1 = QtGui.QPen(QtCore.Qt.SolidLine)
         pen1.setWidth(3)
         pen1.setColor(QtGui.QColor(color))
         pen2 = QtGui.QPen(QtCore.Qt.DotLine)
         pen2.setWidth(3)
         pen2.setColor(QtGui.QColor(color))
         if preset == 'IA':
             Phi1 = profile
             Phi2 = profile + np.full(len(profile), 180)
             Radius = radius / np.amax(radius)
         elif preset == 'FA':
             Phi1 = profile
             Phi2 = profile + np.full(len(profile), 180)
             Radius = radius
         elif preset == 'general':
             Phi = profile
             Radius = radius
         series1 = QtChart.QLineSeries()
         series1.setPen(pen1)
         series2 = QtChart.QLineSeries()
         series2.setPen(pen2)
         self.currentRadius = []
         self.currentProfile = []
         if not switchXY:
             for x, y in zip(Phi1, Radius):
                 series1.append(x, y)
                 self.currentRadius.append(x)
                 self.currentProfile.append(y)
             for x, y in zip(Phi2, Radius):
                 series2.append(x, y)
                 self.currentRadius.append(x)
                 self.currentProfile.append(y)
         else:
             for y, x in zip(Phi1, Radius):
                 series1.append(x, y)
                 self.currentRadius.append(x)
                 self.currentProfile.append(y)
             for y, x in zip(Phi2, Radius):
                 series2.append(x, y)
                 self.currentRadius.append(x)
                 self.currentProfile.append(y)
         self.profileChart = QtChart.QPolarChart()
         self.profileChart.setTheme(self.theme)
         self.profileChart.setBackgroundRoundness(0)
         self.profileChart.setMargins(QtCore.QMargins(0, 0, 0, 0))
         self.profileChart.removeAllSeries()
         self.profileChart.addSeries(series1)
         self.profileChart.addSeries(series2)
         self.profileChart.setTitleFont(QtGui.QFont(fontname, fontsize, 57))
         self.profileChart.legend().setVisible(False)
         self.axisR = QtChart.QValueAxis()
         self.axisR.setTickCount(10)
         self.axisR.setLabelFormat("%.1f")
         self.axisR.setLabelsFont(QtGui.QFont(fontname, fontsize, 57))
         self.axisR.setTitleFont(QtGui.QFont(fontname, fontsize, 57))
         self.axisP = QtChart.QValueAxis()
         self.axisP.setTickCount(13)
         self.axisP.setLabelFormat("%.1f")
         self.axisP.setRange(0, 360)
         self.axisP.setLabelsFont(QtGui.QFont(fontname, fontsize, 57))
         self.axisP.setTitleFont(QtGui.QFont(fontname, fontsize, 57))
         if preset == 'IA':
             z = kwargs['Kp']
             low = kwargs['low']
             high = kwargs['high']
             self.profileChart.setTitle(
                 'Intensity vs Azimuth at Kperp = {:6.2f} (\u212B\u207B\u00B9)'
                 .format(z))
             self.axisR.setTitleText('Intensity (arb. units)')
             self.axisR.setRange(low, high)
         elif preset == 'FA':
             z = kwargs['Kp']
             low = kwargs['low']
             high = kwargs['high']
             self.profileChart.setTitle(
                 'HWHM vs Azimuth at Kperp = {:6.2f} (\u212B\u207B\u00B9)'.
                 format(z))
             self.axisR.setTitleText('HWHM (\u212B\u207B\u00B9)')
             self.axisR.setRange(low, high)
         elif preset == 'general':
             title = kwargs['title']
             r_label = kwargs['r_label']
             r_unit = kwargs['r_unit']
             low = kwargs['low']
             high = kwargs['high']
             self.profileChart.setTitle(title)
             self.axisR.setTitleText(r_label + " (" + r_unit + ")")
             self.axisR.setRange(low, high)
         self.profileChart.addAxis(
             self.axisR, QtChart.QPolarChart.PolarOrientationRadial)
         self.profileChart.addAxis(
             self.axisP, QtChart.QPolarChart.PolarOrientationAngular)
         series1.attachAxis(self.axisR)
         series1.attachAxis(self.axisP)
         series2.attachAxis(self.axisR)
         series2.attachAxis(self.axisP)
         self.chartView.setChart(self.profileChart)
         self.chartView.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
         self.CHART_IS_PRESENT = True
     elif self.type == 'Normal':
         pen = QtGui.QPen(QtCore.Qt.SolidLine)
         pen.setWidth(3)
         pen.setColor(QtGui.QColor(color))
         series = QtChart.QLineSeries()
         series.setPen(pen)
         self.currentRadius = []
         self.currentProfile = []
         if not switchXY:
             for x, y in zip(radius, profile):
                 series.append(x, y)
                 self.currentRadius.append(x)
                 self.currentProfile.append(y)
         else:
             for y, x in zip(radius, profile):
                 series.append(x, y)
                 self.currentRadius.append(x)
                 self.currentProfile.append(y)
         self.profileChart = QtChart.QChart()
         self.profileChart.setTheme(self.theme)
         self.profileChart.setBackgroundRoundness(0)
         self.profileChart.setMargins(QtCore.QMargins(0, 0, 0, 0))
         self.profileChart.removeAllSeries()
         self.profileChart.addSeries(series)
         self.profileChart.setTitleFont(QtGui.QFont(fontname, fontsize, 57))
         self.profileChart.legend().setVisible(False)
         self.axisX = QtChart.QValueAxis()
         self.axisX.setTickCount(10)
         self.axisX.setLabelsFont(QtGui.QFont(fontname, fontsize, 57))
         self.axisX.setTitleFont(QtGui.QFont(fontname, fontsize, 57))
         self.axisY = QtChart.QValueAxis()
         self.axisY.setTickCount(10)
         self.axisY.setLabelsFont(QtGui.QFont(fontname, fontsize, 57))
         self.axisY.setTitleFont(QtGui.QFont(fontname, fontsize, 57))
         if preset == "IK":
             Az = kwargs['Az']
             self.profileChart.setTitle(
                 'Intensity vs Kperp at \u03C6 = {:5.1f} (\u00BA)'.format(
                     Az))
             self.axisX.setTitleText("Intensity (arb. units)")
             self.axisY.setTitleText("Kperp (\u212B\u207B\u00B9)")
         elif preset == "FK":
             Az = kwargs['Az']
             self.profileChart.setTitle(
                 'HWHM vs Kperp at \u03C6 = {:5.1f} (\u00BA)'.format(Az))
             self.axisX.setTitleText("HWHM (\u212B\u207B\u00B9)")
             self.axisY.setTitleText("Kperp (\u212B\u207B\u00B9)")
         elif preset == "general":
             title = kwargs['title']
             x_label = kwargs['x_label']
             x_unit = kwargs['x_unit']
             y_label = kwargs['y_label']
             y_unit = kwargs['y_unit']
             self.profileChart.setTitle(title)
             self.axisX.setTitleText(x_label + " (" + x_unit + ")")
             self.axisY.setTitleText(y_label + " (" + y_unit + ")")
         self.profileChart.addAxis(self.axisX, QtCore.Qt.AlignBottom)
         self.profileChart.addAxis(self.axisY, QtCore.Qt.AlignLeft)
         series.attachAxis(self.axisX)
         series.attachAxis(self.axisY)
         self.profileChart.legend().setVisible(False)
         self.chartView.setChart(self.profileChart)
         self.chartView.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
         self.CHART_IS_PRESENT = True
Exemplo n.º 28
0
    def coinTableChangedSlot(self):
        # update new values

        # todo: display all displayCurrencies
        taxCoinName = settings.mySettings.reportCurrency()
        numberOfDecimals = 4

        # initialize local vars
        # total invested fiat
        totalInvestFiat = core.CoinValue()
        # total returned fiat
        totalReturnFiat = core.CoinValue()
        # fiat performance
        # fiatPerformance = core.CoinValue()

        # invested value of current holdings
        currentInvestNoFiat = core.CoinValue()
        # current value of current holdings (hypothetical)
        hypotheticalCoinValueNoFiat = core.CoinValue()
        # current performance of current holdings (hypothetical)
        # hypotheticalPerformanceNoFiat = core.CoinValue()

        # realized profit (relevant for tax)
        realizedProfit = core.CoinValue()
        # unrealized profit (would be relevant for tax if realized)
        # unrealizedProfit = core.CoinValue()
        # paid fees
        paidFees = core.CoinValue()

        # testing
        # currentInvestAll = core.CoinValue()
        # hypotheticalValueAll = core.CoinValue()
        # realizedProfitAll = core.CoinValue()
        if self.controller.tradeList.isEmpty():
            startYear = datetime.datetime.now().year
        else:
            startYear = min([trade.date for trade in self.controller.tradeList]).year
        stopYear = datetime.datetime.now().year
        realizedProfitPerYear = {}
        paidFeesPerYear = {}
        fiatPerYear = {}
        taxProfitPerYear = {}
        rewardPerYear = {}

        for year in range(startYear, stopYear+1):
            realizedProfitPerYear[str(year)] = core.CoinValue()
            paidFeesPerYear[str(year)] = core.CoinValue()
            fiatPerYear[str(year)] = core.CoinValue()
            taxProfitPerYear[str(year)] = core.CoinValue()
            rewardPerYear[str(year)] = core.CoinValue()

        # calculate all needed values
        for coin in self.model:
            if coin.isFiat():  # calculate invested and returned fiat
                for trade in coin.trades:
                    # only add fiat trade if partner trade is not fiat
                    isFiatCryptoTrade = True
                    if trade.tradePartnerId:
                        if self.controller.tradeList.getTradeById(trade.tradePartnerId):
                            if self.controller.tradeList.getTradeById(trade.tradePartnerId).isFiat():
                                isFiatCryptoTrade = False
                    if isFiatCryptoTrade:
                        if trade.amount < 0:
                            totalInvestFiat.add(trade.getValue().mult(-1))
                        else:
                            totalReturnFiat.add(trade.getValue())
                        # fiat invest/ return per year
                        for year in range(startYear, stopYear + 1):
                            startDate = datetime.date(year=year, month=1, day=1)
                            endDate = datetime.date(year=year, month=12, day=31)
                            if trade.date.date() >= startDate and trade.date.date() <= endDate:
                                fiatPerYear[str(year)].add(trade.getValue())

            else:  # calculate value of portfolio
                currentInvestNoFiat.add(coin.initialValue)
                hypotheticalCoinValueNoFiat.add(coin.getCurrentValue())
                realizedProfit.add(coin.getTotalProfit())
            # calc fees per year
            for trade in coin.trades:
                if trade.tradeType == "fee":
                    paidFees.add(trade.getValue())
                    for year in range(startYear, stopYear + 1):
                        startDate = datetime.date(year=year, month=1, day=1)
                        endDate = datetime.date(year=year, month=12, day=31)
                        if trade.date.date() >= startDate and trade.date.date() <= endDate:
                            paidFeesPerYear[str(year)].add(trade.getValue())

            for year in range(startYear, stopYear + 1):
                startDate = datetime.date(year=year, month=1, day=1)
                endDate = datetime.date(year=year, month=12, day=31)
                taxProfitPerYear[str(year)].add(coin.getTimeDeltaProfitTaxable(startDate, endDate))
                rewardPerYear[str(year)].add(coin.getTimeDeltaReward(startDate, endDate))
                realizedProfitPerYear[str(year)].add(coin.getTimeDeltaProfit(startDate, endDate))
            # fiat and coins
            # currentInvestAll.add(coin.initialValue)
            # hypotheticalValueAll.add(coin.getCurrentValue())
            # realizedProfitAll.add(coin..getTotalProfit())

        fiatPerformance = (totalReturnFiat-totalInvestFiat).div(totalInvestFiat).mult(100)
        hypotheticalPerformanceNoFiat = (hypotheticalCoinValueNoFiat.div(currentInvestNoFiat)
                                         - core.CoinValue().setValue(1)).mult(100)
        unrealizedProfit = hypotheticalCoinValueNoFiat - currentInvestNoFiat

        def setLabelColor(label, isPositiv):
            if isPositiv:
                label.setBodyColor(self.posColor.name())
            else:
                label.setBodyColor(self.negColor.name())

        # tax value chart
        self.currentValueChart.chartView.setText(
            [controls.floatToString(currentInvestNoFiat[taxCoinName], numberOfDecimals) + ' ' + taxCoinName,
             controls.floatToString(hypotheticalCoinValueNoFiat[taxCoinName], numberOfDecimals) + ' ' + taxCoinName,
             "%.2f%%" % hypotheticalPerformanceNoFiat[taxCoinName]])

        self.currentValueChart.setLabelToolTip(['current invest', 'current value', 'performance'])

        if unrealizedProfit[taxCoinName] < 0:
            self.donutSliceInvested.setValue(currentInvestNoFiat[taxCoinName]+unrealizedProfit[taxCoinName])
            self.donutSliceInvested.setColor(self.neutrColor)
            self.donutSlicePerformance.setValue(-unrealizedProfit[taxCoinName])
            self.donutSlicePerformance.setColor(self.negColor)
            # self.donutSlicePerformance.setLabelColor(self.negColor)
            self.currentValueChart.chartView.setColor([self.neutrColor, self.negColor, self.negColor])
        else:
            self.donutSliceInvested.setValue(currentInvestNoFiat[taxCoinName])
            self.donutSliceInvested.setColor(self.neutrColor)
            self.donutSlicePerformance.setValue(unrealizedProfit[taxCoinName])
            self.donutSlicePerformance.setColor(self.posColor)
            # self.donutSlicePerformance.setLabelColor(self.posColor)
            self.currentValueChart.chartView.setColor([self.neutrColor, self.posColor, self.posColor])

        # fiat value chart
        self.currentFiatValueChart.chartView.setText(
            [controls.floatToString(totalInvestFiat[taxCoinName], numberOfDecimals) + ' ' + taxCoinName,
             controls.floatToString(hypotheticalCoinValueNoFiat[taxCoinName], numberOfDecimals) + ' ' + taxCoinName,
             controls.floatToString(totalReturnFiat[taxCoinName], numberOfDecimals) + ' ' + taxCoinName], qt.AlignCenter)

        self.currentFiatValueChart.setLabelToolTip(['fiat invest', 'current value', 'fiat return'])

        self.sliceFiatInvested.setValue(totalInvestFiat[taxCoinName])
        self.sliceFiatInvested.setColor(self.neutrColor)
        self.sliceFiatReturn.setValue(totalReturnFiat[taxCoinName])
        self.sliceFiatReturn.setColor(self.styleHandler.getQColor('PRIMARY'))
        self.sliceCoinValue.setValue(hypotheticalCoinValueNoFiat[taxCoinName])

        if (hypotheticalCoinValueNoFiat[taxCoinName] + totalReturnFiat[taxCoinName]) \
                < totalInvestFiat[taxCoinName]:
            self.sliceCoinValue.setColor(self.negColor)
            self.currentFiatValueChart.chartView.setColor([self.neutrColor, self.negColor,
                                                           self.styleHandler.getQColor('PRIMARY')])
        else:
            self.sliceCoinValue.setColor(self.posColor)
            self.currentFiatValueChart.chartView.setColor([self.neutrColor, self.posColor,
                                                           self.styleHandler.getQColor('PRIMARY')])

        # profit table
        years = []
        for year in realizedProfitPerYear:
            years.append(year)
        self.profitTable.setRowCount(len(years))
        self.profitTable.setVerticalHeaderLabels(years)
        for year, row in zip(realizedProfitPerYear, range(len(realizedProfitPerYear))):
            self.profitTable.setItem(row, 0, qtwidgets.QTableWidgetItem(
                controls.floatToString(realizedProfitPerYear[year][taxCoinName] + rewardPerYear[year][taxCoinName], 5) + ' ' + taxCoinName))
            self.profitTable.setItem(row, 1, qtwidgets.QTableWidgetItem(
                controls.floatToString(taxProfitPerYear[year][taxCoinName] + rewardPerYear[year][taxCoinName], 5) + ' ' + taxCoinName))
            self.profitTable.setItem(row, 2, qtwidgets.QTableWidgetItem(
                controls.floatToString(paidFeesPerYear[year][taxCoinName], 5) + ' ' + taxCoinName))
            self.profitTable.setItem(row, 3, qtwidgets.QTableWidgetItem(
                controls.floatToString(fiatPerYear[year][taxCoinName], 5) + ' ' + taxCoinName))


        # pie chart
        pieSeries = qtchart.QPieSeries()
        sortedModelIndex = sorted(range(len(self.model)),
                                  key=lambda x: self.model.coins[x].getCurrentValue()[taxCoinName], reverse=True)
        otherssum = core.CoinValue()
        try:
            topvalue = self.model.coins[sortedModelIndex[0]].getCurrentValue()[taxCoinName]
        except IndexError:
            topvalue = 0
        for index in sortedModelIndex:
            coin = self.model.coins[index]
            if not coin.isFiat():
                if coin.getCurrentValue()[taxCoinName] > topvalue/40 and \
                        coin.getCurrentValue()[taxCoinName] > abs(hypotheticalCoinValueNoFiat[taxCoinName]/75):
                    pieSeries.append(coin.coinname, coin.getCurrentValue()[taxCoinName])
                elif coin.getCurrentValue()[taxCoinName] > 0:
                    otherssum.add(coin.getCurrentValue())
        if otherssum[taxCoinName] > abs(hypotheticalCoinValueNoFiat[taxCoinName]/100):
            slice = pieSeries.append("others", otherssum[taxCoinName])
            slice.setLabelVisible()

        # if len(pieSeries.slices()) > 5:
        #     for slice in pieSeries.slices()[0:5]:
        #         if slice.value() > hypotheticalCoinValueNoFiat[taxCoinName]/20:
        #             slice.setLabelVisible()
        # else:
        for slice in pieSeries.slices():
            if slice.value() > abs(hypotheticalCoinValueNoFiat[taxCoinName]/20):
                slice.setLabelVisible()

        color = [255, 75, 225]
        for slice in pieSeries.slices():
            color = style.nextColor(color, 55)
            slice.setBrush(qtgui.QColor(*tuple(color)))
            slice.setLabelColor(qtgui.QColor(*tuple(color)))
            slice.setLabelPosition(qtchart.QPieSlice.LabelOutside)

        pieSeries.setHoleSize(0.6)
        self.portfolioChart.setSeries(pieSeries)
        portfolioChartLabels = []
        for coin in hypotheticalCoinValueNoFiat:
            portfolioChartLabels.append(controls.floatToString(hypotheticalCoinValueNoFiat[coin],
                                                               numberOfDecimals) + ' ' + coin)
        self.portfolioChart.chartView.setText(portfolioChartLabels, qt.AlignCenter)
        self.portfolioChart.chartView.setColor(self.neutrColor, False)
Exemplo n.º 29
0
    def __init__(self, weather_points: List[Weather], settings, main_ui):
        QtWidgets.QWidget.__init__(self)

        # set up  window style and size
        # frameless modal window fullscreen (same as main ui)
        self.setWindowFlags(Qt.WindowType(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint))
        self.setWindowModality(Qt.WindowModal)
        self.setGeometry(main_ui.geometry())

        # create series from weather points
        series = QtChart.QLineSeries(self)
        self._weather_points = weather_points

        # sort weather points dataset?

        for point in weather_points:
            series.append(QtCore.QPointF(point.date_time.timestamp() * 1000, point.temp))

        self.begin_hour = (min([point.date_time for point in weather_points])).timestamp() * 1000
        self.end_hour = (max([point.date_time for point in weather_points])).timestamp() * 1000
        # get min and max temp
        min_temp = min([point.temp for point in weather_points])
        max_temp = max([point.temp for point in weather_points])

        # start displaying from -20 - so that the icons have enough space
        begin_temp = min_temp - 20

        # this is a dummy which marks the bottom of the areas series - so we can color the whole thing
        series_dummy = QtChart.QLineSeries(self)
        series_dummy.append(self.begin_hour, begin_temp)
        series_dummy.append(self.end_hour, begin_temp)

        area = QtChart.QAreaSeries(series, series_dummy)
        area.setBrush(QtGui.QColor(self.AREA_COLOR))

        # init a generic font
        font = QtGui.QFont()
        font.setPixelSize(16)

        # PointLabels do not work on area - we need to draw both
        series.setPointLabelsVisible(True)
        series.setPointLabelsColor(Qt.white)
        series.setPointLabelsFont(font)
        series.setPointLabelsFormat("@yPoint")
        series.setPointLabelsClipping(True)

        # draw a dashed line at the first tick of y axis
        pen = QtGui.QPen(Qt.DashLine)
        pen.setColor(Qt.white)
        pen.setStyle(Qt.DashLine)
        dashed_line_series = QtChart.QLineSeries(self)  # QSplineSeries()
        dashed_line_series.setPen(pen)
        self.first_tick = round((max_temp - round(begin_temp)) / (5 - 1) +
                                round(begin_temp), 1)  # chart.axisY().tickCount()

        dashed_line_series.append(QtCore.QPointF(self.begin_hour, self.first_tick))
        dashed_line_series.append(QtCore.QPointF(self.end_hour, self.first_tick))

        # chart setup
        chart = QtChart.QChart()
        self._chart = chart
        chart.addSeries(series)
        chart.addSeries(area)
        chart.addSeries(dashed_line_series)

        # visual style
        chart.legend().setVisible(False)
        chart.setTitle(f"{settings.get(LOCATION)} " +
                       common.get_localized_date(weather_points[0].date_time, settings))
        font.setPixelSize(24)
        chart.setTitleFont(font)

        # chart axis
        chart.createDefaultAxes()
        chart.axisY().setTitleText("Temperature [Celsius]")
        chart.axisY().setGridLineVisible(False)
        chart.axisY().setVisible(False)
        chart.axisY().setLineVisible(False)

        chart.axisY(series).setRange(begin_temp, round(max_temp) + 5)

        chart.axisX().setRange(self.begin_hour - 1800000, self.end_hour + 1800000)
        axisX = QtChart.QDateTimeAxis()
        axisX.setFormat("h:mm")
        chart.setAxisX(axisX, series)
        chart.axisX().setGridLineVisible(False)

        # gradient for background
        gradient = QtGui.QLinearGradient(0, 0, 0, self.height())
        gradient.setColorAt(0, QtGui.QColor(13, 119, 167))  # light blue
        gradient.setColorAt(1, QtGui.QColor(115, 158, 201))  # lighetr blue
        pen = QtGui.QPen()
        pen.setColor(QtGui.QColor(Qt.transparent))
        brush = QtGui.QBrush(gradient)
        brush.setStyle(Qt.LinearGradientPattern)
        chart.setBackgroundBrush(brush)
        geo = main_ui.geometry()
        chart.setGeometry(geo.x(), geo.y(), SCREEN_WIDTH, SCREEN_HEIGHT)

        # display on a chart view
        chart_view = QtChart.QChartView(chart)
        self._chart_view = chart_view
        chart_view.setRenderHint(QtGui.QPainter.Antialiasing)
        chart_view.setSizeAdjustPolicy(QtChart.QChartView.AdjustToContents)

        # Button to close
        ok_button = QtWidgets.QPushButton("OK", self)
        ok_button.clicked.connect(self.close)

        self._layout = QtWidgets.QVBoxLayout(self)
        self._layout.setGeometry(geo)
        self._layout.setSizeConstraint(QtWidgets.QLayout.SetMinAndMaxSize)

        self._layout.addWidget(chart_view)
        self._layout.addWidget(ok_button)

        self.installEventFilter(self)
Exemplo n.º 30
0
	def add_series(self, name):
		self.series_ = series = QtChart.QLineSeries()
		series.setName(name)
		self.addSeries(series)
		series.attachAxis(self.axis_x)
		series.attachAxis(self.axis_y)