Exemplo n.º 1
0
	def newPeriod(self):
		period = self.periods[self.period.currentIndex()]
		appGlobal.getApp().portfolio.portPrefs.setPositionPeriod(period)

		period = self.periods[self.period.currentIndex()]
		if period == "One Week":
			self.model.days = 7
		elif period == "One Month":
			self.model.days = 30
		elif period == "Three Months":
			self.model.days = 91
		elif period == "One Year":
			self.model.days = 365
		elif period == "Two Years":
			self.model.days = 365 * 2
		elif period == "Three Years":
			self.model.days = 365 * 3
		elif period == "Five Years":
			self.model.days = 365 * 5 + 1
		elif period == "Ten Years":
			self.model.days = 365 * 10 + 2
		else:
			self.model.days = 365 * 100 # 100 years

		self.model.rebuildSpending()
		self.table.resizeColumnsToContents()
Exemplo n.º 2
0
	def insert(self):
		data =  {
			"ticker": self.ticker,
			"date": self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
			"value": str(self.value)
		}
		
		appGlobal.getApp().stockData.db.insertOrUpdate("stockDividends", data)
Exemplo n.º 3
0
    def insert(self):
        data = {
            "ticker": self.ticker,
            "date": self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
            "value": str(self.value)
        }

        appGlobal.getApp().stockData.db.insertOrUpdate("stockDividends", data)
Exemplo n.º 4
0
 def selectedRow(self, deselected, selected):
     # Update tool action to allow editing/deleting transactions
     if len(self.table.selectionModel().selectedRows()) > 0 and (
         appGlobal.getApp().portfolio.isBrokerage() or appGlobal.getApp().portfolio.isBank()
     ):
         self.deleteTransactionButton.setDisabled(False)
         self.editTransactionButton.setDisabled(False)
     else:
         self.deleteTransactionButton.setDisabled(True)
         self.editTransactionButton.setDisabled(True)
Exemplo n.º 5
0
 def selectedRow(self, deselected, selected):
     # Update tool action to allow editing/deleting transactions
     if len(self.table.selectionModel().selectedRows()) > 0 and (
             appGlobal.getApp().portfolio.isBrokerage()
             or appGlobal.getApp().portfolio.isBank()):
         self.deleteTransactionButton.setDisabled(False)
         self.editTransactionButton.setDisabled(False)
     else:
         self.deleteTransactionButton.setDisabled(True)
         self.editTransactionButton.setDisabled(True)
Exemplo n.º 6
0
    def data(self, index, role):
        row = index.row()
        column = index.column()
        if self.rowHeader:
            column += 1

        if not index.isValid():
            return QVariant()
        elif role == Qt.BackgroundRole:
            if row % 2 == 1:
                return QVariant(appGlobal.getApp().alternateRowColor)
        elif role == Qt.ForegroundRole:
            # Return red/green if it is a red/green column
            if column in self.redGreenCols or row in self.redGreenRows:
                d = self.myData[row]
                if column < len(d):
                    val = d[column]
                    if val:
                        # Try converting to float and return positive/negative
                        try:
                            val = val.replace('$',
                                              '').replace('%',
                                                          '').replace(',', '')
                            val = float(val)
                            if val >= 0:
                                return QVariant(
                                    appGlobal.getApp().positiveColor)
                            else:
                                return QVariant(
                                    appGlobal.getApp().negativeColor)
                        except:
                            return QVariant()
        elif role == Qt.TextAlignmentRole:
            if column == 0:
                return QVariant(Qt.AlignLeft | Qt.AlignVCenter)
            else:
                return QVariant(Qt.AlignRight | Qt.AlignVCenter)
        elif role != Qt.DisplayRole:
            return QVariant()
        if row < len(self.myData):
            # Return nothing if it is an editor
            if column in self.myTable.editColumns and row in self.myTable.editColumns[
                    column]:
                return QVariant()

            d = self.myData[row]
            if column < len(d):
                # Return string depending on column
                val = d[column]
                if isinstance(val, datetime.datetime):
                    return QVariant(val.strftime("%m/%d/%Y"))
                else:
                    return QVariant(val)
        return QVariant()
Exemplo n.º 7
0
	def rebuildPerformance(self):
		stockData = appGlobal.getApp().stockData
		portfolio = appGlobal.getApp().portfolio

		table = portfolio.getPerformanceTable(self.current, self.dividend, self.type)
		self.setColumns(table[0])
		self.setData(table[1])
		for col in range(len(table[0])):
			if col == 0:
				continue
			self.setRedGreenColumn(col)
Exemplo n.º 8
0
	def rebuildPerformance(self):
		stockData = appGlobal.getApp().stockData
		portfolio = appGlobal.getApp().portfolio

		table = portfolio.getPerformanceTable(self.current, self.dividend, self.type)
		self.setColumns(table[0])
		self.setData(table[1])
		for col in range(len(table[0])):
			if col == 0:
				continue
			self.setRedGreenColumn(col)
Exemplo n.º 9
0
	def __init__(self, parent = None, *args): 
		EditGridModel.__init__(self, parent, *args)
		self.app = appGlobal.getApp()
		
		self.ticker = appGlobal.getApp().portfolio.getLastTicker()
		if appGlobal.getApp().portfolio.isBrokerage():
			self.setColumns(["Symbol", "Target %", "Current %", "Current $", "Difference %", "Difference $", "Shares"])
		else:
			self.setColumns(["Symbol", "Target %", "Current %", "Current $", "Difference %", "Difference $"])
		self.setRedGreenColumn(4)
		self.setRedGreenColumn(5)
		self.setAllocation()
