Пример #1
0
    def addCandle(self, open, close, high, low, timestamp):
        candlestickSet = QCandlestickSet()
        candlestickSet.setOpen(open)
        candlestickSet.setClose(close)
        candlestickSet.setHigh(high)
        candlestickSet.setLow(low)
        candlestickSet.setTimestamp(timestamp)

        pen = QPen()
        candlestickSet.setPen(pen)
        self.candleSeries.append(candlestickSet)
    def read_candlestick_set(self):

        line = self.readLine()

        if line.startswith("#") or line is None:
            return None

        (timestamp, open_, high, low,
         close) = line.split(" ")  # SkipEmptyParts\

        candlestickset = QCandlestickSet(float(timestamp))
        candlestickset.setOpen(float(open_))
        candlestickset.setHigh(float(high))
        candlestickset.setLow(float(low))
        candlestickset.setClose(float(close))

        return candlestickset
Пример #3
0
    def readCandlestickSet(self):
        line = self.readLine()
        if line.startswith("#") or not line:
            return

        strList = line.split(" ")
        if len(strList) != 5:
            return

        timestamp, _open, high, low, close = [float(v) for v in strList]

        candlestickSet = QCandlestickSet(timestamp)
        candlestickSet.setOpen(_open)
        candlestickSet.setHigh(high)
        candlestickSet.setLow(low)
        candlestickSet.setClose(close)

        return candlestickSet
