Пример #1
0
    def setUp(self):
        ## Called before testfunction is executed
        self.dataAccess = GpwCurrentStockData()

        def data_path():
            return get_data_path("akcje_2021-12-21_20-00.xls")

        self.dataAccess.dao.getDataPath = data_path  # type: ignore
        self.dataAccess.dao.storage = WorksheetStorageMock()
        self.dataAccess.dao.parseWorksheetFromFile(data_path())
Пример #2
0
    def getWalletState(self, includeCommission=True):
        currentStock: GpwCurrentStockData = self.gpwCurrentSource.stockData

        transMode = self.userContainer.transactionsMatchMode

        walletValue = 0.0
        refWalletValue = 0.0
        walletProfit = 0.0
        totalGain = 0.0
        for ticker, transactions in self.wallet.stockList.items():
            amount, buy_unit_price = transactions.currentTransactionsAvg(
                transMode)

            stockGain = transactions.transactionsGain(transMode,
                                                      includeCommission)
            totalGain += stockGain

            if amount == 0:
                continue

            currentStockRow = currentStock.getRowByTicker(ticker)
            if currentStockRow is None or currentStockRow.empty:
                _LOGGER.warning("could not find stock by ticker: %s", ticker)
                continue

            currUnitValue = GpwCurrentStockData.unitPrice(currentStockRow)

            stockValue = currUnitValue * amount
            stockProfit = stockValue
            stockProfit -= buy_unit_price * amount
            if includeCommission:
                stockProfit -= broker_commission(stockValue)

            walletValue += stockValue
            walletProfit += stockProfit

            refUnitValue = GpwCurrentStockData.unitReferencePrice(
                currentStockRow)
            referenceValue = refUnitValue * amount
            refWalletValue += referenceValue

        walletValue = round(walletValue, 2)
        walletProfit = round(walletProfit, 2)
        refWalletValue = round(refWalletValue, 2)
        if refWalletValue != 0.0:
            referenceFactor = walletValue / refWalletValue - 1
            rounded_factor = round(referenceFactor * 100, 2)
            changeToRef = f"{rounded_factor}%"
        else:
            changeToRef = "--"
        totalGain = round(totalGain, 2)
        overallProfit = walletProfit + totalGain
        overallProfit = round(overallProfit, 2)
        return (walletValue, walletProfit, changeToRef, totalGain,
                overallProfit)
Пример #3
0
 def foreground(self, index: QModelIndex ):
     dataChangeIndex = GpwCurrentStockData.getColumnIndex( StockDataType.CHANGE_TO_REF )
     dataColumn = index.column()
     ## "Zm.do k.odn.[%]"
     if dataColumn == dataChangeIndex:
         stockChangeString = index.data()
         if stockChangeString != "-":
             stockChange = float(stockChangeString)
             if stockChange > 0.0:
                 return QtGui.QColor( "green" )
 #             return QtGui.QColor( "red" )
     return None
Пример #4
0
    def __init__(self):
        self.userContainer = UserContainer()  ## user data

        self.gpwCurrentSource = StockDataWrapper(GpwCurrentStockData())
        self.gpwStockIntradayData = GpwStockIntradayMap()
        self.gpwIndexIntradayData = GpwIndexIntradayMap()

        self.gpwESPIData = GpwESPIData()

        self.gpwIndexesData = GpwCurrentIndexesData()
        self.globalIndexesData = GlobalIndexesData()
        self.gpwIndicatorsData = GpwIndicatorsData()
        self.gpwDividendsData = DividendsCalendarData()

        self.gpwReportsData = FinRepsCalendarData()
        self.gpwPubReportsData = PublishedFinRepsCalendarData()

        self.gpwCurrentShortSellingsData = CurrentShortSellingsData()
        self.gpwHistoryShortSellingsData = HistoryShortSellingsData()
    ## following import success only when file is directly executed from command line
    ## otherwise will throw exception when executing as parameter for "python -m"
    # pylint: disable=W0611
    import __init__
except ImportError:
    ## when import fails then it means that the script was executed indirectly
    ## in this case __init__ is already loaded
    pass

import logging

from stockmonitor.dataaccess.gpw.gpwcurrentdata import GpwCurrentStockData

_LOGGER = logging.getLogger(__name__)

logging.basicConfig(level=logging.DEBUG)

_LOGGER.info("loading worksheet")

dataAccess = GpwCurrentStockData()

dataAccess.loadWorksheet()

frame = dataAccess.dao.storage.worksheet
if frame is None:
    _LOGGER.warning("")
    _LOGGER.warning("unable to load data")
    _LOGGER.warning("")
else:
    _LOGGER.info("loaded data:\n%s", frame)