Exemplo n.º 10
0
	def appYield(self):
		self.repaint()

		# Choose how long to sleep based on last yield time
		# Yield up to 100ms at most once every half second
		now = datetime.datetime.now()
		if now - self.lastWaitYield > datetime.timedelta(milliseconds = 500):
			self.lastWaitYield = now
			waitMs = 100
		else:
			waitMs = 1
		appGlobal.getApp().processEvents(QEventLoop.AllEvents, waitMs)
Exemplo n.º 11
0
	def appYield(self):
		self.repaint()

		# Choose how long to sleep based on last yield time
		# Yield up to 100ms at most once every half second
		now = datetime.datetime.now()
		if now - self.lastWaitYield > datetime.timedelta(milliseconds = 500):
			self.lastWaitYield = now
			waitMs = 100
		else:
			waitMs = 1
		appGlobal.getApp().processEvents(QEventLoop.AllEvents, waitMs)
Exemplo n.º 12
0
    def onOk(self):
        app = appGlobal.getApp()
        self.setCursor(Qt.WaitCursor)
        app.processEvents()

        newName = str(self.name.text())
        if re.search("[/\\.]", newName):
            QMessageBox(
                QMessageBox.Critical, 'Invalid Name',
                'Please do not use any of the following characters: / or \ or .'
            ).exec_()
            return

        prefs = appGlobal.getApp().prefs

        # Check for unique name
        portfolios = prefs.getPortfolios()
        for name in portfolios:
            if name.upper() == newName.upper():
                QMessageBox(
                    QMessageBox.Critical, 'Duplicate Name',
                    'A portfolio with that name already exists.  Please choose a new name.'
                ).exec_()
                return

        self.added = True

        # Create portfolio, go to settings, and select it
        prefs.addPortfolio(newName)
        prefs.setLastTab("Settings")
        prefs.setLastPortfolio(newName)
        app.main.ts.selectTool("Settings")
        app.loadPortfolio(newName)

        if self.benchmark.isChecked():
            app.portfolio.makeBenchmark()
            app.loadPortfolio(newName)
        elif self.combined.isChecked():
            app.portfolio.makeCombined()
            app.loadPortfolio(newName)
        elif self.bank.isChecked():
            app.portfolio.makeBank()
            app.loadPortfolio(newName)

        if self.benchmark.isChecked():
            app.portfolioMenuNames[newName] = "benchmark"
        else:
            app.portfolioMenuNames[newName] = "other"
        app.rebuildPortfoliosMenu()

        self.setCursor(Qt.ArrowCursor)
        self.close()
Exemplo n.º 13
0
    def newTicker(self, index):
        if index >= len(self.tickers):
            return

        ticker = self.tickers[index]
        if ticker == "All Symbols":
            self.model.ticker = False
        elif ticker == "Cash Balance":
            self.model.ticker = "__CASH__"
        else:
            self.model.ticker = ticker
        appGlobal.getApp().portfolio.setLastTicker(self.model.ticker)
        self.model.setTransactions()
Exemplo n.º 14
0
    def newTicker(self, index):
        if index >= len(self.tickers):
            return

        ticker = self.tickers[index]
        if ticker == "All Symbols":
            self.model.ticker = False
        elif ticker == "Cash Balance":
            self.model.ticker = "__CASH__"
        else:
            self.model.ticker = ticker
        appGlobal.getApp().portfolio.setLastTicker(self.model.ticker)
        self.model.setTransactions()
Exemplo n.º 15
0
	def __init__(self, parent = None, *args): 
		EditGridModel.__init__(self, parent, *args)
		
		self.showDeleted = False
		self.ticker = appGlobal.getApp().portfolio.getLastTicker()
		if self.ticker == "False" or self.ticker == "__COMBINED__":
			self.ticker = False

		self.setTransactions()
	
		columns = ["Date", "Position", "Transaction", "Shares", "$/Share", "Fee", "Total"]
		if appGlobal.getApp().prefs.getShowCashInTransactions():
			columns.append("Cash Balance")
		self.setColumns(columns)
Exemplo n.º 16
0
	def data(self, index, role):
		row = index.row()
		column = index.column()
		if self.rowHeader:
			column += 1
		
		if not index.isValid():
			return QVariant() 
		elif role == Qt.BackgroundRole:
			if row % 2 == 1:
				return QVariant(appGlobal.getApp().alternateRowColor)
		elif role == Qt.ForegroundRole:
			# Return red/green if it is a red/green column
			if column in self.redGreenCols or row in self.redGreenRows:
				d = self.myData[row]
				if column < len(d):
					val = d[column]
					if val:
						# Try converting to float and return positive/negative
						try:
							val = val.replace('$', '').replace('%', '').replace(',', '')
							val = float(val)
							if val >= 0:
								return QVariant(appGlobal.getApp().positiveColor)
							else:
								return QVariant(appGlobal.getApp().negativeColor)
						except:
							return QVariant()
		elif role == Qt.TextAlignmentRole: 
			if column == 0:
				return QVariant(Qt.AlignLeft | Qt.AlignVCenter)
			else:
				return QVariant(Qt.AlignRight | Qt.AlignVCenter)
		elif role != Qt.DisplayRole: 
			return QVariant()
		if row < len(self.myData):
			# Return nothing if it is an editor
			if column in self.myTable.editColumns and row in self.myTable.editColumns[column]:
				return QVariant()

			d = self.myData[row]
			if column < len(d):
				# Return string depending on column
				val = d[column]
				if isinstance(val, datetime.datetime):
					return QVariant(val.strftime("%m/%d/%Y"))
				else:
					return QVariant(val)
		return QVariant()
