示例#1
0
 def run(self):
     self.image = Gtk.Image()
     try:
         sock = urllib.urlopen(self.image_url, proxies=mate_invest.PROXY)
     except Exception, msg:
         mate_invest.debug("Error while opening %s: %s" %
                           (self.image_url, msg))
示例#2
0
	def __init__(self):
		self.state = STATE_UNKNOWN
		self.statechange_callback = None

		try:
			# get an event loop
			loop = DBusGMainLoop()

			# get the NetworkManager object from D-Bus
			mate_invest.debug("Connecting to Network Manager via D-Bus")
			bus = dbus.SystemBus(mainloop=loop)
			nmobj = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
			nm = dbus.Interface(nmobj, 'org.freedesktop.NetworkManager')

			# connect the signal handler to the bus
			bus.add_signal_receiver(self.handler, None,
					'org.freedesktop.NetworkManager',
					'org.freedesktop.NetworkManager',
					'/org/freedesktop/NetworkManager')

			# get the current status of the network manager
			self.state = nm.state()
			mate_invest.debug("Current Network Manager status is %d" % self.state)
		except Exception, msg:
			mate_invest.error("Could not connect to the Network Manager: %s" % msg )
    def __init__(self):
        self.state = STATE_UNKNOWN
        self.statechange_callback = None

        try:
            # get an event loop
            loop = DBusGMainLoop()

            # get the NetworkManager object from D-Bus
            mate_invest.debug("Connecting to Network Manager via D-Bus")
            bus = dbus.SystemBus(mainloop=loop)
            nmobj = bus.get_object('org.freedesktop.NetworkManager',
                                   '/org/freedesktop/NetworkManager')
            nm = dbus.Interface(nmobj, 'org.freedesktop.NetworkManager')

            # connect the signal handler to the bus
            bus.add_signal_receiver(self.handler, None,
                                    'org.freedesktop.NetworkManager',
                                    'org.freedesktop.NetworkManager',
                                    '/org/freedesktop/NetworkManager')

            # get the current status of the network manager
            self.state = nm.state()
            mate_invest.debug("Current Network Manager status is %d" %
                              self.state)
        except Exception, msg:
            mate_invest.error("Could not connect to the Network Manager: %s" %
                              msg)
示例#4
0
	def show_run_hide(self, explanation = ""):
		expl = self.ui.get_object("explanation")
		expl.set_markup(explanation)
		self.dialog.show_all()
		if explanation == "":
			expl.hide()
		# returns 1 if help is clicked
		while self.dialog.run() == 1:
			pass
		self.dialog.destroy()

		mate_invest.STOCKS = {}

		def save_symbol(model, path, iter, data):
			#if int(model[iter][1]) == 0 or float(model[iter][2]) < 0.0001:
			#	return

			if not model[iter][0] in mate_invest.STOCKS:
				mate_invest.STOCKS[model[iter][0]] = { 'label': model[iter][1], 'purchases': [] }
				
			mate_invest.STOCKS[model[iter][0]]["purchases"].append({
				"amount": float(model[iter][2]),
				"bought": float(model[iter][3]),
				"comission": float(model[iter][4]),
				"exchange": float(model[iter][5])
			})
		self.model.foreach(save_symbol, None)
		try:
			cPickle.dump(mate_invest.STOCKS, file(mate_invest.STOCKS_FILE, 'w'))
			mate_invest.debug('Stocks written to file')
		except Exception, msg:
			mate_invest.error('Could not save stocks file: %s' % msg)
示例#5
0
	def save_currencies(self, data):
		mate_invest.debug("Storing currencies to %s" % mate_invest.CURRENCIES_FILE)
		try:
			f = open(mate_invest.CURRENCIES_FILE, 'w')
			f.write(data)
			f.close()
		except Exception as msg:
			mate_invest.error("Could not save the retrieved currencies to %s: %s" % (mate_invest.CURRENCIES_FILE, msg) )
示例#6
0
	def on_currency_retriever_completed(self, retriever):
		if retriever.retrieved == False:
			mate_invest.error("Failed to retrieve currency rates!")
		else:
			mate_invest.debug("CurrencyRetriever completed")
			self.save_currencies(retriever.data)
			self.load_currencies()
		self.update_tooltip()
示例#7
0
	def save_quotes(self, data):
		mate_invest.debug("Storing quotes")
		try:
			f = open(mate_invest.QUOTES_FILE, 'w')
			f.write(data)
			f.close()
		except Exception, msg:
			mate_invest.error("Could not save the retrieved quotes file to %s: %s" % (mate_invest.QUOTES_FILE, msg) )