Пример #6
0
    def getAllTransactions(self):
        columnsList = [
            "Nazwa", "Ticker", "Liczba", "Kurs transakcji", "Kurs",
            "Zm.do k.odn.(%)", "Zysk %", "Zysk", "Data transakcji"
        ]

        currentStock: GpwCurrentStockData = self.gpwCurrentSource.stockData

        stockNameIndex = currentStock.getDataColumnIndex(
            StockDataType.STOCK_NAME)
        dataChangeIndex = currentStock.getDataColumnIndex(
            StockDataType.CHANGE_TO_REF)

        rowsList = []

        for ticker, transactions in self.wallet.stockList.items():
            currentStockRow = currentStock.getRowByTicker(ticker)
            if currentStockRow.empty:
                _LOGGER.warning("could not find stock by ticker: %s", ticker)
                currTransactions = transactions.allTransactions()
                for item in currTransactions:
                    trans_amount = item[0]
                    trans_unit_price = item[1]
                    trans_date = item[2]
                    rowsList.append([
                        "-", ticker, trans_amount, trans_unit_price, "-", "-",
                        "-", "-", trans_date
                    ])
                continue

            stockName = currentStockRow.iloc[stockNameIndex]
            currAmount = transactions.currentAmount()

            currUnitValue = GpwCurrentStockData.unitPrice(currentStockRow)

            currChangeRaw = currentStockRow.iloc[dataChangeIndex]
            currChange = 0
            if currChangeRaw != "-":
                currChange = float(currChangeRaw)

            currTransactions = transactions.allTransactions()
            for item in currTransactions:
                trans_amount = item[0]
                trans_unit_price = item[1]
                trans_date = item[2]

                if currAmount <= 0:
                    trans_unit_price = round(trans_unit_price, 4)
                    profitPnt = "-"
                    profit = "-"
                else:
                    currValue = abs(currUnitValue * trans_amount)
                    buyValue = abs(trans_unit_price * trans_amount)

                    profit = currValue - buyValue
                    profitPnt = 0
                    if buyValue != 0:
                        profitPnt = profit / buyValue * 100.0

                    trans_unit_price = round(trans_unit_price, 4)
                    profitPnt = round(profitPnt, 2)
                    profit = round(profit, 2)

                rowsList.append([
                    stockName, ticker, trans_amount, trans_unit_price,
                    currUnitValue, currChange, profitPnt, profit, trans_date
                ])

        dataFrame = DataFrame.from_records(rowsList, columns=columnsList)
        return dataFrame
Пример #7
0
    def getWalletBuyTransactions(self):
        columnsList = [
            "Nazwa", "Ticker", "Liczba", "Kurs transakcji", "Kurs",
            "Zm.do k.odn.(%)", "Zysk %", "Zysk", "Data transakcji"
        ]

        currentStock: GpwCurrentStockData = self.gpwCurrentSource.stockData

        stockNameIndex = currentStock.getDataColumnIndex(
            StockDataType.STOCK_NAME)
        dataChangeIndex = currentStock.getDataColumnIndex(
            StockDataType.CHANGE_TO_REF)

        rowsList = []

        transMode = self.userContainer.transactionsMatchMode

        ticker: str
        transactions: TransHistory
        for ticker, transactions in self.wallet.stockList.items():
            #             if ticker == "PCX":
            #                 print( "xxxxx:\n", transactions.items() )
            currentStockRow = currentStock.getRowByTicker(ticker)
            if currentStockRow is None or currentStockRow.empty:
                _LOGGER.warning("could not find stock by ticker: %s", ticker)
                currTransactions = transactions.currentTransactions(transMode)
                for item in currTransactions:
                    trans_amount = item[0]
                    trans_unit_price = item[1]
                    trans_date = item[2]
                    rowsList.append([
                        "-", ticker, trans_amount, trans_unit_price, "-", "-",
                        "-", "-", trans_date
                    ])
                continue

            stockName = currentStockRow.iloc[stockNameIndex]

            currUnitValue = GpwCurrentStockData.unitPrice(currentStockRow)

            currChangeRaw = currentStockRow.iloc[dataChangeIndex]
            currChange = 0
            if currChangeRaw != "-":
                currChange = float(currChangeRaw)

            currTransactions = transactions.currentTransactions(transMode)
            for item in currTransactions:
                trans_amount = item[0]
                trans_unit_price = item[1]
                trans_date = item[2]

                currValue = currUnitValue * trans_amount
                buyValue = trans_unit_price * trans_amount
                profit = currValue - buyValue
                profitPnt = 0
                if buyValue != 0:
                    profitPnt = profit / buyValue * 100.0

                trans_unit_price = round(trans_unit_price, 4)
                profitPnt = round(profitPnt, 2)
                profit = round(profit, 2)

                rowsList.append([
                    stockName, ticker, trans_amount, trans_unit_price,
                    currUnitValue, currChange, profitPnt, profit, trans_date
                ])

        dataFrame = DataFrame.from_records(rowsList, columns=columnsList)
        return dataFrame
