Ejemplo n.º 1
0
    def getChartUserData(self):
        self.query = TradeSum.getDistinctStratsQuery()
        self.runFilters()

        strats = self.stratquery.all() if self.stratquery else self.query.all()
        total = sum([x[1] for x in strats if x[0] != ''])
        # threshhold is a percentage of the total. 1% in this case
        threshold = total * .03

        self.labels = [
            x[0] if x[1] > threshold else '' for x in strats
            if x[0] is not None
        ]
        self.legendLabels = [x[0] for x in strats if x[0] is not None]
        self.data = [x[1] for x in strats if x[0] is not None]
        # self.legendData = ['{:0.2f}%'.format(x * 100 / sum(self.data)) for x in self.data]
        self.legendData = [
            str(x) + ' trade' + ('s' if x > 1 else '') for x in self.data
        ]
        self.title = "Strategies used"

        # If the strategies2 key is populated then 'no strategies' is excluded
        if 'strategies2' in self.cud and self.cud['strategies2']:
            self.title += " (excluding no strategy)"
        len(self.labels), len(self.data), len(self.legendLabels), len(
            self.legendData)
    def getChartUserData(self):
        '''
        Getting an array of queries will allow the devel of digging down into each candle
        '''
        stratQueries = TradeSum.getDistinctStratAvgPnlQuery()
        self.alldata = []
        self.labels = []
        count = 0
        for i, (strat, squery) in enumerate(stratQueries):

            stratQueries[i][1] = self.runFiltersOnQuery(squery).all()

            if len(stratQueries[i][1]) == 0: continue

            self.alldata.append([stratQueries[i][0]])
            self.alldata[count].append(
                sum([
                    x.pnl if isinstance(x.pnl, (float, int)) else 0
                    for x in stratQueries[i][1]
                ]) / len(stratQueries[i][1]))
            count += 1

        self.alldata.sort(reverse=True, key=lambda x: x[1])
        # self.query = self.query.all()

        self.labels = [x[0] for x in self.alldata]
        self.data = [x[1] for x in self.alldata]
        self.title = f'Average PnL per Strategy in {self.cud["accounts"]} accounts'
        self.getFormatGraphArray()
Ejemplo n.º 3
0
 def getChartUserData(self):
     self.labels, self.data = TradeSum.getNamesAndProfits(
         self.date.strftime("%Y%m%d"))
     self.labels = self.labels[self.account]
     self.data = self.data[self.account]
     self.getFormatGraphArray()
     self.title = f'Profits in {self.account} account on {self.date.strftime("%B %d, %Y")}'
Ejemplo n.º 4
0
    def lookForPnlError(self, d, s, daSum):
        '''
        An isolated use of SA for the first time in this module. Look for existing db trades that
        have a bad pnl and update it, but only if the difference is more than 1 cent. This
        should apply mostly to blob entries for the pnl in the sqlite db.
        :params d: The Date parameter from the tradeobject. A datetime string
        :parmas s: The Start parameter from the tradeobject. A time string
        :parmas daSum: The sum value that structjour just calculated

        Programmers note: if this causes any exceptions and the answer is not fixable, wrap it with
        try and pass.
        '''
        if not daSum:
            return
        q = TradeSum.getTradeSumQuery()
        d = pd.Timestamp(d).strftime("%Y%m%d")
        s = pd.Timestamp(s).strftime("%H:%M:%S")
        q = q.filter_by(date=d).filter_by(start=s)
        x = q.all()
        if x:
            if not isinstance(x[0].pnl, (int, float)) or not math.isclose(
                    daSum, x[0].pnl, abs_tol=0.011):
                x[0].pnl = daSum
                ModelBase.session.commit()
                logging.info(
                    f'Structjour updated the pnl for {x[0].name} on {d} {s}')
Ejemplo n.º 5
0
 def getNamesNProfits(self, ts=None):
     '''
     Get Names and profits for use in daily profit chart
     '''
     if not self.date:
         return {}, {}
     return TradeSum.getNamesAndProfits(self.date.strftime(self.date.strftime("%Y%m%d")))
Ejemplo n.º 6
0
def notmain():
    '''Run some local code'''
    q = TradeSum.getById(1786)
    print(q.shares)

    dbdr = DbDoctorCrud()
    qq = dbdr.getTradeSumById(1786)
Ejemplo n.º 7
0
 def populateAccounts(self):
     accounts = TradeSum.getAccounts()
     self.ui.selectAccount.clear()
     self.ui.selectAccount.addItem('All Accounts')
     for account in accounts:
         self.ui.selectAccount.addItem(account)
     if 'SIM' in accounts:
         self.ui.selectAccount.setCurrentText('SIM')
Ejemplo n.º 8
0
    def filterHubStrategy(self):
        '''
        HACK ALERT:The access to the chartData methods uses an arbitrary reference 
        to charts[0]. 
        Filter the strategies and numbers listed in the UI according to the current
        state of self.cud. This will be called when the user changes dates, account
        side, or symbol. The call should be before the very similar runfilters methods
        and needs to be independent of them
        '''
        q = TradeSum.getDistinctStratsQuery()

        q = self.charts[0].chartData.filter_by_dates(q)
        q = self.charts[0].chartData.filter_by_accounts(q)
        q = self.charts[0].chartData.filter_by_side(q)
        q = self.charts[0].chartData.filter_by_symbols(q)
        self.populateStrategies(strats=q.all())
Ejemplo n.º 9
0
 def getTradeSumById(self, tid):
     q = TradeSum.getById(tid)
     if not q:
         return q
     # TODO
     # Unfortunately, formatting to match the old interface. Definitely fix later
     t = dict()
     t['id'] = q.id
     t['name'] = q.name
     t['strat'] = q.strategy
     t['accnt'] = q.account
     t['pl'] = q.pnl
     t['start'] = q.start
     t['date'] = q.date
     t['dur'] = q.duration
     t['qty'] = q.shares
     return t