示例#8
0
	def save_quotes(self, data):
		mate_invest.debug("Storing quotes")
		try:
			f = open(mate_invest.QUOTES_FILE, 'w')
			f.write(data)
			f.close()
		except Exception, msg:
			mate_invest.error("Could not save the retrieved quotes file to %s: %s" % (mate_invest.QUOTES_FILE, msg) )
示例#9
0
	def run(self):
		quotes_url = QUOTES_URL % {"s": self.tickers}
		try:
			quotes_file = urlopen(quotes_url, proxies = mate_invest.PROXY)
			self.data = quotes_file.readlines ()
			quotes_file.close ()
		except Exception, msg:
			mate_invest.debug("Error while retrieving quotes data (url = %s): %s" % (quotes_url, msg))
示例#10
0
	def set_update_interval(self, interval):
		if self.timeout_id != None:
			mate_invest.debug("Canceling refresh timer")
			GObject.source_remove(self.timeout_id)
			self.timeout_id = None
		if interval > 0:
			mate_invest.debug("Setting refresh timer to %s:%02d.%03d" % ( interval / 60000, interval % 60000 / 1000, interval % 1000) )
			self.timeout_id = GObject.timeout_add(interval, self.refresh)
示例#11
0
	def __init__(self, tickers):
		Thread.__init__(self)
		_IdleObject.__init__(self)
		self.tickers = tickers
		self.retrieved = False
		self.data = []
		self.currencies = []
                mate_invest.debug("QuotesRetriever created");
示例#12
0
	def save_currencies(self, data):
		mate_invest.debug("Storing currencies to %s" % mate_invest.CURRENCIES_FILE)
		try:
			f = open(mate_invest.CURRENCIES_FILE, 'w')
			f.write(data)
			f.close()
		except Exception as msg:
			mate_invest.error("Could not save the retrieved currencies to %s: %s" % (mate_invest.CURRENCIES_FILE, msg) )
示例#13
0
	def on_currency_retriever_completed(self, retriever):
		if retriever.retrieved == False:
			mate_invest.error("Failed to retrieve currency rates!")
		else:
			mate_invest.debug("CurrencyRetriever completed")
			self.save_currencies(retriever.data)
			self.load_currencies()
		self.update_tooltip()
示例#14
0
	def __init__(self, tickers):
		Thread.__init__(self)
		_IdleObject.__init__(self)
		self.tickers = tickers
		self.retrieved = False
		self.data = []
		self.currencies = []
                mate_invest.debug("QuotesRetriever created");
示例#15
0
	def load_currencies(self):
		mate_invest.debug("Loading currencies from %s" % mate_invest.CURRENCIES_FILE)
		try:
			f = open(mate_invest.CURRENCIES_FILE, 'r')
			data = f.readlines()
			f.close()

			self.convert_currencies(self.parse_yahoo_csv(csv.reader(data)))
		except Exception as msg:
			mate_invest.error("Could not load the currencies from %s: %s" % (mate_invest.CURRENCIES_FILE, msg) )
示例#16
0
	def load_currencies(self):
		mate_invest.debug("Loading currencies from %s" % mate_invest.CURRENCIES_FILE)
		try:
			f = open(mate_invest.CURRENCIES_FILE, 'r')
			data = f.readlines()
			f.close()

			self.convert_currencies(self.parse_yahoo_csv(csv.reader(data)))
		except Exception as msg:
			mate_invest.error("Could not load the currencies from %s: %s" % (mate_invest.CURRENCIES_FILE, msg) )
示例#17
0
	def handler(self,signal=None):
		if isinstance(signal, dict):
			state = signal.get('State')
			if state != None:
				mate_invest.debug("Network Manager change state %d => %d" % (self.state, state) );
				self.state = state

				# notify about state change
				if self.statechange_callback != None:
					self.statechange_callback()
示例#18
0
	def on_retriever_completed(self, retriever):
		if retriever.retrieved == False:
                        mate_invest.debug("QuotesRetriever failed");
                        self.update_tooltip(_('Invest could not connect to Yahoo! Finance'))

		else:
                        mate_invest.debug("QuotesRetriever completed");
                        # cache the retrieved csv file
                        self.save_quotes(retriever.data)
                        # load the cache and parse it
                        self.load_quotes()