Пример #4
0
class MainClass(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def getStockData(self):
        self.close()
        print("HI")

        self.mainLayout.removeWidget(self.newChartView)
        self.newSeries = QCandlestickSeries()
        self.newSeries.setName("Test Chart 2")

        self.saucePage = urllib.request.urlopen(
            'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol='
            + self.stockRequestBox.text() +
            '&interval=1min&apikey=NOC1N35PNDQOFF1A')
        self.output = self.saucePage.read()
        self.webContent = self.output.decode(
            'utf-8')  # Convert from bytes to string

        self.writePage = open(
            'stock.json', 'w'
        )  # Write webContent to a html file because otherwise i can't use readlines()
        self.writePage.write(
            self.webContent)  # It's very efficient code trust me
        self.writePage.close()

        self.sauce = json.load(open('stock.json'))

        # print(sauce["Monthly Time Series"]["2018-01-14 20:23:00"]["1. open"])
        self.openStocks = {}
        for date in self.sauce["Monthly Time Series"]:
            self.openStocks[date] = self.sauce["Monthly Time Series"][date][
                "1. open"]

        self.ordered = collections.OrderedDict(sorted(self.openStocks.items()))
        for k, v in self.ordered.items():
            dateString = k
            dt = datetime.datetime(int(dateString[:4]), int(dateString[5:7]),
                                   int(dateString[8:10]))

            self.newSet = QCandlestickSet((time.mktime(dt.timetuple()) * 1000))
            self.newSet.setOpen(float(v))
            self.newSet.setHigh(
                float(self.sauce["Monthly Time Series"][k]["2. high"]))
            self.newSet.setLow(
                float(self.sauce["Monthly Time Series"][k]["3. low"]))
            self.newSet.setClose(
                float(self.sauce["Monthly Time Series"][k]["4. close"]))
            self.newSeries.append(self.newSet)
        self.newChart = QChart()
        self.newChart.addSeries(self.newSeries)
        self.newChart.setTitle("Test Actual Chart")
        self.newChart.createDefaultAxes()
        self.newChartView = QChartView(self.newChart)
        self.mainLayout.addWidget(self.newChartView)
        self.show()

    def initUI(self):
        self.mainLayout = QVBoxLayout()
        self.stockFrame = QFrame()
        self.mainLayout.addWidget(self.stockFrame)
        self.mainButton = QPushButton("Push Me!")
        self.mainButton.clicked.connect(self.getStockData)
        self.mainLayout.addWidget(self.mainButton)

        self.stockRequestLayout = QHBoxLayout()
        self.stockRequestedLabel = QLabel("Stock: ")
        self.stockRequestLayout.addWidget(self.stockRequestedLabel)
        self.stockRequestBox = QLineEdit()
        self.stockRequestLayout.addWidget(self.stockRequestBox)

        self.mainLayout.addLayout(self.stockRequestLayout)
        self.setLayout(self.mainLayout)

        self.newSeries = QCandlestickSeries()
        self.newSeries.setName("Test Chart")

        # for i in range(1000):

        #     self.newSet = QCandlestickSet(time.time() * 1000 + (random.randint(-5, 5) * 60000))
        #     self.newSet.setOpen(random.randint(1, 10))
        #     self.newSet.setHigh(random.randint(1, 10))
        #     self.newSet.setLow(random.randint(1, 10))
        #     self.newSet.setClose(random.randint(1, 10))
        #     self.newSeries.append(self.newSet)

        # self.newSet2 = QCandlestickSet()
        # self.newSet2.setOpen(1.00)
        # self.newSet2.setHigh(10.00)
        # self.newSet2.setLow(0.50)
        # self.newSet2.setClose(5.00)
        # self.newSeries.append(self.newSet2)

        self.saucePage = urllib.request.urlopen(
            'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=BHP&apikey=NOC1N35PNDQOFF1A'
        )

        self.output = self.saucePage.read()
        self.webContent = self.output.decode(
            'utf-8')  # Convert from bytes to string

        self.writePage = open(
            'stock.json', 'w'
        )  # Write webContent to a html file because otherwise i can't use readlines()
        self.writePage.write(
            self.webContent)  # It's very efficient code trust me
        self.writePage.close()

        self.sauce = json.load(open('stock.json'))

        # print(sauce["Monthly Time Series"]["2018-01-14 20:23:00"]["1. open"])
        self.openStocks = {}
        for date in self.sauce["Monthly Time Series"]:
            self.openStocks[date] = self.sauce["Monthly Time Series"][date][
                "1. open"]

        self.ordered = collections.OrderedDict(sorted(self.openStocks.items()))
        count = 0
        for k, v in self.ordered.items():
            dateString = k
            dt = datetime.datetime(int(dateString[:4]), int(dateString[5:7]),
                                   int(dateString[8:10]))

            self.newSet = QCandlestickSet((time.mktime(dt.timetuple()) * 1000))
            self.newSet.setOpen(float(v))
            self.newSet.setHigh(
                float(self.sauce["Monthly Time Series"][k]["2. high"]))
            self.newSet.setLow(
                float(self.sauce["Monthly Time Series"][k]["3. low"]))
            self.newSet.setClose(
                float(self.sauce["Monthly Time Series"][k]["4. close"]))
            self.newSeries.append(self.newSet)
            count = count + 1
            # if count > 8:
            #     break

        self.newChart = QChart()
        self.newChart.addSeries(self.newSeries)
        self.newChart.setTitle("Test Actual Chart")
        self.newChart.createDefaultAxes()
        self.newChartView = QChartView(self.newChart)
        self.mainLayout.addWidget(self.newChartView)
        # self.subjectLabel = QLabel()
        # self.subjectLabel.setAlignment(Qt.Qt.AlignCenter)
        # self.mainLayout.addWidget(self.subjectLabel)
        # self.testLabel = QLabel()
        # self.testLabel.setAlignment(Qt.Qt.AlignCenter)
        # self.mainLayout.addWidget(self.testLabel)
        # self.randomButton = QPushButton("Choose")
        # self.randomButton.clicked.connect(self.randomDef)
        # self.mainLayout.addWidget(self.randomButton)
        # self.setLayout(self.mainLayout)
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle("Stocks")
        self.show()
Пример #5
0
    def __drawChart(self):  ##绘制图表
        self.chart.removeAllSeries()  #删除所有序列
        self.chart.setTitle("股票日线图--" + self.ui.tabWidget.tabText(0))

        ## 1. 创建蜡烛图
        seriesCandle = QCandlestickSeries()
        seriesCandle.setName("蜡烛图")
        seriesCandle.setIncreasingColor(Qt.red)  #暴涨
        seriesCandle.setDecreasingColor(Qt.darkGreen)  #暴跌

        visible = self.ui.chkBox_Outline.isChecked()
        seriesCandle.setBodyOutlineVisible(visible)
        seriesCandle.setCapsVisible(self.ui.chkBox_Caps.isChecked())

        self.chart.addSeries(seriesCandle)
        seriesCandle.attachAxis(self.__axisX)
        seriesCandle.attachAxis(self.__axisY)

        seriesCandle.clicked.connect(self.do_candleClicked)
        seriesCandle.hovered.connect(self.do_candleHovered)

        ## 2. 创建MA曲线
        pen = QPen()
        pen.setWidth(2)

        seriesMA1 = QLineSeries()  #不能使用QSplineSeries
        seriesMA1.setName("MA5")
        pen.setColor(Qt.magenta)
        seriesMA1.setPen(pen)
        self.chart.addSeries(seriesMA1)
        seriesMA1.attachAxis(self.__axisX)
        seriesMA1.attachAxis(self.__axisY)

        seriesMA2 = QLineSeries()
        seriesMA2.setName("MA10")
        pen.setColor(Qt.yellow)
        seriesMA2.setPen(pen)
        self.chart.addSeries(seriesMA2)
        seriesMA2.attachAxis(self.__axisX)
        seriesMA2.attachAxis(self.__axisY)

        seriesMA3 = QLineSeries()
        seriesMA3.setName("MA20")
        pen.setColor(Qt.cyan)
        seriesMA3.setPen(pen)
        self.chart.addSeries(seriesMA3)
        seriesMA3.attachAxis(self.__axisX)
        seriesMA3.attachAxis(self.__axisY)

        seriesMA4 = QLineSeries()
        seriesMA4.setName("MA60")
        pen.setColor(Qt.green)  #green
        seriesMA4.setPen(pen)
        self.chart.addSeries(seriesMA4)
        seriesMA4.attachAxis(self.__axisX)
        seriesMA4.attachAxis(self.__axisY)

        ## 3. 填充数据到序列
        dataRowCount = self.itemModel.rowCount()  #数据点个数
        for i in range(dataRowCount):
            dateStr = self.itemModel.item(i, 0).text()  #日期字符串,如"2017/02/03"
            dateValue = QDate.fromString(dateStr, "yyyy/MM/dd")  #QDate
            dtValue = QDateTime(dateValue)  #日期时间 QDateTime
            timeStamp = dtValue.toMSecsSinceEpoch()  #毫秒数

            oneCandle = QCandlestickSet()  #QCandlestickSet
            oneCandle.setOpen(float(self.itemModel.item(i, 1).text()))  #开盘
            oneCandle.setHigh(float(self.itemModel.item(i, 2).text()))  #最高
            oneCandle.setLow(float(self.itemModel.item(i, 3).text()))  #最低
            oneCandle.setClose(float(self.itemModel.item(i, 4).text()))  #收盘
            oneCandle.setTimestamp(timeStamp)  #时间戳
            seriesCandle.append(oneCandle)  #添加到序列

            M1 = float(self.itemModel.item(i, 5).text())
            M2 = float(self.itemModel.item(i, 6).text())
            M3 = float(self.itemModel.item(i, 7).text())
            M4 = float(self.itemModel.item(i, 8).text())

            seriesMA1.append(timeStamp, M1)
            seriesMA2.append(timeStamp, M2)
            seriesMA3.append(timeStamp, M3)
            seriesMA4.append(timeStamp, M4)

    ## 4. 设置坐标轴范围
        minDateStr = self.itemModel.item(0, 0).text()  #日期字符串,如"2017/02/03"
        minDate = QDate.fromString(minDateStr, "yyyy/MM/dd")  #QDate
        minDateTime = QDateTime(minDate)  #最小日期时间,QDateTime

        maxDateStr = self.itemModel.item(dataRowCount - 1,
                                         0).text()  #日期字符串,如"2017/05/03"
        maxDate = QDate.fromString(maxDateStr, "yyyy/MM/dd")
        maxDateTime = QDateTime(maxDate)  #最大日期时间

        self.__axisX.setRange(minDateTime, maxDateTime)  #日期时间范围
        dateFormat = self.ui.comboDateFormat.currentText()  #格式,如"MM-dd"
        self.__axisX.setFormat(dateFormat)  #标签格式

        self.__axisY.applyNiceNumbers()  #自动

        for marker in self.chart.legend().markers():  #QLegendMarker类型列表
            marker.clicked.connect(self.do_LegendMarkerClicked)