Ejemplo n.º 10
0
    def findTradeSummary(self, date, start):
        '''
        A helper method for addTradeSummariesSA and updateTradeSummaries
        Get a single trade summary record by date and time
        :date: A Date string or Timestamp for the date to find.
        :start: A Time string or Timestamp for the time to find
        :return: The found record as a tuple or False
        '''

        x = TradeSum.findByTime(formatDate(date), formatTime(start))
        if x:
            if len(x) > 1:
                logging.error(
                    f'multiple trade summaries found with date:{date}, start: {start}'
                )
            return x[0]

        return False
Ejemplo n.º 11
0
    def populateStrategies(self, strats=None):
        '''
        Populate the listwidget from every strategy that has been named in a trade or in the 
        argument strats. If strats is None, this will include every strategy that has been named
        by the user in a trade (for this database table).
        Reiterate, unnecessarily, that the TradeSum.strategy is a string and has no relationship
        with the strategy tables
        :params strats: A List  of lists [[strat, numstrats], ...]
        '''
        if strats is None:
            strats = TradeSum.getDistinctStrats()

        self.ui.strategyListWidget.clear()
        for strat in strats:
            if strat[0] == '':
                self.ui.strategyListWidget.addItem(f'No Strategy ({strat[1]})')
            else:
                self.ui.strategyListWidget.addItem(f'{strat[0]} ({strat[1]})')
Ejemplo n.º 12
0
    def plot(self):
        names, profits = TradeSum.getNamesAndProfits(self.daDate)

        neg, pos = self.getFormatGraphArray(profits[self.account])
        x = range(len(neg))
        d = pd.Timestamp(self.daDate)
        title = f'Profits in {self.account} account on {d.strftime("%B %d, %Y")}'

        ax = self.figure.add_subplot(111)
        ax.clear()
        ax.bar(x, neg, width=0.9, color='crimson')
        ax.bar(x, pos, width=0.9, color='limegreen')
        ax.set_xticks(x)
        ax.set_xticklabels(names[self.account])
        for label in ax.get_xticklabels():
            label.set_rotation(-45)
            label.set_fontsize(8)
        self.figure.subplots_adjust(bottom=.2)
        ax.set_title(title)
        self.draw()
Ejemplo n.º 13
0
    def insertTradeSummary(self, trade):
        '''
        Create a new record from the trade object
        :params trade: DataFrame that uses the column names defined in SumReqFields
        '''
        sf = self.sf
        rc = self.rc
        # tcols = sf.tcols
        newts = dict()
        ModelBase.session.rollback()
        close_all_sessions()
        ModelBase.connect(new_session=True)
        session = ModelBase.session
        tradesum = TradeSum()

        tradesum.name = trade[sf.name].unique()[0]
        tradesum.strategy = trade[sf.strat].unique()[0]
        tradesum.link1 = trade[sf.link1].unique()[0]
        tradesum.account = trade[sf.acct].unique()[0]
        tradesum.pnl = trade[sf.pl].unique()[0]
        tradesum.start = formatTime(trade[sf.start].unique()[0])
        tradesum.date = formatDate(trade[sf.date].unique()[0])
        tradesum.duration = trade[sf.dur].unique()[0]
        tradesum.shares = trade[sf.shares].unique()[0]
        tradesum.mktval = getFloat(trade[sf.mktval].unique()[0])
        tradesum.target = getFloat(trade[sf.targ].unique()[0])
        tradesum.targdiff = getFloat(trade[sf.targdiff].unique()[0])
        tradesum.stoploss = getFloat(trade[sf.stoploss].unique()[0])
        tradesum.sldiff = getFloat(trade[sf.sldiff].unique()[0])
        tradesum.rr = trade[sf.rr].unique()[0]
        tradesum.realrr = trade[sf.realrr].unique()[0]
        tradesum.maxloss = getFloat(trade[sf.maxloss].unique()[0])
        tradesum.mstkval = getFloat(trade[sf.mstkval].unique()[0])
        tradesum.mstknote = trade[sf.mstknote].unique()[0]
        tradesum.explain = trade[sf.explain].unique()[0]
        tradesum.notes = trade[sf.notes].unique()[0]
        tradesum.clean = ''
        session.add(tradesum)
        session.commit()
        # session.close()
        return tradesum
Ejemplo n.º 14
0
 def getTradeSumById(self, tsid):
     return TradeSum.getById(tsid)
Ejemplo n.º 15
0
 def deleteTradeSumById(self, tid):
     return TradeSum.deleteById(tid)
Ejemplo n.º 16
0
 def updateMstkVals(self, tsid, val, note):
     TradeSum.updateMstkVals(tsid, val, note)
Ejemplo n.º 17
0
 def getEntryTrades(self, tsid):
     return TradeSum.getEntryTrades(tsid)
Ejemplo n.º 18
0
 def getNumTicketsForDay(self, day, account='all'):
     '''Get the counts of both Trade and TradeSum transactactions for given day'''
     tcount = Trade.getNumTicketsForDay(day, account)
     tscount = TradeSum.getNumTradesForDay(day, account)
     return tcount, tscount
Ejemplo n.º 19
0
 def getNamesNProfits(self, date):
     '''
     Just temp
     '''
     return TradeSum.getNamesAndProfits(date.strftime("%Y%m%d"))
Ejemplo n.º 20
0
 def getTradeSumByDate(self, daDate):
     sf = self.sf
     tsums = TradeSum.findByTime(formatDate(daDate))
     if not tsums:
         return None
     return tsums