示例#19
0
    def handler(self, signal=None):
        if isinstance(signal, dict):
            state = signal.get('State')
            if state != None:
                mate_invest.debug("Network Manager change state %d => %d" %
                                  (self.state, state))
                self.state = state

                # notify about state change
                if self.statechange_callback != None:
                    self.statechange_callback()
示例#20
0
	def on_retriever_completed(self, retriever):
		if retriever.retrieved == False:
                        mate_invest.debug("QuotesRetriever failed");
                        self.update_tooltip(_('Invest could not connect to Yahoo! Finance'))

		else:
                        mate_invest.debug("QuotesRetriever completed");
                        # cache the retrieved csv file
                        self.save_quotes(retriever.data)
                        # load the cache and parse it
                        self.load_quotes()
示例#21
0
	def load_quotes(self):
		mate_invest.debug("Loading quotes");
		try:
			f = open(mate_invest.QUOTES_FILE, 'r')
			data = f.readlines()
			f.close()

			self.populate(self.parse_yahoo_csv(csv.reader(data)))
			self.updated = True
			self.last_updated = datetime.datetime.fromtimestamp(getmtime(mate_invest.QUOTES_FILE))
			self.update_tooltip()
		except Exception, msg:
			mate_invest.error("Could not load the cached quotes file %s: %s" % (mate_invest.QUOTES_FILE, msg) )
示例#22
0
	def load_quotes(self):
		mate_invest.debug("Loading quotes");
		try:
			f = open(mate_invest.QUOTES_FILE, 'r')
			data = f.readlines()
			f.close()

			self.populate(self.parse_yahoo_csv(csv.reader(data)))
			self.updated = True
			self.last_updated = datetime.datetime.fromtimestamp(getmtime(mate_invest.QUOTES_FILE))
			self.update_tooltip()
		except Exception, msg:
			mate_invest.error("Could not load the cached quotes file %s: %s" % (mate_invest.QUOTES_FILE, msg) )
示例#23
0
	def __init__(self, ui):
		self.ui = ui
		
		#Time ranges of the plot
		self.time_ranges = ["1d", "5d", "3m", "6m", "1y", "5y", "my"]
		
		# Window Properties
		win = ui.get_object("window")
		win.set_title(_("Financial Chart"))
		
		try:
			pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(join(mate_invest.ART_DATA_DIR, "invest_neutral.svg"), 96,96)
			self.ui.get_object("plot").set_from_pixbuf(pixbuf)
		except Exception, msg:
			mate_invest.debug("Could not load 'invest-neutral.svg' file: %s" % msg)
			pass
示例#24
0
	def refresh(self):
		mate_invest.debug("Refreshing")

		# when nm tells me I am offline, stop the update interval
		if mate_invest.nm.offline():
			mate_invest.debug("We are offline, stopping update timer")
			self.set_update_interval(0)
			return False

		if len(mate_invest.STOCKS) == 0:
			return True

		tickers = '+'.join(mate_invest.STOCKS.keys())
		quotes_retriever = QuotesRetriever(tickers)
		quotes_retriever.connect("completed", self.on_retriever_completed)
		quotes_retriever.start()

		return True
示例#25
0
    def show_run_hide(self, explanation=""):
        expl = self.ui.get_object("explanation")
        expl.set_markup(explanation)
        self.dialog.show_all()
        if explanation == "":
            expl.hide()
        # returns 1 if help is clicked
        while self.dialog.run() == 1:
            pass
        self.dialog.destroy()

        mate_invest.STOCKS = {}

        def save_symbol(model, path, iter, data):
            #if int(model[iter][1]) == 0 or float(model[iter][2]) < 0.0001:
            #	return

            if not model[iter][0] in mate_invest.STOCKS:
                mate_invest.STOCKS[model[iter][0]] = {
                    'label': model[iter][1],
                    'purchases': []
                }

            mate_invest.STOCKS[model[iter][0]]["purchases"].append({
                "amount":
                float(model[iter][2]),
                "bought":
                float(model[iter][3]),
                "comission":
                float(model[iter][4]),
                "exchange":
                float(model[iter][5])
            })

        self.model.foreach(save_symbol, None)
        try:
            cPickle.dump(mate_invest.STOCKS, file(mate_invest.STOCKS_FILE,
                                                  'w'))
            mate_invest.debug('Stocks written to file')
        except Exception, msg:
            mate_invest.error('Could not save stocks file: %s' % msg)
