some fixes
[stockthis] / stockthis.py
1 #!/usr/bin/env python2.5
2 # -*- coding: UTF8 -*-
3 # Copyright (C) 2008 by Daniel Martin Yerga
4 # <dyerga@gmail.com>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 #
19 # StocksPy: Application to get stocks data from Yahoo Finance.
20 # Version 0.1
21 #
22
23 import urllib2
24 import gtk, gobject
25 try:
26     import hildon
27     HILDON = True
28 except:
29     HILDON = False
30
31 try:
32     import osso
33     OSSO = True
34     osso_c = osso.Context("net.yerga.stockthis", "0.2", False)
35 except:
36     OSSO = False
37
38 from marketdata import markets, idmarket, localmarkets, localids
39
40 #TODO: detect if running in Fremantle
41 FREMANTLE=True
42
43 #detect if is ran locally or not
44 import sys
45 runningpath = sys.path[0]
46
47 if '/usr/share' in runningpath:
48     running_locally = False
49 else:
50     running_locally = True
51
52 if running_locally:
53     imgdir = 'pixmaps/'
54 else:
55     imgdir = '/usr/share/stockthis/pixmaps/'
56
57 loading_img = imgdir + 'loading.gif'
58
59 gtk.gdk.threads_init()
60
61 class StocksPy:
62
63     def __init__(self):
64         if HILDON:
65             self.program = hildon.Program()
66             self.program.__init__()
67             gtk.set_application_name('')
68             if FREMANTLE:
69                 self.window = hildon.StackableWindow()
70             else:
71                 self.window = hildon.Window()
72             self.program.add_window(self.window)
73         else:
74             self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
75
76         self.window.set_default_size(800, 480)
77         self.window.set_title('StockThis')
78         self.window.connect("destroy", gtk.main_quit)
79         self.window.connect("key-press-event", self.on_key_press)
80         self.window.connect("window-state-event", self.on_window_state_change)
81         self.window_in_fullscreen = False
82
83         if HILDON:
84             if FREMANTLE:
85                 menu = hildon.AppMenu()
86                 self.window.set_main_menu(menu)
87                 about_menu = gtk.Button("About")
88             else:
89                 menu = gtk.Menu()
90                 self.window.set_menu(menu)
91                 about_menu = gtk.MenuItem("About")
92                 about_menu.set_size_request(-1, 55)
93
94             about_menu.connect("activate", self.on_about)
95             menu.append(about_menu)
96             menu.show_all()
97         else:
98             #TODO: create a gtk.menubar
99             pass
100
101
102         vbox = gtk.VBox()
103
104         self.toolbar = gtk.HBox()
105         self.toolbar.set_property("no-show-all", True)
106         self.toolbar.hide()
107         self.toolbar.set_homogeneous(True)
108         self.toolbar.set_size_request(-1, 55)
109
110         self.markets_btn = gtk.Button('Markets')
111         self.markets_btn.connect("clicked", self.create_markets_view)
112         self.markets_btn.set_property("can_focus", False)
113
114         self.components_btn = gtk.Button('Companies')
115         self.components_btn.connect("clicked", self.show_components_view)
116         self.components_btn.set_property("can_focus", False)
117
118         self.graph_btn = gtk.Button('Graphs')
119         self.graph_btn.connect("clicked", self.create_graphs_view)
120         self.graph_btn.set_property("can_focus", False)
121
122         self.refresh_btn = gtk.Button('Refresh')
123         self.refresh_btn.connect("clicked", self.refresh_stock_data)
124         self.refresh_btn.set_property("can_focus", False)
125
126         self.quotes_btn = gtk.Button('Quotes')
127         self.quotes_btn.connect("clicked", self.show_quotes_view)
128         self.quotes_btn.set_property("can_focus", False)
129
130         self.toolbar.pack_start(self.markets_btn)
131         self.toolbar.pack_start(self.components_btn)
132         self.toolbar.pack_start(self.graph_btn)
133         self.toolbar.pack_start(self.quotes_btn)
134         self.toolbar.pack_start(self.refresh_btn)
135
136         self.mainbox = gtk.VBox()
137
138
139         if FREMANTLE:
140             self.swin = hildon.PannableArea()
141         else:
142             self.swin = gtk.ScrolledWindow()
143             if HILDON:
144                 hildon.hildon_helper_set_thumb_scrollbar(self.swin, True)
145             self.swin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
146         self.swin.add_with_viewport(self.mainbox)
147
148         vbox.pack_start(self.swin, True, True, 0)
149         vbox.pack_start(gtk.HSeparator(), False, False, 5)
150         vbox.pack_start(self.toolbar, False, False, 0)
151
152         self.create_markets_view(self.mainbox)
153         self.window.add(vbox)
154
155         self.window.show_all()
156
157     def create_markets_view(self, widget):
158         names = markets
159         ids = idmarket
160         self.toolbar.hide()
161
162         actual_view = self.mainbox.get_children()
163         if len(actual_view) > 0:
164             for a_widget in actual_view:
165                 a_widget.destroy()
166
167         self.marketsbox = gtk.VBox()
168         lnames = len(names)
169
170         for i in range(lnames):
171             button = gtk.Button(names[i])
172             button.connect("clicked", self.create_components_view, ids[i])
173             button.set_size_request(-1, 65)
174             button.set_property("can_focus", False)
175             self.marketsbox.pack_start(button, True, True, 2)
176
177         self.mainbox.pack_start(self.marketsbox, True, True, 2)
178         self.mainbox.show_all()
179
180     def show_components_view(self, widget):
181         kind = self.market_id
182         self.create_components_view(widget, kind)
183
184     def create_components_view(self, widget, kind):
185         actual_view = self.mainbox.get_children()
186         for i in actual_view:
187             i.destroy()
188
189         self.market_id = kind
190         self.toolbar.show()
191         self.components_btn.hide()
192         self.markets_btn.show()
193         self.refresh_btn.hide()
194         self.graph_btn.hide()
195         self.quotes_btn.hide()
196
197         names = localmarkets[idmarket.index(kind)]
198         ids = localids[idmarket.index(kind)]
199
200         self.compbox = gtk.VBox()
201
202         self.components_trv = gtk.TreeView()
203         self.components_trv.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_HORIZONTAL)
204
205         if not FREMANTLE:
206             selection = self.components_trv.get_selection()
207             selection.connect("changed", self.changed_selection, ids)
208         else:
209             self.components_trv.connect("row-activated", self.select_component, ids)
210
211         self.components_trv.set_rubber_banding(True)
212         self.components_trv.set_headers_visible(False)
213         self.components_model = self.__create_components_model()
214         self.components_trv.set_model(self.components_model)
215         self._components_trv_columns(self.components_trv)
216         self.add_initial_components(names, ids)
217
218         self.compbox.pack_start(self.components_trv, True, True, 0)
219
220         self.mainbox.pack_start(self.compbox, True, True, 0)
221         self.mainbox.show_all()
222
223     def select_component(self, widget, path, column, ids):
224         self.create_quotes_view(widget,self.components_model[path][1] )
225
226     def changed_selection(self, widget, ids):
227         n, i, m = self.get_selected_from_treeview(self.components_trv, self.components_model, 1)
228         if n is not None:
229             self.create_quotes_view(widget, n)
230
231     def __create_components_model(self):
232         lstore = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
233         return lstore
234
235     def _components_trv_columns(self, treeview):
236         renderer = gtk.CellRendererText()
237         renderer.set_property('scale', 1.6)
238         #renderer.set_property("background", 'lightgray')
239         renderer.set_property("xpad", 15)
240         column = gtk.TreeViewColumn('Name', renderer, text=0)
241         column.set_expand(True)
242         treeview.append_column(column)
243
244         renderer = gtk.CellRendererText()
245         column = gtk.TreeViewColumn('IDS', renderer, text=1)
246         column.set_visible(False)
247         treeview.append_column(column)
248
249     def add_initial_components(self, kind, ids):
250         for i in range(len(kind)):
251             niter = self.components_model.append()
252             self.components_model.set(niter, 0, kind[i], 1, ids[i])
253
254     def get_selected_from_treeview(self, treeview, model, setting):
255         selection = treeview.get_selection()
256         selected_model, selected_iter = selection.get_selected()
257         if selected_iter:
258             selected_name = model.get_value(selected_iter, setting)
259         else:
260             selected_name = None
261         return selected_name, selected_iter, selected_model
262
263     def show_quotes_view(self, widget):
264         kind = self.stocks_id
265         self.create_quotes_view(widget, kind)
266
267     def create_quotes_view(self, widget, kind):
268         self.stocks_id = kind
269         self.toolbar.show()
270         self.components_btn.show()
271         self.markets_btn.show()
272         self.refresh_btn.show()
273         self.graph_btn.show()
274         self.quotes_btn.hide()
275
276         #actual_view = self.mainbox.get_children()
277         #actual_view[0].destroy()
278
279         try:
280             self.graphbox.destroy()
281         except:
282             pass
283
284         for i in range(len(localids)):
285             if kind in localids[i]:
286                 ind1, ind2 = i, localids[i].index(kind)
287
288         self.quotesbox = gtk.VBox()
289
290         self.titlelbl = gtk.Label('')
291         self.titlelbl.set_markup('<b><big>'+localmarkets[ind1][ind2]+'</big></b>')
292         color = gtk.gdk.color_parse("#03A5FF")
293         self.titlelbl.modify_fg(gtk.STATE_NORMAL, color)
294
295         self.databox = gtk.VBox()
296
297         self.imagebox = gtk.VBox()
298         self.dataimg = gtk.Image()
299         self.imagebox.pack_start(self.dataimg)
300
301         self.show_data(kind)
302
303         hbox1 = gtk.HBox()
304
305         label2 = gtk.Label('')
306         label2.set_markup('<b><big>Price:</big></b>')
307         self.lprice = gtk.Label('')
308
309         hbox1.pack_start(label2, False, False, 50)
310         hbox1.pack_start(self.lprice, False, False, 185)
311
312         hbox2 = gtk.HBox()
313
314         label4 = gtk.Label('')
315         label4.set_markup('<b><big>Change:</big></b>')
316         self.lchange = gtk.Label('')
317         self.lpercent = gtk.Label('')
318
319         hbox2.pack_start(label4, False, False, 50)
320         hbox2.pack_start(self.lchange  , False, False, 145)
321         hbox2.pack_start(self.lpercent, False, False, 0)
322
323         hbox3 = gtk.HBox()
324
325         label7 = gtk.Label('')
326         label7.set_markup('<b><big>Volume:</big></b>')
327         self.lvolume = gtk.Label('')
328
329         hbox3.pack_start(label7, False, False, 50)
330         hbox3.pack_start(self.lvolume  , False, False, 145)
331
332         hbox4 = gtk.HBox()
333
334         label9 = gtk.Label('')
335         label9.set_markup('<b><big>52 week high:</big></b>')
336         self.l52whigh = gtk.Label('')
337
338         hbox4.pack_start(label9, False, False, 50)
339         hbox4.pack_start(self.l52whigh , False, False, 55)
340
341         hbox5 = gtk.HBox()
342
343         label11 = gtk.Label('')
344         label11.set_markup('<b><big>52 week low:</big></b>')
345         self.l52wlow = gtk.Label('')
346
347         hbox5.pack_start(label11, False, False, 50)
348         hbox5.pack_start(self.l52wlow , False, False, 70)
349
350         self.databox.pack_start(hbox1, True, True, 0)
351         self.databox.pack_start(hbox2, True, True, 0)
352         self.databox.pack_start(hbox3, True, True, 0)
353         self.databox.pack_start(hbox4, True, True, 0)
354         self.databox.pack_start(hbox5, True, True, 0)
355
356         self.quotesbox.pack_start(self.titlelbl, False, False, 0)
357         self.quotesbox.pack_start(gtk.HSeparator(), False, False, 0)
358         self.quotesbox.pack_start(self.databox, True, True, 0)
359         self.quotesbox.pack_start(self.imagebox, True, True, 0)
360
361         self.mainbox.pack_start(self.quotesbox, True, True, 0)
362         self.mainbox.show_all()
363         self.compbox.hide()
364         self.databox.hide()
365
366     def show_data(self, kind):
367         import thread
368         self.dataimg.set_from_file(loading_img)
369         self.imagebox.show()
370         self.databox.hide()
371         thread.start_new_thread(self.get_data, (kind,))
372
373     def get_data(self, kind):
374         self.graph_btn.show()
375         self.refresh_btn.show()
376         self.quotes_btn.hide()
377
378         from ystockquote import ystockquote as yt
379         try:
380             data = yt.get_all(kind)
381         except:
382             print 'Failed to get internet data'
383             data = {'price': 'N/A', 'change': 'N/A', 'volume':'N/A',
384                     '52_week_high': 'N/A', '52_week_low': 'N/A'}
385             self.titlelbl.set_markup('<b><big>Failed to get data</big></b>')
386
387         try:
388             ch_percent = 100.0 * float(data['change'])/float(data['price'])
389         except ValueError:
390             ch_percent = 0.0
391
392         self.lprice.set_label(data['price'])
393         self.lchange.set_label(data['change'])
394         self.lpercent.set_label('%6.2f %%' % ch_percent)
395
396         if '-' in data['change']:
397             color = gtk.gdk.color_parse("#FF0000")
398         else:
399             color = gtk.gdk.color_parse("#16EB78")
400
401         self.lpercent.modify_fg(gtk.STATE_NORMAL, color)
402         self.lchange.modify_fg(gtk.STATE_NORMAL, color)
403
404         self.lvolume.set_label(data['volume'])
405         self.l52whigh.set_label(data['52_week_high'])
406         self.l52wlow.set_label(data['52_week_low'])
407
408         self.databox.show_all()
409         self.imagebox.hide()
410
411     def refresh_stock_data(self, widget):
412         self.show_data(self.stocks_id)
413
414     def create_graphs_view(self, widget):
415         self.graph_btn.hide()
416         self.refresh_btn.hide()
417         self.quotes_btn.show()
418
419         self.graph = gtk.Image()
420
421         kind = self.stocks_id
422
423         self.show_graph(None, '1d', kind)
424
425         for i in range(len(localids)):
426             if kind in localids[i]:
427                 ind1, ind2 = i, localids[i].index(kind)
428
429         #self.mainbox.destroy()
430         #self.mainbox = gtk.VBox()
431         #self.swin.add_with_viewport(self.mainbox)
432
433         actual_view = self.mainbox.get_children()
434         for a_widget in actual_view:
435             a_widget.destroy()
436
437         self.graphbox = gtk.VBox()
438
439         self.graphs_title = gtk.Label(localmarkets[ind1][ind2])
440         color = gtk.gdk.color_parse("#03A5FF")
441         self.graphs_title.modify_fg(gtk.STATE_NORMAL, color)
442
443         hbox1 = gtk.HBox()
444         hbox1.set_size_request(-1, 55)
445         hbox1.set_homogeneous(True)
446
447         self.btn1d = gtk.Button('1d')
448         self.btn1d.set_property("can_focus", False)
449         self.btn1d.connect("clicked", self.show_graph, '1d', kind)
450         self.btn5d = gtk.Button('5d')
451         self.btn5d.set_property("can_focus", False)
452         self.btn5d.connect("clicked", self.show_graph, '5d', kind)
453         self.btn3m = gtk.Button('3m')
454         self.btn3m.set_property("can_focus", False)
455         self.btn3m.connect("clicked", self.show_graph, '3m', kind)
456         self.btn6m = gtk.Button('6m')
457         self.btn6m.set_property("can_focus", False)
458         self.btn6m.connect("clicked", self.show_graph, '6m', kind)
459         self.btn1y = gtk.Button('1y')
460         self.btn1y.set_property("can_focus", False)
461         self.btn1y.connect("clicked", self.show_graph, '1y', kind)
462         self.btn2y = gtk.Button('2y')
463         self.btn2y.set_property("can_focus", False)
464         self.btn2y.connect("clicked", self.show_graph, '2y', kind)
465         self.btn5y = gtk.Button('5y')
466         self.btn5y.set_property("can_focus", False)
467         self.btn5y.connect("clicked", self.show_graph, '5y', kind)
468         self.btnmax = gtk.Button('max')
469         self.btnmax.set_property("can_focus", False)
470         self.btnmax.connect("clicked", self.show_graph, 'max', kind)
471
472         hbox1.pack_start(self.btn1d)
473         hbox1.pack_start(self.btn5d)
474         hbox1.pack_start(self.btn3m)
475         hbox1.pack_start(self.btn6m)
476         hbox1.pack_start(self.btn1y)
477         hbox1.pack_start(self.btn2y)
478         hbox1.pack_start(self.btn5y)
479         hbox1.pack_start(self.btnmax)
480
481         self.graphbox.pack_start(self.graphs_title, False, False, 2)
482         self.graphbox.pack_start(hbox1, False, False, 0)
483         self.graphbox.pack_start(self.graph, True, True, 5)
484
485         self.mainbox.pack_start(self.graphbox, False, False, 2)
486         self.mainbox.show_all()
487
488     def show_graph(self, widget, option, kind):
489         import thread
490         self.graph.set_from_file(loading_img)
491         thread.start_new_thread(self.get_graph_data, (option, kind))
492
493     def get_graph_data(self, option, kind):
494         if option == '1d':
495             url = 'http://uk.ichart.yahoo.com/b?s=%s' % kind
496         elif option == '5d':
497             url = 'http://uk.ichart.yahoo.com/w?s=%s' % kind
498         elif option == '3m':
499             url = 'http://chart.finance.yahoo.com/c/3m/s/%s' % kind.lower()
500         elif option == '6m':
501             url = 'http://chart.finance.yahoo.com/c/6m/s/%s' % kind.lower()
502         elif option == '1y':
503             url = 'http://chart.finance.yahoo.com/c/1y/s/%s' % kind.lower()
504         elif option == '2y':
505             url = 'http://chart.finance.yahoo.com/c/2y/s/%s' % kind.lower()
506         elif option == '5y':
507             url = 'http://chart.finance.yahoo.com/c/5y/s/%s' % kind.lower()
508         elif option == 'max':
509             url = 'http://chart.finance.yahoo.com/c/my/s/%s' % kind.lower()
510
511         try:
512             myimg = urllib2.urlopen(url)
513             imgdata=myimg.read()
514
515             pbl = gtk.gdk.PixbufLoader()
516             pbl.write(imgdata)
517
518             pbuf = pbl.get_pixbuf()
519             pbl.close()
520             self.graph.set_from_pixbuf(pbuf)
521         except:
522             print 'no internet data'
523             self.graphs_title.set_label('Failed to get data')
524             self.graph.destroy()
525
526
527     #Functions for fullscreen
528     def on_window_state_change(self, widget, event, *args):
529         if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
530             self.window_in_fullscreen = True
531         else:
532             self.window_in_fullscreen = False
533
534     #F6 fullscreen, F7 bigger font, F8 smaller font
535     def on_key_press(self, widget, event, *args):
536         if event.keyval == gtk.keysyms.F6:
537             if self.window_in_fullscreen:
538                 self.window.unfullscreen ()
539             else:
540                 self.window.fullscreen ()
541
542     def on_about(self, widget):
543         dialog = gtk.AboutDialog()
544         dialog.set_name("StockThis")
545         dialog.set_version("0.2")
546         dialog.set_copyright("Copyright © 2009")
547         dialog.set_website("http://stockthis.garage.maemo.org")
548         dialog.set_authors(["Daniel Martin Yerga <dyerga@gmail.com>"])
549         logo = gtk.gdk.pixbuf_new_from_file(imgdir + "stockthis.png")
550         dialog.set_logo(logo)
551         dialog.set_license("This program is released under the GNU\nGeneral Public License. Please visit \nhttp://www.gnu.org/copyleft/gpl.html\nfor details.")
552         dialog.set_artists(["Logo by Daniel Martin Yerga"])
553         dialog.run()
554         dialog.destroy()
555
556 if __name__ == "__main__":
557     stockspy = StocksPy()
558     gtk.gdk.threads_enter()
559     gtk.main()
560     gtk.gdk.threads_leave()