Exemplo n.º 17
0
    def checkErrors(parent=None):
        portfolio = appGlobal.getApp().portfolio

        errors = portfolio.errorCheckTransactions(appGlobal.getApp().stockData)
        if not errors:
            return

        i = 1
        for e in errors:
            fix = FixTransactionError(e, parent, i, len(errors))
            i += 1
            fix.exec_()

            if fix.stop:
                break
Exemplo n.º 18
0
    def checkErrors(parent=None):
        portfolio = appGlobal.getApp().portfolio

        errors = portfolio.errorCheckTransactions(appGlobal.getApp().stockData)
        if not errors:
            return

        i = 1
        for e in errors:
            fix = FixTransactionError(e, parent, i, len(errors))
            i += 1
            fix.exec_()

            if fix.stop:
                break
Exemplo n.º 19
0
    def getFromServer(self, request, status=False):
        '''Return True if new stock data is received'''

        if appGlobal.getFailConnected():
            return False

        # Encode as string
        icarraTickers = {}
        for (ticker, date) in request.items():
            icarraTicker = self.getIcarraTicker(ticker)
            icarraTickers[icarraTicker] = ticker

            # Change request to icarraTicker if necessary
            if icarraTicker != ticker:
                request[icarraTicker] = date.strftime("%Y-%m-%d %H:%M:%S")
                del request[ticker]
            else:
                request[ticker] = date.strftime("%Y-%m-%d %H:%M:%S")
        request["__UNIQUEID__"] = str(appGlobal.getApp().getUniqueId())

        try:
            if status:
                status.setStatus("Receiving Stock Data", 70)
            data = self.s.getStockZip(request)
        except Exception, inst:
            appGlobal.setFailConnected(True)
            return False
Exemplo n.º 20
0
	def query(securityId, timestamp = False, option = False):
		if timestamp:
			prices = appGlobal.getApp().stockData.getPrices(securityId, startDate = timestamp, endDate = timestamp)
		else:
			prices = appGlobal.getApp().stockData.getPrices(securityId)
			
		if not prices:
			return False
		else:
			if timestamp:
				row = prices[0]
				row["securityId"] = securityId
				return IcarraPriceRecord(row = row)
			else:
				print "not implemented"
				sys.exit()
Exemplo n.º 21
0
def check(value):
    app = appGlobal.getApp()

    # Check then show
    if not (app.prefs.getTutorial() & value):
        tut = Tutorial(tutorial=value)
        app.prefs.setTutorialBit(value)
Exemplo n.º 22
0
	def __init__(self, parent):
		QDialog.__init__(self)
		self.setWindowTitle("Icarra Preferences")
		self.app = appGlobal.getApp()
		
		grid = QGridLayout(self)
		
		self.backgroundRebuild = QCheckBox("Rebuild portfolios in background")
		if self.app.prefs.getBackgroundRebuild():
			self.backgroundRebuild.setChecked(True)
		grid.addWidget(self.backgroundRebuild, 0, 0, 1, 1)

		self.backgroundImport = QCheckBox("Import transactions in background")
		if self.app.prefs.getBackgroundImport():
			self.backgroundImport.setChecked(True)
		grid.addWidget(self.backgroundImport, 1, 0, 1, 1)

		self.showCash = QCheckBox("Show cash total in Transactions")
		if self.app.prefs.getShowCashInTransactions():
			self.showCash.setChecked(True)
		grid.addWidget(self.showCash, 2, 0, 1, 1)

		self.ofxDebug = QCheckBox("Enable OFX Debugging")
		if self.app.prefs.getOfxDebug():
			self.ofxDebug.setChecked(True)
		grid.addWidget(self.ofxDebug, 3, 0, 1, 1)
		
  		buttons = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
  		grid.addWidget(buttons, 4, 0, 2, 1)
  		self.connect(buttons.button(QDialogButtonBox.Cancel), SIGNAL("clicked()"), SLOT("reject()"))
  		self.connect(buttons.button(QDialogButtonBox.Ok), SIGNAL("clicked()"), self.onOk)

		self.exec_()
Exemplo n.º 23
0
	def query(securityId, ticker, timestamp = False, value = False):
		if timestamp:
			dividend = appGlobal.getApp().stockData.getDividend(ticker, timestamp)
		else:
			dividend = appGlobal.getApp().stockData.getDividends(securityId)[0]
		
		if not dividend:
			return False
		else:
			if timestamp:
				dividend["securityId"] = securityId
				dividend["ticker"] = ticker
				return IcarraDividendRecord(row = dividend)
			else:
				print "not implemented"
				sys.exit()
Exemplo n.º 24
0
    def editTransaction(self):
        # Get transaction id
        row = self.table.selectedRow()
        if row == -1:
            return
        id = self.model.transactionIds[row]

        # Loop over transactions, edit id, reselect row and finish
        for t in appGlobal.getApp().portfolio.getTransactions():
            if t.uniqueId == id:
                if t.auto:
                    QMessageBox(
                        QMessageBox.Warning,
                        "Cannot Edit",
                        "This tranaction was added by Icarra automatically to balance your portfolio.  It may not be edited.",
                    ).exec_()
                    return

                NewTransaction(self, t).exec_()

                # Find the row for our transaction id, it may have changed
                i = 0
                for thisId in self.model.transactionIds:
                    if thisId == id:
                        self.table.selectRow(i)
                        break
                    i += 1
                break