示例#26
0
	def __init__(self, ui):
		self.ui = ui
		
		#Time ranges of the plot (parameter / combo-box t)
		self.time_ranges = ["1d", "5d", "3m", "6m", "1y", "5y", "my"]
		
		#plot types (parameter / combo-box q)
		self.plot_types = ["l", "b", "c"]

		#plot scales (parameter / combo-box l)
		self.plot_scales = ["off", "on"]

		# Window Properties
		win = ui.get_object("window")
		win.set_title(_("Financial Chart"))
		
		try:
			pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(join(mate_invest.ART_DATA_DIR, "invest_neutral.svg"), 96,96)
			self.ui.get_object("plot").set_from_pixbuf(pixbuf)
		except Exception, msg:
			mate_invest.debug("Could not load 'invest-neutral.svg' file: %s" % msg)
			pass
示例#27
0
        self.model.foreach(save_symbol, None)
        try:
            cPickle.dump(mate_invest.STOCKS, file(mate_invest.STOCKS_FILE,
                                                  'w'))
            mate_invest.debug('Stocks written to file')
        except Exception, msg:
            mate_invest.error('Could not save stocks file: %s' % msg)

        mate_invest.CONFIG = {}
        if self.currency_code != None and len(self.currency_code) == 3:
            mate_invest.CONFIG['currency'] = self.currency_code
        try:
            cPickle.dump(mate_invest.CONFIG, file(mate_invest.CONFIG_FILE,
                                                  'w'))
            mate_invest.debug('Configuration written to file')
        except Exception, msg:
            mate_invest.debug('Could not save configuration file: %s' % msg)

    def sync_ui(self):
        pass

    def on_add_stock(self, w):
        iter = self.model.append(["GOOG", "Google Inc.", 0.0, 0.0, 0.0, 0.0])
        path = self.model.get_path(iter)
        self.treeview.set_cursor(path, self.treeview.get_column(0), True)

    def on_remove_stock(self, w):
        model, paths = self.treeview.get_selection().get_selected_rows()
        for path in paths:
            model.remove(model.get_iter(path))
示例#28
0
def applet_factory(applet, iid, data):
	mate_invest.debug('Starting invest instance: %s %s'% ( applet, iid ))
	mate_invest.applet.InvestApplet(applet)
	return True
示例#29
0
	standalone = False

	try:
		opts, args = getopt.getopt(sys.argv[1:], "hdw", ["help", "debug", "window"])
	except getopt.GetoptError:
		# Unknown args were passed, we fallback to behave as if
		# no options were passed
		opts = []
		args = sys.argv[1:]

	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
		elif o in ("-d", "--debug"):
			mate_invest.DEBUGGING = True
			mate_invest.debug("Debugging enabled")
			# these messages cannot be turned by mate_invest.DEBUGGING at their originating location,
			# because that variable was set here to be True
			mate_invest.debug("Data Dir: %s" % mate_invest.SHARED_DATA_DIR)
			mate_invest.debug("Detected PROXY: %s" % mate_invest.PROXY)
		elif o in ("-w", "--window"):
			standalone = True

	if standalone:
		build_window()
		Gtk.main()
	else:
		MatePanelApplet.Applet.factory_main(
			"InvestAppletFactory",
			True,
			MatePanelApplet.Applet.__gtype__,
示例#30
0
				self.avg_quotes_change = 0
				
			# mark quotes to finally be valid
			self.quotes_valid = True

		except Exception, msg:
			mate_invest.debug("Failed to populate quotes: %s" % msg)
			mate_invest.debug(quotes)
			self.quotes_valid = False

		# start retrieving currency conversion rates
		if mate_invest.CONFIG.has_key("currency"):
			target_currency = mate_invest.CONFIG["currency"]
			symbols = []

			mate_invest.debug("These currencies occur: %s" % self.currencies)
			for currency in self.currencies:
				if currency == target_currency:
					continue

				mate_invest.debug("%s will be converted to %s" % ( currency, target_currency ))
				symbol = currency + target_currency + "=X"
				symbols.append(symbol)

			if len(symbols) > 0:
				tickers = '+'.join(symbols)
				quotes_retriever = QuotesRetriever(tickers)
				quotes_retriever.connect("completed", self.on_currency_retriever_completed)
				quotes_retriever.start()

	def convert_currencies(self, quotes):
示例#31
0
        try:
            sock = urllib.urlopen(self.image_url, proxies=mate_invest.PROXY)
        except Exception, msg:
            mate_invest.debug("Error while opening %s: %s" %
                              (self.image_url, msg))
        else:
            loader = GdkPixbuf.PixbufLoader()
            loader.connect(
                "closed",
                lambda loader: self.image.set_from_pixbuf(loader.get_pixbuf()))
            loader.write(sock.read())
            sock.close()
            try:
                loader.close()
            except Exception, msg:
                mate_invest.debug("Error handling %s: %s" %
                                  (self.image_url, msg))
            else:
                self.retrieved = True
        self.emit("completed")


# p:
#  eX = Exponential Moving Average
#  mX = Moving Average
#  b = Bollinger Bands Overlay
#  v = Volume Overlay
#  p = Parabolic SAR overlay
#  s = Splits Overlay
# q:
#  l = Line
#  c = Candles
示例#32
0
				"comission": float(model[iter][4]),
				"exchange": float(model[iter][5])
			})
		self.model.foreach(save_symbol, None)
		try:
			cPickle.dump(mate_invest.STOCKS, file(mate_invest.STOCKS_FILE, 'w'))
			mate_invest.debug('Stocks written to file')
		except Exception, msg:
			mate_invest.error('Could not save stocks file: %s' % msg)

		mate_invest.CONFIG = {}
		if self.currency_code != None and len(self.currency_code) == 3:
			mate_invest.CONFIG['currency'] = self.currency_code
		try:
			cPickle.dump(mate_invest.CONFIG, file(mate_invest.CONFIG_FILE, 'w'))
			mate_invest.debug('Configuration written to file')
		except Exception, msg:
			mate_invest.debug('Could not save configuration file: %s' % msg)

	def sync_ui(self):
		pass

	def on_add_stock(self, w):
		iter = self.model.append(["GOOG", "Google Inc.", 0.0, 0.0, 0.0, 0.0])
		path = self.model.get_path(iter)
		self.treeview.set_cursor(path, self.treeview.get_column(0), True)

	def on_remove_stock(self, w):
		model, paths = self.treeview.get_selection().get_selected_rows()
		for path in paths:
			model.remove(model.get_iter(path))
