Stock Quotes on your Desktop with Conky


I wrote another script today to save me from needing to open up a browser.
The old process for stock quotes was, go to yahoo, type in each stock, get the price.
The new process involves only directing my attention to the bottom right corner of my desktop. All stocks of interest are lined up inside my conky. They auto refresh every 2 minutes for me. I can see the current value, what it opened at, and the change.

If you don’t know what conky is click here for my conky tutorial.

To get it working, download the script and add the following line to your .conkyrc

${execi 120 python /path/to/script/stocks.py stock1 stock2 stock3}

Replace 120 with your interval, use your path to the script, and change the stocks to actual stock quotes.
Example:

{execi 120 python /home/bhavik/scripts/stocks.py goog msft aapl}

Hope it helps any of the linux users out there that also like to trade =)

Changes:
3/5/09 – Removed decimal conversion to float…
If the market was closed the value was N/A.
Since you can’t convert a string to float it was getting errors.
Should be good now.

Screenshot
conky_stocks_screenshot
Download Stocks.py Here (Right click and Save link as…)

  1. #1 by p.daniels on April 12, 2009 - 10:30 am

    Hi there, good script, just what I was looking for! One problem: when I supply multiple arguments, only the last one prints. Any advice on this?

    thx again-
    pete

  2. #2 by Bhavik on April 12, 2009 - 1:30 pm

    Hey man,
    Thats weird, its workin fine for me. Which stocks are you supplying? Can you show me the execi line thats in your conkyrc?

    Thanks

  3. #3 by p.daniels on April 13, 2009 - 12:30 pm

    Here’s my execi:
    ${execi 1800 python /home/me/src/conky_stocks.py goog ibm java msft rht}

    I did comment out the Else statement at the bottom, because it was crapping out on me with a syntax error before:

    $ python ~/src/conky_stocks.py goog rht
    File “/home/me/src/conky_stocks.py”, line 42
    else:
    ^
    SyntaxError: invalid syntax

    Surely displaying my ignorance here, but I don’t know whether that could have anything to do with this or not…

    thx-
    pete

  4. #4 by Bhavik on April 13, 2009 - 12:44 pm

    I can’t seem to re-create your error… I have the same line in my conky and it all works fine

    bhavik@BhaviksXPS:~/scripts$ python stocks.py goog ibm java msft rht
     Name    Value      Open    Change      Time
    --------------------------------------------
     GOOG   378.22    371.33     +5.72    3:25pm
      IBM 100.1024    100.28   -1.5976    3:25pm
     JAVA   6.4304      6.51   -0.2496    3:25pm
     MSFT    19.68     19.65     +0.01    3:25pm
      RHT    18.89     18.99     -0.11    3:25pm

    Do you have the latest version of the script? You shouldn’t be getting any errors. Did you edit the script? I’m stumped buddy, its working fine over here. Let me know

  5. #5 by p.daniels on April 13, 2009 - 1:36 pm

    Huh. I actually saved your file instead of cut and pasting it, and now it works perfectly. Something screwy must have been going on in the formatting. Thanks for your help, sorry it turned out to be a false alarm :)

    -pete

    • #6 by Bhavik on April 13, 2009 - 4:32 pm

      Hey man, no problem…I’m glad you got it to work.

  6. #7 by wiejak on April 25, 2009 - 2:03 am

    hello, great script – but can You help mi with formating ?

    as You see it all mixed up – on Your screen everything is nice aligned.

    [URL=http://img220.imageshack.us/my.php?image=zrzutekranuw.png][IMG]http://img220.imageshack.us/img220/3729/zrzutekranuw.th.png[/IMG][/URL]

    http://img220.imageshack.us/my.....kranuw.png

  7. #8 by Bhavik on April 27, 2009 - 11:40 am

    Hey Wiejak,
    You can try and make your conky wider, that could give it more space to output the text.
    In .conkyrc set this to a higher number

    maximum_width

    If that doesn’t work post back and i’ll try something else.

    • #9 by darian on May 26, 2010 - 2:25 pm

      Hi Bhavik!

      What a usefull script! I do have the same problem as wiejak though. I tried adjusting the maximum_width, sadly to no avail. It would be great if you could help me out on this one!

      Btw: I complemented your script with percentage changes:

      num = float(tokens[4])
      num2 = float(tokens[1])
      change = round((num/num2)*100, 2)

      Thanks mate, have a nice day!

  8. #10 by Douglas on May 12, 2009 - 10:29 pm

    Hey,

    Very nice script.
    I would like to know if its possible to put all the variables that is present on the Invest api for Gnome Panel.
    There I can put things like “How many stocks I have” and them it calculates the gain or loss.

    • #11 by Bhavik on May 13, 2009 - 11:09 am

      Hey Douglas, Thanks! That’s a nice idea you have there. I’ll see what I can come up with, any other features you’d like to see?

  9. #12 by Douglas on May 13, 2009 - 11:17 am

    Hi Bhavik,

    Thanks for the reply.
    Well, for me will be just great only the features on the Invest api.
    Stock | Last quote (actual value) | % | Gain/Loss | Gain/Loss %

    % = difference between actual quote and yesterday quote

    Then we just need to define the stocks and how much we have. Example:

    ${execi 120 python /path/to/script/stocks.py quote1 stock1 price1 quote2 stock2 price2}

    Meaning:
    quote1: GOOG
    stock1: how much I have (50)
    price1: how much I paid for (300,00)

    Then the program will be able to calculate, based on todays price, how much money I did.

    • #13 by Bhavik on May 13, 2009 - 2:19 pm

      Its definitely a great idea. I’ll be busy until this weekend, hopefully I’ll get a chance to work on it next week. Keep checking back! Thanks again!

  10. #14 by Calum on August 27, 2009 - 7:56 pm

    I know this is a little old but I wanted this to show my profit or loss of each stock like Douglas did so I changed the script a little to accept either just the stock symbol or ‘stock_symbol:bought_price:quantity’. It was just a quick and dirty change:

    # Author: Bhavik Shah
    # Date Created: Feb 27th, 2009
    # Description: Pulls stock quotes from yahoo finance
    # and displays them in conky

    # Open up .conkyrc and add the following line
    # {execi 120 /path/to/your/script.py goog xom}
    # replace 120 by your desired interval in seconds
    # replace the path with your path
    # Change goog and xom to the stocks you want
    # Optional input is stock_symbol:bought_price:quantity to show profit or loss
    # If Value is N/A you probably typed the quote in wrong
    # If Open is N/A the stock market is probably closed

    # Script is free, do whatever you want with it
    # Credit to http://www.bhaviksblog.com is appreciated =)

    import urllib2
    import sys

    if sys.argv > 1: #arg must be supplied
    stocks = sys.argv #args are the stocks
    stocks.pop(0) #pop the first entry since its the filename
    print
    print ‘%5s %10s %10s %9s %9s %9s’ % (‘Name’,'Profit’,'Value’,'Open’,'Change’,'Time’) #print header
    print ‘———————————————————’ #fancy line

    for i in stocks: #for each stock do this
    k=i.split(‘:’) #optional input is stock_symbol:bought_price:quantity
    stock=k[0]

    #This is the url from yahoo…if this changes the script dies, Ill fix it and upload again if it happens.
    csv = urllib2.urlopen(‘http://download.finance.yahoo......v?s='+ stock +’&f=sl1d1t1c1ohgv&e=.csv’)
    data = csv.read() #grab csv
    tokens = data.split(‘,’) #split into tokens

    name=tokens[0].replace(‘”‘,”) #get rid of quotes
    value=tokens[1]
    time=tokens[3].replace(‘”‘,”)
    change=tokens[4]
    openVal=tokens[5]

    if len(k) > 2: #if there are bought price and quantity terms compute profit or loss
    gain=’$’ + str(round((float(k[2]) * float(value)) – (float(k[2]) * float(k[1])),2))
    else:
    gain=’N/A’

    print ‘%5s’ % name,’%10s’ % gain,’%10s’% value,’%9s’% openVal,’%9s’% change,’%9s’% time #print to screen with formatting
    else:
    print ‘You forgot to supply your stock quote as an arg’ #go back and give the script your stocks as arguments
    print ‘Example: python stocks.py goog’

    • #15 by Bhavik on September 24, 2009 - 11:09 pm

      Calum you’re the man! This is very cool, thanks a lot for the addition!

  11. #16 by Will on September 20, 2009 - 3:40 pm

    Hey,

    Thanks for the great script. I’m also having trouble with alignment issues just like wiejak where all of the values are not lining up. I tried to increase the size of it but it still doesn’t seem to line up. Can you please help me? I’m not using Ubuntu like you though, I’m using opensuse 11.1.

    Thanks for the help.

    • #17 by Bhavik on September 24, 2009 - 11:09 pm

      Hey Will,
      You cant try playing with the print line. The spacing is done with ‘%5s’ etc. Changing the 5 to a higher number would shift it farther to the right. Gl!

  12. #18 by Simon on November 12, 2009 - 9:32 am

    Hi,
    I’ve made a slight change to the feed line so that the script can now support UK shares:
    - csv = urllib2.urlopen(’http://download.finance.yahoo.com/d/quotes.csv?s=’+ stock +’&f=sl1d1t1c1ohgv&e=.csv’)
    + csv = urllib2.urlopen(‘http://uk.finance.yahoo.com/d/quotes.csv?s='+ stock +’&f=sl1d1t1c1ohgv&e=.csv’)

  13. #19 by Ciaran on January 26, 2010 - 9:05 am

    Very nice little script. Would be great if it was in some little repository somewhere where one could submit updates.

    Nice job though!

  14. #20 by aqua on February 23, 2010 - 4:51 am

    hi, great script!!!
    but i would ask you if there is a setting for getting the “right” time, because i live in Italy and I got the wrong time displayed

    thanks :)

    • #21 by Ciaran on March 5, 2010 - 5:03 pm

      Hey, I rearranged some stuff, and made the script a little more efficient by only connecting to Yahoo once to retrieve all stocks, then loop through them. I’m also using the UK url. Hope it’s useful.

      import urllib2
      import os
      import sys

      OUTPUT_FORMAT = ‘%-8s %-6s %-6s %-6s %-7s %-10s’

      def main():
      if len(sys.argv) > 1:
      print OUTPUT_FORMAT % (‘Name’,'Value’,'Open’,'Change’,'Time’, ‘Date’)
      stck_str = ‘+’.join(sys.argv[1:])
      try:
      csv = urllib2.urlopen(
      http://uk.old.finance.yahoo.com/
      ‘d/quotes.csv?s=%s&f=sl1d1t1c1ohgv&e=.csv’ % stck_str)
      except urllib2.URLError, err:
      print ‘Error getting data from Yahoo.’
      sys.exit(1)
      data = csv.readlines()

      for line in data:
      cells = line.replace(‘ ‘, ”).replace(‘N/A,’, ”).split(‘,’)

      name, value, time, date, change, open_val = cells[0:6]
      print OUTPUT_FORMAT % (name, value, open_val, change, time, date)
      else:
      print ‘You forgot to supply your stock quote as an arg’
      print ‘Example: python stocks.py goog’

      if __name__ == ‘__main__’:
      main()

  15. #22 by Pedro on May 11, 2010 - 7:24 am

    Dear, on my computer return this error.

    /etc/conky$ python stocks.py CAKE

    Name Value Open Change Time
    ——————————————–
    Traceback (most recent call last):
    File “stocks.py”, line 31, in
    csv = urllib2.urlopen(‘http://download.finance.yahoo......v?s='+ stock +’&f=sl1d1t1c1ohgv&e=.csv’)
    File “/usr/lib/python2.6/urllib2.py”, line 126, in urlopen
    return _opener.open(url, data, timeout)
    File “/usr/lib/python2.6/urllib2.py”, line 391, in open
    response = self._open(req, data)
    File “/usr/lib/python2.6/urllib2.py”, line 409, in _open
    ‘_open’, req)
    File “/usr/lib/python2.6/urllib2.py”, line 369, in _call_chain
    result = func(*args)
    File “/usr/lib/python2.6/urllib2.py”, line 1161, in http_open
    return self.do_open(httplib.HTTPConnection, req)
    File “/usr/lib/python2.6/urllib2.py”, line 1136, in do_open
    raise URLError(err)
    urllib2.URLError:

    anyone know what happens?

    thx

    • #23 by Pedro on May 11, 2010 - 7:39 am

      On SUDO this work….

  16. #24 by Duplication on July 6, 2010 - 5:03 am

    Interesting developments guy. Good work!

  17. #25 by shapeshifter on July 27, 2010 - 6:32 pm

    Hi Bhavik great script. One thing.

    I have about 7 or 8 stocks, but the script only displays 5. I tried playing with Conky width etc and looking at your stocks.py, but couldn’t change.

    Many thanks

    P

  18. #26 by Evan Beidler on November 29, 2010 - 6:58 pm

    Hello, firstly, I would like to let you know that I think it’s a superb website you have got here. What I wanted to ask is, I haven’t figured out the way to add your site rss or atom in my feed subscriber, where’s the link for the RSS? Thanks

  19. #27 by Hal on March 21, 2011 - 11:46 am

    there is a problem with this script,
    when executed from shell it works fine
    however when added to conky it
    has a limit on how many lines it can display,
    depending one how much space it takes in
    conky…

    the problem is reported above: for some ppl
    it will be 3 lines, for some 5 for some 7
    on my conky it only displays 4+1/2 lines

    if i remove ————- line below
    the header then i can get one extra line
    in there and add one more stock

    basically I think it has to do with max
    number of characters conky can print in one
    shot, all lines in this script starting from
    first letter of header down to the last char
    is probably treated as one line…
    so if this conky max is exceded the rest is
    simply truncated… thata’s why i get 4+1/2 lines

    Bhavik, it’s a nice script, is there anyway
    it could look into it and fix it…

    try 5,8,13,21 symbols, but don’t try it in
    shell but in conky… you will hit the limit
    and you can replicate it this way

    thanks!
    Hal.

  20. #28 by Hal on March 21, 2011 - 11:57 am

    ps.
    ps. also it would be nice if stock that is up ( positive change ) could be colored green
    and stock that is down could be colored red

    futures and index symbols work as well:

    INDU – dow industrial index
    ^GSPC – sp500 index
    ^IXIC – Naz
    ^TNX – 10Y NOTE yield
    ^VIX – volatility index
    DX-Y.NYB – dollar index
    EURUSD=X – euro
    as well as futures contracts for oil and gold ( lookup symbols on yahoo finance )
    foreign indicies also work fine.

    Google finance feed is better for stocks because it’s real time and free,
    but gf does not provide real time data for futures or indicies
    it would be nice to add the google finance as a feed in this script

    *********************
    after all these changes this script i think would need to be added
    to official conky website as an example or conky-colors, it’s a nice script
    for those that track markets !

  21. #29 by Example This on April 23, 2011 - 10:51 am

    this blog is boring

  22. #30 by GAMEFLAVOR on May 10, 2011 - 1:40 am

    Hi,
    Great script. Just that the stock rows are limited to 5. How can I display more rows?

    Thanks

Comments are closed.