Exemplo n.º 25
0
	def setTransactions(self):
		app = appGlobal.getApp()
		app.portfolio.readFromDb()
		trans = app.portfolio.getTransactions(deletedOnly = self.showDeleted)
		self.transactions = []
		self.transactionIds = []
		
		# Build cash position if set
		showCash = app.prefs.getShowCashInTransactions()
		if showCash:
			trans.reverse()
			cash = 0
			for t in trans:
				cash += t.getCashMod()
				t.computedCashValue = cash
			trans.reverse()

		for t in trans:
			if not self.ticker or t.ticker == self.ticker or t.ticker2 == self.ticker:
				self.transactionIds.append(t.uniqueId)

				row = [t.getDate(), t.formatTicker(), t.formatType()]
				if t.type in [Transaction.deposit, Transaction.withdrawal, Transaction.dividend, Transaction.adjustment, Transaction.expense, Transaction.split]:
					row.append("")
				else:
					row.append(t.formatShares())
				row.append(t.formatPricePerShare())
				row.append(t.formatFee())
				row.append(t.formatTotal())
				if showCash:
					row.append(Transaction.formatDollar(t.computedCashValue))

				self.transactions.append(row)

		self.setData(self.transactions)
Exemplo n.º 26
0
	def setFinished(self):
		if self.finished:
			return
		self.finished = True
		
		self.progress.setValue(100)

		app = appGlobal.getApp()
		if app:
			app.statusUpdate = False
		
		if self.closeOnFinish:
			# If closing on finish, no longer modal, then close and return
			self.appYield()
			time.sleep(1)
			if self.modal:
				self.setModal(False)
			self.close()
			return
		
		self.ok.setEnabled(True)
		if self.cancelable:
			self.cancel.setEnabled(False)
		if self.modal:
			self.exec_()
Exemplo n.º 27
0
	def __init__(self, parent):
		QWidget.__init__(self, parent)
		self.model = AllocationModel()
		self.app = appGlobal.getApp()
		
		vbox = QVBoxLayout(self)
		vbox.setMargin(0)
		vbox.setAlignment(Qt.AlignTop)
		
		horiz = QHBoxLayout()
		vbox.addLayout(horiz)
		
		self.add = QPushButton("Add Symbol")
		horiz.addWidget(self.add)
		self.connect(self.add, SIGNAL("clicked()"), self.addPosition)
		
		self.delete = QPushButton("Delete Symbol")
		self.delete.setEnabled(False)
		horiz.addWidget(self.delete)
		self.connect(self.delete, SIGNAL("clicked()"), self.deletePosition)
		
		horiz.addStretch(1000)
		
		self.table = EditGrid(self.model)
		# Set edit columns for allocation for all but last row
		for i in range(self.model.rowCount() - 1):
			self.table.setEdit(i, 1)
			editor = self.table.getEdit(i, 1)
			editor.setValidator(QDoubleValidator(0, 1e9, 12, editor))

		self.table.resizeRowsToContents()
		vbox.addWidget(self.table)
		
		self.connect(self.table.selectionModel(), SIGNAL("selectionChanged(QItemSelection, QItemSelection)"), self.selectedRow)
Exemplo n.º 28
0
	def __init__(self, parent = None):
		QDialog.__init__(self, parent)
		self.app = appGlobal.getApp()
		self.added = False
		self.setWindowTitle("Add To Allocation")
		
		vert = QVBoxLayout(self)
		grid = QGridLayout()
		vert.addLayout(grid)

		self.name = QLineEdit()
		self.name.setText("New Symbol")
		grid.addWidget(QLabel("Symbol:"), 0, 0)
		grid.addWidget(self.name, 0, 1)
		self.name.setFocus()
		self.name.setSelection(0, 200) # Select all

		# Buttons
		hbox = QHBoxLayout()
		vert.addLayout(hbox)

		cancel = QPushButton("Cancel")
		hbox.addWidget(cancel)
		self.connect(cancel, SIGNAL("clicked()"), SLOT("reject()"))
		
		ok = QPushButton("Ok")
		ok.setDefault(True)
		hbox.addWidget(ok)
		self.connect(ok, SIGNAL("clicked()"), self.onOk)

		self.exec_()
Exemplo n.º 29
0
	def __init__(self, ticker):
		QDialog.__init__(self, None)
		self.app = appGlobal.getApp()
		self.deleted = False
		self.ticker = ticker
		self.setWindowTitle("Delete From Allocation")
		
		vert = QVBoxLayout(self)
		label = QLabel("Are you sure you wish to delete %s from your portfolio's allocation?" % ticker);
		label.setWordWrap(True)
		label.setMaximumWidth(300)
		vert.addWidget(label)

		# Buttons
		hbox = QHBoxLayout()
		vert.addLayout(hbox)
		
		hbox.addStretch(1000)

		cancel = QPushButton("Cancel")
		hbox.addWidget(cancel)
		self.connect(cancel, SIGNAL("clicked()"), SLOT("reject()"))
		
		ok = QPushButton("Ok")
		ok.setDefault(True)
		hbox.addWidget(ok)
		self.connect(ok, SIGNAL("clicked()"), self.onOk)
		
		self.exec_()