示例#33
0
class QuoteUpdater(Gtk.ListStore):
	updated = False
	last_updated = None
	quotes_valid = False
	timeout_id = None
	SYMBOL, LABEL, CURRENCY, TICKER_ONLY, BALANCE, BALANCE_PCT, VALUE, VARIATION_PCT, PB = range(9)
	def __init__ (self, change_icon_callback, set_tooltip_callback):
		Gtk.ListStore.__init__ (self, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, bool, float, float, float, float, GdkPixbuf.Pixbuf)
		self.set_update_interval(AUTOREFRESH_TIMEOUT)
		self.change_icon_callback = change_icon_callback
		self.set_tooltip_callback = set_tooltip_callback
		self.set_sort_column_id(1, Gtk.SortType.ASCENDING)
		self.refresh()

		# tell the network manager to notify me when network status changes
		mate_invest.nm.set_statechange_callback(self.nm_state_changed)

	def set_update_interval(self, interval):
		if self.timeout_id != None:
			mate_invest.debug("Canceling refresh timer")
			GObject.source_remove(self.timeout_id)
			self.timeout_id = None
		if interval > 0:
			mate_invest.debug("Setting refresh timer to %s:%02d.%03d" % ( interval / 60000, interval % 60000 / 1000, interval % 1000) )
			self.timeout_id = GObject.timeout_add(interval, self.refresh)

	def nm_state_changed(self):
		# when nm is online but we do not have an update timer, create it and refresh
		if mate_invest.nm.online():
			if self.timeout_id == None:
				self.set_update_interval(AUTOREFRESH_TIMEOUT)
				self.refresh()

	def refresh(self):
		mate_invest.debug("Refreshing")

		# when nm tells me I am offline, stop the update interval
		if mate_invest.nm.offline():
			mate_invest.debug("We are offline, stopping update timer")
			self.set_update_interval(0)
			return False

		if len(mate_invest.STOCKS) == 0:
			return True

		tickers = '+'.join(mate_invest.STOCKS.keys())
		quotes_retriever = QuotesRetriever(tickers)
		quotes_retriever.connect("completed", self.on_retriever_completed)
		quotes_retriever.start()

		return True


	# locale-aware formatting of the percent float (decimal point, thousand grouping point) with 2 decimal digits
	def format_percent(self, value):
		return locale.format("%+.2f", value, True) + "%"

	# locale-aware formatting of the float value (decimal point, thousand grouping point) with sign and 2 decimal digits
	def format_difference(self, value):
		return locale.format("%+.2f", value, True, True)

	def on_retriever_completed(self, retriever):
		if retriever.retrieved == False:
			tooltip = [_('Invest could not connect to Yahoo! Finance')]
			if self.last_updated != None:
				# Translators: %s is an hour (%H:%M)
				tooltip.append(_('Updated at %s') % self.last_updated.strftime("%H:%M"))
			self.set_tooltip_callback('\n'.join(tooltip))
		else:
			self.populate(self.parse_yahoo_csv(csv.reader(retriever.data)))
			self.updated = True
			self.last_updated = datetime.datetime.now()
			self.update_tooltip()

	def on_currency_retriever_completed(self, retriever):
		if retriever.retrieved == False:
			mate_invest.error("Failed to retrieve currency rates!")
		else:
			self.convert_currencies(self.parse_yahoo_csv(csv.reader(retriever.data)))
		self.update_tooltip()

	def update_tooltip(self):
		tooltip = []
		if self.quotes_count > 0:
			# Translators: This is share-market jargon. It is the average percentage change of all stock prices. The %s gets replaced with the string value of the change (localized), including the percent sign.
			tooltip.append(_('Average change: %s') % self.format_percent(self.avg_quotes_change))
		for currency, stats in self.statistics.items():
			# get the statsitics
			balance = stats["balance"]
			paid = stats["paid"]
			change = self.format_percent(balance / paid * 100)
			balance = self.format_difference(balance)

			# Translators: This is share-market jargon. It refers to the total difference between the current price and purchase price for all the shares put together for a particular currency. i.e. How much money would be earned if they were sold right now. The first string is the change value, the second the currency, and the third value is the percentage of the change, formatted using user's locale.
			tooltip.append(_('Positions balance: %s %s (%s)') % (balance, currency, change))
		tooltip.append(_('Updated at %s') % self.last_updated.strftime("%H:%M"))
		self.set_tooltip_callback('\n'.join(tooltip))


	def parse_yahoo_csv(self, csvreader):
		result = {}
		for fields in csvreader:
			if len(fields) == 0:
				continue

			result[fields[0]] = {}
			for i, field in enumerate(QUOTES_CSV_FIELDS):
				if type(field) == tuple:
					try:
						result[fields[0]][field[0]] = field[1](fields[i])
					except:
						result[fields[0]][field[0]] = 0
				else:
					result[fields[0]][field] = fields[i]
			# calculated fields
			try:
				result[fields[0]]['variation_pct'] = result[fields[0]]['variation'] / float(result[fields[0]]['trade'] - result[fields[0]]['variation']) * 100
			except ZeroDivisionError:
				result[fields[0]]['variation_pct'] = 0
		return result

	# Computes the balance of the given purchases using a certain current value
	# and optionally a current exchange rate.
	def balance(self, purchases, value, currentrate=None):
		current = 0
		paid = 0

		for purchase in purchases:
			if purchase["amount"] != 0:
				buyrate = purchase["exchange"]
				# if the buy rate is invalid, use 1.0
				if buyrate <= 0:
					buyrate = 1.0

				# if no current rate is given, ignore buy rate
				if currentrate == None:
					buyrate = 1.0
					rate = 1.0
				else:
					# otherwise, take use buy rate and current rate to compute the balance
					rate = currentrate

				# current value is the current rate * amount * value
				current += rate * purchase["amount"] * value
				# paid is buy rate * ( amount * price + commission )
				paid += buyrate * (purchase["amount"] * purchase["bought"] + purchase["comission"])

		balance = current - paid
		if paid != 0:
			change = 100*balance/paid
		else:
			change = 100 # Not technically correct, but it will look more intuitive than the real result of infinity.

		return (balance, change)

	def populate(self, quotes):
		if (len(quotes) == 0):
			return

		self.clear()
		self.currencies = []

		try:
			quote_items = quotes.items ()
			quote_items.sort ()

			quotes_change = 0
			self.quotes_count = 0
			self.statistics = {}

			for ticker, val in quote_items:
				pb = None

				# get the label of this stock for later reuse
				label = mate_invest.STOCKS[ticker]["label"]
				if len(label) == 0:
					if len(val["label"]) != 0:
						label = val["label"]
					else:
						label = ticker

				# make sure the currency field is upper case
				val["currency"] = val["currency"].upper();

				# the currency of currency conversion rates like EURUSD=X is wrong in csv
				# this can be fixed easily by reusing the latter currency in the symbol
				if len(ticker) == 8 and ticker.endswith("=X"):
					val["currency"] = ticker[3:6]

				# indices should not have a currency, though yahoo says so
				if ticker.startswith("^"):
					val["currency"] = ""

				# sometimes, funny currencies are returned (special characters), only consider known currencies
				if len(val["currency"]) > 0 and val["currency"] not in currencies.Currencies.currencies:
					mate_invest.debug("Currency '%s' is not known, dropping" % val["currency"])
					val["currency"] = ""

				# if this is a currency not yet seen and different from the target currency, memorize it
				if val["currency"] not in self.currencies and len(val["currency"]) > 0:
					self.currencies.append(val["currency"])

				# Check whether the symbol is a simple quote, or a portfolio value
				is_simple_quote = True
				for purchase in mate_invest.STOCKS[ticker]["purchases"]:
					if purchase["amount"] != 0:
						is_simple_quote = False
						break

				if is_simple_quote:
					row = self.insert(0, [ticker, label, val["currency"], True, 0.0, 0.0, val["trade"], val["variation_pct"], pb])
				else:
					(balance, change) = self.balance(mate_invest.STOCKS[ticker]["purchases"], val["trade"])
					row = self.insert(0, [ticker, label, val["currency"], False, float(balance), float(change), val["trade"], val["variation_pct"], pb])
					self.add_balance_change(balance, change, val["currency"])

				if len(ticker.split('.')) == 2:
					url = 'http://ichart.europe.yahoo.com/h?s=%s' % ticker
				else:
					url = 'http://ichart.yahoo.com/h?s=%s' % ticker

				image_retriever = mate_invest.chart.ImageRetriever(url)
				image_retriever.connect("completed", self.set_pb_callback, row)
				image_retriever.start()

			        quotes_change += val['variation_pct']
			        self.quotes_count += 1

			# we can only compute an avg quote if there are quotes
			if self.quotes_count > 0:
			        self.avg_quotes_change = quotes_change / float(self.quotes_count)

			        # change icon
			        quotes_change_sign = 0
			        if self.avg_quotes_change != 0:
			                quotes_change_sign = self.avg_quotes_change / abs(self.avg_quotes_change)
			        self.change_icon_callback(quotes_change_sign)
			else:
				self.avg_quotes_change = 0
				
			# mark quotes to finally be valid
			self.quotes_valid = True

		except Exception, msg:
			mate_invest.debug("Failed to populate quotes: %s" % msg)
			mate_invest.debug(quotes)
			self.quotes_valid = False

		# start retrieving currency conversion rates
		if mate_invest.CONFIG.has_key("currency"):
			target_currency = mate_invest.CONFIG["currency"]
			symbols = []

			mate_invest.debug("These currencies occur: %s" % self.currencies)
			for currency in self.currencies:
				if currency == target_currency:
					continue

				mate_invest.debug("%s will be converted to %s" % ( currency, target_currency ))
				symbol = currency + target_currency + "=X"
				symbols.append(symbol)

			if len(symbols) > 0:
				tickers = '+'.join(symbols)
				quotes_retriever = QuotesRetriever(tickers)
				quotes_retriever.connect("completed", self.on_currency_retriever_completed)
				quotes_retriever.start()
