Example #1
0
    def loadTradesFromDB(self, theDate=None):
        '''
        User tweak-- if DAS or IB import files are checked when the load button is clicked,
        Change the selected radio to useDatabase and return. Update will show if there are
        any DB trades to load.
        '''
        if self.sc.ui.dasImport.isChecked() or self.sc.ui.ibImport.isChecked():
            self.sc.ui.useDatabase.setChecked(True)
            self.sc.dbDefault(True)
            return 1

        ibdb = StatementDB()
        df = ibdb.getStatement(theDate)
        tu = DefineTrades('DB')
        self.df, ldf = tu.processDBTrades(df)

        ts, self.entries = ibdb.getTradeSummariesSA(theDate)
        if not ts:
            logging.info(
                f"No user data has been saved for {theDate.strftime('%A %B %d')}."
            )
            return None
        self.ts = setTradeSummaryHeaders(ts)

        logging.info('load up the trade names now')
        tradeSummaries = []
        self.sc.ui.tradeList.clear()
        for key in self.ts:
            self.sc.ui.tradeList.addItem(key)
            tradeSummaries.append(self.ts[key])

        # Load dailyote
        dailyNoteModel = DailyNotesCrud(theDate)
        note = dailyNoteModel.getNote()
        self.dailyNoteModel = dailyNoteModel
        if not note:
            note = ""
        self.sc.ui.dailyNote.setText(note)

        inf = self.sc.ui.infileEdit.text()
        windowTitle = f"{self.sc.baseWindowTitle}: {inf}: User Data Loaded"
        self.sc.setWindowTitle(windowTitle)

        # In prep to do the mistake summary and excel export, return the list it uses now
        # It might be good to use the dict self.ts instead
        return tradeSummaries
Example #2
0
def registerTrades(wb, theDate):

    ibdb = StatementDB()
    df = ibdb.getStatement(theDate)
    x = ibdb.getNumTicketsForDaySA(theDate)
    if not x[0] or not x[1]:
        msg = f'''found {x[0]} tickets and {x[1]} trades. Nothing to process for the date {theDate.strftime('%A %d, %Y')}in the DB'''
        return msg
    tu = DefineTrades('DB')
    df, ldf = tu.processDBTrades(df)

    ts, entries = ibdb.getTradeSummariesSA(theDate)
    # self.ts = setTradeSummaryHeaders(ts)

    drc = DisReqCol(theDate)

    tlog = wb["Trade Log"]
    account = tlog['I1'].value

    startSearch = False
    ix = -2
    cols = drc.tfcolumns
    # Here is a list of the keys to use cols.keys() of the trade log DataFrame
    # ['date', 'time', 'side', 'symb', 'entry1', 'acctbal', 'shares',
    # 'stoploss', 'targ', 'avgexit', 'pl', 'notes'])
    # Not bothering with the abstraction (drc.name) because this is entirely ours.

    srf = SumReqFields()

    ids = list()

    for row in tlog.iter_rows():
        # Unconventional loop stuff
        anchor = (1, row[0].row)
        keys = list(ts.keys())
        if startSearch is True:
            idcol = cols['id'][0][0] - 1
            if row[idcol].value:
                ids.append(row[idcol].value)
            if not row[0].value:
                startSearch = False
                ix = 0

        if row[0].value == 'Date':
            startSearch = True

        if ix >= 0 and ix < len(keys):

            while True and ix < len(keys):
                key = keys[ix]
                tdf = ts[key]
                if not gotAnyExits(tdf) or tdf['id'].unique()[0] in ids or (
                        tdf['Account'].unique()[0] != account):
                    if tdf['Account'].unique()[0] not in ['SIM', 'Live']:
                        raise ValueError(
                            'Programmer exception in search of weird data')
                    # Continue the inner loop -- keep row from the outer loop loop
                    ix += 1
                    continue

                # date
                cell = tcell(cols['date'][0], anchor=anchor)
                tlog[cell] = theDate

                # time
                cell = tcell(cols['time'][0], anchor=anchor)
                tim = tdf[srf.start].unique()[0]
                tlog[cell] = tim

                # side
                name = tdf[srf.name].unique()[0]
                if name:
                    cell = tcell(cols['side'][0], anchor=anchor)
                    tlog[cell] = name.split()[1]

                # symb
                cell = tcell(cols['symb'][0], anchor=anchor)
                tlog[cell] = name.split()[0]

                # entry1
                cell = tcell(cols['entry1'][0], anchor=anchor)
                tlog[cell] = tdf[srf.entry1].unique()[0]

                # Account Balance (setting an excel formula)
                cell = tcell(cols['acctbal'][0], anchor=anchor)
                formula = "=$M$3+SUM($N$7:$N{})".format(row[0].row - 1)
                tlog[cell] = formula

                # "shares"
                cell = tcell(cols['shares'][0], anchor=anchor)
                shares = tdf[srf.shares].unique()[0].split()[0]
                if len(shares) > 0:
                    try:
                        ishares = int(shares)
                    except ValueError:
                        ishares = 0
                tlog[cell] = ishares

                # stoploss
                cell = tcell(cols['stoploss'][0], anchor=anchor)
                sl = tdf[srf.stoploss].unique()[0]
                if isinstance(sl, bytes):
                    sl = None
                tlog[cell] = sl

                # target
                cell = tcell(cols['targ'][0], anchor=anchor)
                target = tdf[srf.targ].unique()[0]
                if isinstance(target, bytes):
                    target = None
                tlog[cell] = target

                # avgExit
                cell = tcell(cols['avgexit'][0], anchor=anchor)
                tlog[cell] = getAvgExit(tdf)

                # P/L
                cell = tcell(cols['pl'][0], anchor=anchor)
                pl = tdf[srf.pl].unique()[0]

                # Don't know how these are sneaking through-- Is it only on legacy files?
                if isinstance(pl, bytes):
                    pl = 0.0
                tlog[cell] = pl

                # Strategy
                cell = tcell(cols['strat'][0], anchor=anchor)
                strat = tdf[srf.strat].unique()[0]
                tlog[cell] = strat

                # notes (from the mistake note field)
                cell = tcell(cols['notes'][0], anchor=anchor)
                note = tdf[srf.mstknote].unique()[0]
                tlog[cell] = note

                # id (from the database)
                cell = tcell(cols['id'][0], anchor=anchor)
                id = tdf['id'].unique()[0]
                tlog[cell] = id

                # break the inner loop
                break

            ix += 1
            if ix >= len(keys):
                # done with outer loop
                break
    return None