Exemplo n.º 30
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)

        self.setMinimumSize(300, 200)
        self.resize(800, 600)

        vert = QVBoxLayout(self)
        vert.setMargin(0)

        vert.addWidget(QLabel("Download transaction history from your bank or brokerage website"))

        self.webView = WebBrowser(self, downloadImport=True)
        self.webView.changeUrlCallback = self.newUrl
        self.webView.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        vert.addWidget(self.webView)

        # Check if user has saved a url
        url = appGlobal.getApp().portfolio.portPrefs.getUrl()
        if url:
            self.webView.locationEdit.setText(url)
            self.webView.changeLocation()

        self.setStyleSheet("QLabel { padding: 5px }")

        self.exec_()
Exemplo n.º 31
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)

        self.setMinimumSize(300, 200)
        self.resize(800, 600)

        vert = QVBoxLayout(self)
        vert.setMargin(0)

        vert.addWidget(
            QLabel(
                "Download transaction history from your bank or brokerage website"
            ))

        self.webView = WebBrowser(self, downloadImport=True)
        self.webView.changeUrlCallback = self.newUrl
        self.webView.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        vert.addWidget(self.webView)

        # Check if user has saved a url
        url = appGlobal.getApp().portfolio.portPrefs.getUrl()
        if url:
            self.webView.locationEdit.setText(url)
            self.webView.changeLocation()

        self.setStyleSheet("QLabel { padding: 5px }")

        self.exec_()
Exemplo n.º 32
0
	def setFinished(self):
		if self.finished:
			return
		self.finished = True
		
		self.progress.setValue(100)

		app = appGlobal.getApp()
		if app:
			app.statusUpdate = False
		
		if self.closeOnFinish:
			# If closing on finish, no longer modal, then close and return
			self.appYield()
			time.sleep(1)
			if self.modal:
				self.setModal(False)
			self.close()
			return
		
		self.ok.setEnabled(True)
		if self.cancelable:
			self.cancel.setEnabled(False)
		if self.modal:
			self.exec_()
Exemplo n.º 33
0
def check(value):
    app = appGlobal.getApp()

    # Check then show
    if not (app.prefs.getTutorial() & value):
        tut = Tutorial(tutorial=value)
        app.prefs.setTutorialBit(value)
Exemplo n.º 34
0
    def editTransaction(self):
        # Get transaction id
        row = self.table.selectedRow()
        if row == -1:
            return
        id = self.model.transactionIds[row]

        # Loop over transactions, edit id, reselect row and finish
        for t in appGlobal.getApp().portfolio.getTransactions():
            if t.uniqueId == id:
                if t.auto:
                    QMessageBox(
                        QMessageBox.Warning, "Cannot Edit",
                        "This tranaction was added by Icarra automatically to balance your portfolio.  It may not be edited."
                    ).exec_()
                    return

                NewTransaction(self, t).exec_()

                # Find the row for our transaction id, it may have changed
                i = 0
                for thisId in self.model.transactionIds:
                    if thisId == id:
                        self.table.selectRow(i)
                        break
                    i += 1
                break
Exemplo n.º 35
0
	def getFromServer(self, request, status = False):
		'''Return True if new stock data is received'''
		
		if appGlobal.getFailConnected():
			return False
		
		# Encode as string
		icarraTickers = {}
		lastTicker = False
		for (ticker, date) in request.items():
			icarraTicker = self.getIcarraTicker(ticker)
			icarraTickers[icarraTicker] = ticker
			
			# Change request to icarraTicker if necessary
			if icarraTicker != ticker:
				request[icarraTicker] = date.strftime("%Y-%m-%d %H:%M:%S")
				del request[ticker]
			else:
				request[ticker] = date.strftime("%Y-%m-%d %H:%M:%S")
		request["__UNIQUEID__"] = str(appGlobal.getApp().getUniqueId())

		try:
			if status:
				status.setStatus("Receiving Stock Data", 70)
			data = self.s.getStockZip(request)
		except Exception, inst:
			print traceback.format_exc()
			appGlobal.setFailConnected(True)
			return False
Exemplo n.º 36
0
	def __init__(self, parent):
		QWidget.__init__(self, parent)
		self.app = appGlobal.getApp()

		portfolio = self.app.portfolio
		
		vbox = QVBoxLayout(self)
		vbox.setAlignment(Qt.AlignTop)

		frame = QFrame()
		frame.setFrameStyle(QFrame.Panel)
		frame.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
		frame.setStyleSheet("QFrame { background: white; padding: 10px }")
		vbox.addWidget(frame)

		vbox2 = QVBoxLayout(frame)
		vbox2.setMargin(10)

		sync = self.app.portfolio.portPrefs.getSync()

		self.syncIcarra = QCheckBox("Sync with Icarra")
		self.connect(self.syncIcarra, SIGNAL("clicked()"), self.twiddleIcarra)
		if "icarra" in sync:
			self.syncIcarra.setChecked(True)
		vbox2.addWidget(self.syncIcarra)
		
		self.syncYahoo = QCheckBox("Sync with Yahoo Finance")
		self.connect(self.syncYahoo, SIGNAL("clicked()"), self.twiddleYahoo)
		self.syncYahoo.setDisabled(True)
		if "yahoo" in sync:
			self.syncYahoo.setChecked(True)
		vbox2.addWidget(self.syncYahoo)

		self.syncGoogle = QCheckBox("Sync with Google Finance")
		self.connect(self.syncGoogle, SIGNAL("clicked()"), self.twiddleGoogle)
		self.syncGoogle.setDisabled(True)
		if "google" in sync:
			self.syncGoogle.setChecked(True)
		vbox2.addWidget(self.syncGoogle)

		self.syncMorningstar = QCheckBox("Sync with Morningstar")
		self.connect(self.syncMorningstar, SIGNAL("clicked()"), self.twiddleMorningstar)
		self.syncMorningstar.setDisabled(True)
		if "morningstar" in sync:
			self.syncMorningstar.setChecked(True)
		vbox2.addWidget(self.syncMorningstar)
		vbox2.addSpacing(10)

		self.syncButton = QPushButton("Sync " + portfolio.name)
		self.syncButton.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
		self.connect(self.syncButton, SIGNAL("clicked()"), self.sync)
		vbox2.addWidget(self.syncButton)

		# Set timer for tutorial
		self.tutorialTimer = QTimer()
		self.tutorialTimer.setInterval(500)
		self.tutorialTimer.setSingleShot(True)
		self.connect(self.tutorialTimer, SIGNAL("timeout()"), self.checkTutorial)
		self.tutorialTimer.start()