示例#34
0
	def populate(self, quotes):
		if (len(quotes) == 0):
			return

		self.clear()
		self.currencies = []

		try:
			quote_items = quotes.items ()
			quote_items.sort ()

			quotes_change = 0
			self.quotes_count = 0
			self.statistics = {}

			for ticker, val in quote_items:
				pb = None

				# get the label of this stock for later reuse
				label = mate_invest.STOCKS[ticker]["label"]
				if len(label) == 0:
					if len(val["label"]) != 0:
						label = val["label"]
					else:
						label = ticker

				# make sure the currency field is upper case
				val["currency"] = val["currency"].upper();

				# the currency of currency conversion rates like EURUSD=X is wrong in csv
				# this can be fixed easily by reusing the latter currency in the symbol
				if len(ticker) == 8 and ticker.endswith("=X"):
					val["currency"] = ticker[3:6]

				# indices should not have a currency, though yahoo says so
				if ticker.startswith("^"):
					val["currency"] = ""

				# sometimes, funny currencies are returned (special characters), only consider known currencies
				if len(val["currency"]) > 0 and val["currency"] not in currencies.Currencies.currencies:
					mate_invest.debug("Currency '%s' is not known, dropping" % val["currency"])
					val["currency"] = ""

				# if this is a currency not yet seen and different from the target currency, memorize it
				if val["currency"] not in self.currencies and len(val["currency"]) > 0:
					self.currencies.append(val["currency"])

				# Check whether the symbol is a simple quote, or a portfolio value
				is_simple_quote = True
				for purchase in mate_invest.STOCKS[ticker]["purchases"]:
					if purchase["amount"] != 0:
						is_simple_quote = False
						break

				if is_simple_quote:
					row = self.insert(0, [ticker, label, val["currency"], True, 0.0, 0.0, val["trade"], val["variation_pct"], pb])
				else:
					(balance, change) = self.balance(mate_invest.STOCKS[ticker]["purchases"], val["trade"])
					row = self.insert(0, [ticker, label, val["currency"], False, float(balance), float(change), val["trade"], val["variation_pct"], pb])
					self.add_balance_change(balance, change, val["currency"])

				if len(ticker.split('.')) == 2:
					url = 'http://ichart.europe.yahoo.com/h?s=%s' % ticker
				else:
					url = 'http://ichart.yahoo.com/h?s=%s' % ticker

				image_retriever = mate_invest.chart.ImageRetriever(url)
				image_retriever.connect("completed", self.set_pb_callback, row)
				image_retriever.start()

			        quotes_change += val['variation_pct']
			        self.quotes_count += 1

			# we can only compute an avg quote if there are quotes
			if self.quotes_count > 0:
			        self.avg_quotes_change = quotes_change / float(self.quotes_count)

			        # change icon
			        quotes_change_sign = 0
			        if self.avg_quotes_change != 0:
			                quotes_change_sign = self.avg_quotes_change / abs(self.avg_quotes_change)
			        self.change_icon_callback(quotes_change_sign)
			else:
				self.avg_quotes_change = 0
				
			# mark quotes to finally be valid
			self.quotes_valid = True

		except Exception, msg:
			mate_invest.debug("Failed to populate quotes: %s" % msg)
			mate_invest.debug(quotes)
			self.quotes_valid = False