Пример #8
0
    def getWalletStock(self):
        columnsList = [
            "Nazwa", "Ticker", "Liczba", "Średni kurs nabycia", "Kurs",
            "Zm.do k.odn.[%]", "Zm.do k.odn.[PLN]", "Wartość [PLN]",
            "Udział [%]", "Zysk [%]", "Zysk [PLN]", "Zysk całkowity [PLN]"
        ]

        # apply_on_column( dataFrame, 'Zm.do k.odn.(%)', convert_float )

        walletState = self.getWalletState()
        walletValue = walletState[0]

        currentStock: GpwCurrentStockData = self.gpwCurrentSource.stockData

        stockNameIndex = currentStock.getDataColumnIndex(
            StockDataType.STOCK_NAME)
        dataChangeIndex = currentStock.getDataColumnIndex(
            StockDataType.CHANGE_TO_REF)

        rowsList = []

        transMode = self.userContainer.transactionsMatchMode

        for ticker, transactions in self.wallet.stockList.items():
            amount, buy_unit_price = transactions.currentTransactionsAvg(
                transMode)
            currentStockRow = currentStock.getRowByTicker(ticker)

            if currentStockRow is None or currentStockRow.empty:
                _LOGGER.warning("could not find stock by ticker: %s", ticker)
                rowDict = {}
                rowDict[columnsList[0]] = "-"
                rowDict[columnsList[1]] = ticker
                rowDict[columnsList[2]] = amount  ## liczba
                rowDict[columnsList[3]] = "-"  ## sredni kurs nabycia
                rowDict[columnsList[4]] = buy_unit_price  ## kurs
                rowDict[columnsList[5]] = "-"
                rowDict[columnsList[6]] = "-"
                rowDict[columnsList[7]] = "-"
                rowDict[columnsList[8]] = "-"
                rowDict[columnsList[9]] = "-"
                rowDict[columnsList[10]] = "-"
                rowDict[columnsList[11]] = "-"
                rowsList.append(rowDict)
                continue

            stockName = currentStockRow.iloc[stockNameIndex]

            currUnitValue = GpwCurrentStockData.unitPrice(currentStockRow)

            currChangeRaw = currentStockRow.iloc[dataChangeIndex]
            currChangePnt = 0
            if currChangeRaw != "-":
                currChangePnt = float(currChangeRaw)

            currValue = currUnitValue * amount

            ## ( curr_unit_price - ref_unit_price ) * unit_price * amount
            valueChange = currChangePnt / 100.0 * currValue

            participation = currValue / walletValue * 100.0

            buyValue = buy_unit_price * amount
            profit = currValue - buyValue
            profitPnt = 0
            if buyValue != 0:
                profitPnt = profit / buyValue * 100.0

            totalProfit = transactions.transactionsProfit()
            totalProfit += currValue - broker_commission(currValue)

            rowDict = {}
            rowDict[columnsList[0]] = stockName
            rowDict[columnsList[1]] = ticker
            rowDict[columnsList[2]] = amount  ## liczba
            rowDict[columnsList[3]] = round(buy_unit_price,
                                            4)  ## sredni kurs nabycia
            rowDict[columnsList[4]] = round(currUnitValue, 2)  ## kurs
            rowDict[columnsList[5]] = round(currChangePnt,
                                            2)  ## zm. kur. odn %
            rowDict[columnsList[6]] = round(valueChange,
                                            2)  ## zm. kur. odn. PLN
            rowDict[columnsList[7]] = round(currValue, 2)  ## wartosc
            rowDict[columnsList[8]] = round(participation, 2)  ## udzial
            rowDict[columnsList[9]] = round(profitPnt, 2)  ## zysk %
            rowDict[columnsList[10]] = round(profit, 2)  ## zysk PLN
            rowDict[columnsList[11]] = round(totalProfit, 2)  ## zysk calk.
            rowsList.append(rowDict)

        dataFrame = DataFrame(rowsList)
        return dataFrame
Пример #9
0
 def _getSelectedTickers(self):
     dataIndex = GpwCurrentStockData.getColumnIndex(StockDataType.TICKER)
     return self.getSelectedData(dataIndex)  ## ticker
Пример #10
0
from teststockmonitor import data

## ============================= main section ===================================

if __name__ != '__main__':
    sys.exit(0)

app = QApplication(sys.argv)
app.setApplicationName("StockMonitor")
app.setOrganizationName("arnet")