Exemplo n.º 37
0
    def query(securityId, ticker, timestamp=False, value=False):
        if timestamp:
            dividend = appGlobal.getApp().stockData.getDividend(
                ticker, timestamp)
        else:
            dividend = appGlobal.getApp().stockData.getDividends(securityId)[0]

        if not dividend:
            return False
        else:
            if timestamp:
                dividend["securityId"] = securityId
                dividend["ticker"] = ticker
                return IcarraDividendRecord(row=dividend)
            else:
                print "not implemented"
                sys.exit()
Exemplo n.º 38
0
    def setErrors(self):
        app = appGlobal.getApp()

        errors = app.portfolio.errorCheck(app.stockData)
        self.errors = []
        for e in errors:
            self.errors.append(e)
        self.setData(self.errors)
Exemplo n.º 39
0
	def setErrors(self):
		app = appGlobal.getApp()
		
		errors = app.portfolio.errorCheck(app.stockData)
		self.errors = []
		for e in errors:
			self.errors.append(e)
		self.setData(self.errors)
Exemplo n.º 40
0
	def onOk(self):
		app = appGlobal.getApp()
		self.setCursor(Qt.WaitCursor)
		app.processEvents()

		newName = str(self.name.text())
		if re.search("[/\\.]", newName):
			QMessageBox(QMessageBox.Critical, 'Invalid Name', 'Please do not use any of the following characters: / or \ or .').exec_()
			return
		
		prefs = appGlobal.getApp().prefs
		
		# Check for unique name
		portfolios = prefs.getPortfolios()
		for name in portfolios:
			if name.upper() == newName.upper():
				QMessageBox(QMessageBox.Critical, 'Duplicate Name', 'A portfolio with that name already exists.  Please choose a new name.').exec_()
				return
		
		self.added = True
		
		# Create portfolio, go to settings, and select it
		prefs.addPortfolio(newName)
		prefs.setLastTab("Settings")
		prefs.setLastPortfolio(newName)
		app.main.ts.selectTool("Settings")
		app.loadPortfolio(newName)

		if self.benchmark.isChecked():
			app.portfolio.makeBenchmark()
			app.loadPortfolio(newName)
		elif self.combined.isChecked():
			app.portfolio.makeCombined()
			app.loadPortfolio(newName)
		elif self.bank.isChecked():
			app.portfolio.makeBank()
			app.loadPortfolio(newName)

		if self.benchmark.isChecked():
			app.portfolioMenuNames[newName] = "benchmark"
		else:
			app.portfolioMenuNames[newName] = "other"
		app.rebuildPortfoliosMenu()

		self.setCursor(Qt.ArrowCursor)
		self.close()
Exemplo n.º 41
0
    def query(securityId, timestamp=False, option=False):
        if timestamp:
            prices = appGlobal.getApp().stockData.getPrices(
                securityId, startDate=timestamp, endDate=timestamp)
        else:
            prices = appGlobal.getApp().stockData.getPrices(securityId)

        if not prices:
            return False
        else:
            if timestamp:
                row = prices[0]
                row["securityId"] = securityId
                return IcarraPriceRecord(row=row)
            else:
                print "not implemented"
                sys.exit()
Exemplo n.º 42
0
	def query(securityId, ticker, timestamp = False, value = False):
		if timestamp:
			split = appGlobal.getApp().stockData.getSplits(ticker, timestamp, timestamp)
			if split:
				split = split[0]
		else:
			split = appGlobal.getApp().stockData.getSplits(securityId)[0]
		if not split:
			return False
		else:
			if timestamp:
				split["securityId"] = securityId
				split["ticker"] = ticker
				return IcarraSplitRecord(row = split)
			else:
				print "not implemented"
				sys.exit()
Exemplo n.º 43
0
    def __init__(self, parent=None, *args):
        EditGridModel.__init__(self, parent, *args)

        self.showDeleted = False
        self.ticker = appGlobal.getApp().portfolio.getLastTicker()
        if self.ticker == "False" or self.ticker == "__COMBINED__":
            self.ticker = False

        self.setTransactions()

        columns = [
            "Date", "Position", "Transaction", "Shares", "$/Share", "Fee",
            "Total"
        ]
        if appGlobal.getApp().prefs.getShowCashInTransactions():
            columns.append("Cash Balance")
        self.setColumns(columns)