示例#35
0
	def run(self):
		self.image = Gtk.Image()
		try: sock = urllib.urlopen(self.image_url, proxies = mate_invest.PROXY)
		except Exception, msg:
			mate_invest.debug("Error while opening %s: %s" % (self.image_url, msg))
示例#36
0
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hdw",
                                   ["help", "debug", "window"])
    except getopt.GetoptError:
        # Unknown args were passed, we fallback to behave as if
        # no options were passed
        opts = []
        args = sys.argv[1:]

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
        elif o in ("-d", "--debug"):
            mate_invest.DEBUGGING = True
            mate_invest.debug("Debugging enabled")
            # these messages cannot be turned by mate_invest.DEBUGGING at their originating location,
            # because that variable was set here to be True
            mate_invest.debug("Data Dir: %s" % mate_invest.SHARED_DATA_DIR)
            mate_invest.debug("Detected PROXY: %s" % mate_invest.PROXY)
        elif o in ("-w", "--window"):
            standalone = True

    if standalone:
        build_window()
        Gtk.main()
    else:
        MatePanelApplet.Applet.factory_main("InvestAppletFactory", True,
                                            MatePanelApplet.Applet.__gtype__,
                                            applet_factory, None)
示例#37
0
				self.avg_quotes_change = 0
				
			# mark quotes to finally be valid
			self.quotes_valid = True

		except Exception, msg:
			mate_invest.debug("Failed to populate quotes: %s" % msg)
			mate_invest.debug(quotes)
			self.quotes_valid = False

		# start retrieving currency conversion rates
		if mate_invest.CONFIG.has_key("currency"):
			target_currency = mate_invest.CONFIG["currency"]
			symbols = []

			mate_invest.debug("These currencies occur: %s" % self.currencies)
			for currency in self.currencies:
				if currency == target_currency:
					continue

				mate_invest.debug("%s will be converted to %s" % ( currency, target_currency ))
				symbol = currency + target_currency + "=X"
				symbols.append(symbol)

			if len(symbols) > 0:
				tickers = '+'.join(symbols)
				quotes_retriever = QuotesRetriever(tickers)
				quotes_retriever.connect("completed", self.on_currency_retriever_completed)
				quotes_retriever.start()

	def convert_currencies(self, quotes):
示例#38
0
def applet_factory(applet, iid, data):
    mate_invest.debug('Starting invest instance: %s %s' % (applet, iid))
    mate_invest.applet.InvestApplet(applet)
    return True