# dataframe = DataFrame({'a': ['Mary', 'Jim', 'John'],
#                        'b': [100, 200, 300],
#                        'c': ['a', 'b', 'c']})

dataAccess = GpwCurrentStockData()
dataPath = data.get_data_path("akcje_2020-04-14_15-50.xls")
dataframe = dataAccess.dao.parseWorksheetFromFile(dataPath)

# csvPath = data.get_data_root_path() + "/akcje_2020-04-14_15-50.csv"
# dataframe.to_csv( csvPath, encoding='utf-8', index=False )

setup_interrupt_handling()

widget = StockFullTable()
widget.setColumnVisible(0, False)
widget.setColumnVisible(1, False)
widget.setColumnVisible(3, False)
widget.setColumnVisible(4, False)
widget.setColumnVisible(13, False)
widget.setColumnVisible(14, False)
Пример #11
0
class GpwCurrentStockDataTest(unittest.TestCase):
    def setUp(self):
        ## Called before testfunction is executed
        self.dataAccess = GpwCurrentStockData()

        def data_path():
            return get_data_path("akcje_2021-12-21_20-00.xls")

        self.dataAccess.dao.getDataPath = data_path  # type: ignore
        self.dataAccess.dao.storage = WorksheetStorageMock()
        self.dataAccess.dao.parseWorksheetFromFile(data_path())

    def tearDown(self):
        ## Called after testfunction was executed
        pass

    def test_getWorksheetData_False(self):
        currData = self.dataAccess.getWorksheetData(False)
        dataLen = len(currData)
        self.assertGreaterEqual(dataLen, 395)
        self.assertIsNotNone(currData)

#     def test_getWorksheet_micro(self):
#         startTime = datetime.datetime.now()
#         self.dataAccess.getWorksheetData( True )
#         end1Time = datetime.datetime.now()
#         self.dataAccess.loadWorksheet( False )
#         end2Time = datetime.datetime.now()
#         diff1 = end1Time - startTime
#         diff2 = end2Time - end1Time
#         print( "load time:", diff1, diff2 )

    def test_getStockData_None(self):
        currData = self.dataAccess.getStockData()
        self.assertEqual(currData, None)

    def test_getStockData(self):
        stockList = ["11B", "ALR"]
        currData = self.dataAccess.getStockData(stockList)
        dataLen = len(currData)
        self.assertEqual(dataLen, 2)

    def test_getData(self):
        currData = self.dataAccess.getData(StockDataType.TICKER)
        dataLen = len(currData)
        self.assertEqual(dataLen, 395)  ## one removed, because of summary

    def test_getRowByTicker(self):
        rowData = self.dataAccess.getRowByTicker("ZWC")
        #         print( rowData )
        nameIndex = self.dataAccess.getDataColumnIndex(
            StockDataType.STOCK_NAME)
        tickerIndex = self.dataAccess.getDataColumnIndex(StockDataType.TICKER)
        isinIndex = self.dataAccess.getDataColumnIndex(StockDataType.ISIN)

        self.assertEqual(rowData[nameIndex], "ZYWIEC")
        self.assertEqual(rowData[tickerIndex], "ZWC")
        self.assertEqual(rowData[isinIndex], "PLZYWIC00016")

    def test_getTickerField(self):
        rowData = self.dataAccess.getTickerField(4)
        self.assertEqual(rowData, "ABE")

    def test_getTickerFromIsin(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getTickerFromIsin("PLZYWIC00016")
        self.assertEqual(rowData, "ZWC")

    def test_getTickerFromIsin_Invalid(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getTickerFromIsin("XXX")
        self.assertEqual(rowData, None)

    def test_getTickerFromName(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getTickerFromName("ZYWIEC")
        self.assertEqual(rowData, "ZWC")

    def test_getStockIsinFromTicker(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getStockIsinFromTicker("ZWC")
        self.assertEqual(rowData, "PLZYWIC00016")

    def test_getNameFromTicker(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getNameFromTicker("ZWC")
        self.assertEqual(rowData, "ZYWIEC")

    def test_getNameFromIsin(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getNameFromIsin("PLZYWIC00016")
        self.assertEqual(rowData, "ZYWIEC")

    def test_getTickerFieldByName(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getTickerFieldByName("ZYWIEC")
        self.assertEqual(rowData, "ZWC")

    def test_getRecentValueByTicker(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getRecentValueByTicker("11B")
        self.assertEqual(rowData, 541.0)

    def test_getRecentChangeByTicker(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getRecentChangeByTicker("11B")
        self.assertEqual(rowData, 0.37)

    def test_getReferenceValueByTicker(self):
        #         print( self.dataAccess.getWorksheetData() )
        rowData = self.dataAccess.getReferenceValueByTicker("11B")
        self.assertEqual(rowData, 539.0)