Exemplo n.º 44
0
    def setTransactions(self):
        app = appGlobal.getApp()
        app.portfolio.readFromDb()
        trans = app.portfolio.getTransactions(deletedOnly=self.showDeleted)
        self.transactions = []
        self.transactionIds = []

        # Build cash position if set
        showCash = app.prefs.getShowCashInTransactions()
        if showCash:
            trans.reverse()
            cash = 0
            for t in trans:
                cash += t.getCashMod()
                t.computedCashValue = cash
            trans.reverse()

        autoSplit = app.portfolio.portPrefs.getAutoSplit()
        autoDividend = app.portfolio.portPrefs.getAutoDividend()

        for t in trans:
            if not self.ticker or t.ticker == self.ticker or t.ticker2 == self.ticker:
                self.transactionIds.append(t.uniqueId)

                type = t.formatType()
                if t.auto:
                    type += " (auto)"
                elif autoSplit and t.type in [Transaction.split, Transaction.stockDividend]:
                    type += " (ignored)"
                elif (
                    autoDividend
                    and t.type in [Transaction.dividend, Transaction.dividendReinvest]
                    and t.ticker != "__CASH__"
                ):
                    type += " (ignored)"

                row = [t.getDate(), t.formatTicker(), type]
                if not app.portfolio.isBank():
                    if t.type in [
                        Transaction.deposit,
                        Transaction.withdrawal,
                        Transaction.dividend,
                        Transaction.adjustment,
                        Transaction.expense,
                        Transaction.split,
                    ]:
                        row.append("")
                    else:
                        row.append(t.formatShares())
                    row.append(t.formatPricePerShare())
                row.append(t.formatFee())
                row.append(t.formatTotal())
                if showCash:
                    row.append(Transaction.formatDollar(t.computedCashValue))

                self.transactions.append(row)

        self.setData(self.transactions)
Exemplo n.º 45
0
	def insert(self):
		data =  {
			"ticker": self.ticker,
			"date": self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
			"value": str(self.value)
		}
		
		appGlobal.getApp().stockData.db.insertOrUpdate("stockSplits", data)
		return

		assert(False)
		data =  {
			"securityId": str(self.securityId),
			"timestamp": datetime.datetime.strftime(self.timestamp, "%Y-%m-%d %H:%M:%S"),
			"value": str(self.value)
		}
		
		db.insert("splits", data)
Exemplo n.º 46
0
 def query(securityId, ticker, timestamp=False, value=False):
     if timestamp:
         split = appGlobal.getApp().stockData.getSplits(
             ticker, timestamp, timestamp)
         if split:
             split = split[0]
     else:
         split = appGlobal.getApp().stockData.getSplits(securityId)[0]
     if not split:
         return False
     else:
         if timestamp:
             split["securityId"] = securityId
             split["ticker"] = ticker
             return IcarraSplitRecord(row=split)
         else:
             print "not implemented"
             sys.exit()
Exemplo n.º 47
0
    def doImport(parent=None):
        portfolio = appGlobal.getApp().portfolio

        d = Import(parent)
        d.exec_()
        if d.didImport:
            portfolio.readFromDb()
            if appGlobal.getApp().tool.name() == "Transactions":
                appGlobal.getApp().toolWidget.rebuildPositions()
                appGlobal.getApp().toolWidget.model.setTransactions()
                appGlobal.getApp().toolWidget.table.resizeColumnsToContents()
Exemplo n.º 48
0
    def doImport(parent=None):
        portfolio = appGlobal.getApp().portfolio

        d = Import(parent)
        d.exec_()
        if d.didImport:
            portfolio.readFromDb()
            if appGlobal.getApp().tool.name() == "Transactions":
                appGlobal.getApp().toolWidget.rebuildPositions()
                appGlobal.getApp().toolWidget.model.setTransactions()
                appGlobal.getApp().toolWidget.table.resizeColumnsToContents()
Exemplo n.º 49
0
	def query(self, queryStr, tuple = False, reRaiseException = False):
		reRaiseException = True
		try:
			if tuple:
				self.lastQuery = "%s %s" % (queryStr, tuple)
				return self.getConn().execute(queryStr, tuple)
			else:
				self.lastQuery = queryStr
				return self.getConn().execute(queryStr)
		except Exception, e:
			if reRaiseException:
				raise
			
			# Show error if possible
			if appGlobal.getApp():
				appGlobal.getApp().addThreadSafeError("Database Error", "We encountered an error with the following query:" + queryStr + " (" + str(e) + ")")
			
			# Return empty string
			return self.getConn().execute("select 0 where 1 = 0")
Exemplo n.º 50
0
	def query(self, queryStr, tuple = False, reRaiseException = False):
		reRaiseException = True
		try:
			if tuple:
				self.lastQuery = "%s %s" % (queryStr, tuple)
				return self.getConn().execute(queryStr, tuple)
			else:
				self.lastQuery = queryStr
				return self.getConn().execute(queryStr)
		except Exception, e:
			if reRaiseException:
				raise
			
			# Show error if possible
			if appGlobal.getApp():
				appGlobal.getApp().addThreadSafeError("Database Error", "We encountered an error with the following query:" + queryStr + " (" + str(e) + ")")
			
			# Return empty string
			return self.getConn().execute("select 0 where 1 = 0")
Exemplo n.º 51
0
    def setTransactions(self):
        app = appGlobal.getApp()
        app.portfolio.readFromDb()
        trans = app.portfolio.getTransactions(deletedOnly=self.showDeleted)
        self.transactions = []
        self.transactionIds = []

        # Build cash position if set
        showCash = app.prefs.getShowCashInTransactions()
        if showCash:
            trans.reverse()
            cash = 0
            for t in trans:
                cash += t.getCashMod()
                t.computedCashValue = cash
            trans.reverse()

        autoSplit = app.portfolio.portPrefs.getAutoSplit()
        autoDividend = app.portfolio.portPrefs.getAutoDividend()

        for t in trans:
            if not self.ticker or t.ticker == self.ticker or t.ticker2 == self.ticker:
                self.transactionIds.append(t.uniqueId)

                type = t.formatType()
                if t.auto:
                    type += " (auto)"
                elif autoSplit and t.type in [
                        Transaction.split, Transaction.stockDividend
                ]:
                    type += " (ignored)"
                elif autoDividend and t.type in [
                        Transaction.dividend, Transaction.dividendReinvest
                ] and t.ticker != "__CASH__":
                    type += " (ignored)"

                row = [t.getDate(), t.formatTicker(), type]
                if not app.portfolio.isBank():
                    if t.type in [
                            Transaction.deposit, Transaction.withdrawal,
                            Transaction.dividend, Transaction.adjustment,
                            Transaction.expense, Transaction.split
                    ]:
                        row.append("")
                    else:
                        row.append(t.formatShares())
                    row.append(t.formatPricePerShare())
                row.append(t.formatFee())
                row.append(t.formatTotal())
                if showCash:
                    row.append(Transaction.formatDollar(t.computedCashValue))

                self.transactions.append(row)

        self.setData(self.transactions)
Exemplo n.º 52
0
    def __init__(self, parent=None):
        global haveKeyring
        QDialog.__init__(self, parent)
        self.app = appGlobal.getApp()
        self.setWindowTitle("Test login to " + self.app.portfolio.brokerage)

        self.ok = False
        self.didImport = False

        layout = QVBoxLayout(self)

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

        self.passwordLabel = QLabel("Password: "******"Save Password")
            hbox2 = QHBoxLayout()
            hbox2.addSpacing(20)
            layout.addLayout(hbox2)
            hbox2.addWidget(self.savePassword)
            layout.addSpacing(10)

            try:
                password = keyring.get_password(
                    "Icarra-ofx-" + self.app.portfolio.name,
                    self.app.portfolio.username)
                if password:
                    self.password.setText(password)
                    self.savePassword.setChecked(True)
            except:
                haveKeyring = False
                self.password.setDisabled(True)
                self.savePassword.setDisabled(True)

        self.password.setFocus()

        buttons = QHBoxLayout()
        layout.addLayout(buttons)

        cancel = QPushButton("Cancel")
        buttons.addWidget(cancel)
        self.connect(cancel, SIGNAL("clicked()"), SLOT("reject()"))

        ok = QPushButton("Ok")
        ok.setDefault(True)
        buttons.addWidget(ok)
        self.connect(ok, SIGNAL("clicked()"), self.onOk)
Exemplo n.º 53
0
    def insert(self):
        data = {
            "ticker": self.ticker,
            "date": self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
            "value": str(self.value)
        }

        appGlobal.getApp().stockData.db.insertOrUpdate("stockSplits", data)
        return

        assert (False)
        data = {
            "securityId":
            str(self.securityId),
            "timestamp":
            datetime.datetime.strftime(self.timestamp, "%Y-%m-%d %H:%M:%S"),
            "value":
            str(self.value)
        }

        db.insert("splits", data)
Exemplo n.º 54
0
    def checkTable(self, name, fields, index=[], unique=[]):
        # Only allow one thread to check a table at a time
        # Otherwise we may have two threads create/update the same table
        if appGlobal.getApp():
            appGlobal.getApp().checkTableMutex.acquire()

        # First create empty table
        try:
            createString = "create table if not exists " + name + "("
            first = True
            for f in fields:
                if first:
                    first = False
                else:
                    createString += ", "
                createString += f["name"] + " " + f["type"]
            createString += ")"
            cursor = self.getConn().execute(createString)
        except Exception, e:
            print e
            pass
Exemplo n.º 55
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.model = PerformanceModel(self)

        vbox = QVBoxLayout(self)
        vbox.setMargin(0)

        hor = QHBoxLayout()
        vbox.addLayout(hor)

        portfolio = appGlobal.getApp().portfolio

        hor.addWidget(QLabel("Type:"))
        self.chartType = QComboBox()
        self.chartTypes = [
            "Total Value", "Profit", "Return (Time Weighted)",
            "Return (Internal)"
        ]
        self.chartType.addItems(self.chartTypes)
        type = portfolio.portPrefs.getChartType()
        if type in self.chartTypes:
            self.chartType.setCurrentIndex(self.chartTypes.index(type))
            self.model.type = type.lower()
        hor.addWidget(self.chartType)
        self.connect(self.chartType, SIGNAL("currentIndexChanged(int)"),
                     self.changeType)

        current = QCheckBox("Current Symbols Only")
        if portfolio.portPrefs.getPerformanceCurrent():
            current.setChecked(True)
            self.model.current = True
        hor.addWidget(current)

        div = QCheckBox("Dividends")
        if portfolio.portPrefs.getPerformanceDividends():
            div.setChecked(True)
            self.model.dividend = True
        hor.addWidget(div)

        # Redraw when checkboxes are changed
        self.connect(current, SIGNAL("stateChanged(int)"), self.changeCurrent)
        self.connect(div, SIGNAL("stateChanged(int)"), self.changeDiv)

        hor.addStretch(1000)

        self.table = EditGrid(self.model)

        self.model.rebuildPerformance()
        self.table.resizeColumnsToContents()
        self.table.setSortingEnabled(True)

        vbox.addWidget(self.table)