Google

Thursday, January 04, 2007

Online Stock Quotes - Using Python S60


I recently came across an article about a service provided by the Yahoo! finance website, which return details about stock quotes in comma separated values (CSVs). Many folks have used this service in their programs to display (almost) real time stock data. Of course, I had to make my phone do the same :) As we will see, Python makes it look easy - no, Python makes it look GOOD!

Background

The Yahoo! finance service http://quote.yahoo.com/d/quotes.csv is a very simple yet powerful service. The user can control the fields in the stock quote data through a format string. The return data contains stock data fields in CSV format. The fields and their order is based on the format string. This is another example of the usage of this service.

Cache Management

The application on the phone should minimize the network traffic. However, care should be taken that the data is updated as frequently as possible to keep the real-time nature of the data. To achieve this, there is a very rudimentary cache management technique implemented in the module. The cache management checks how old the stock data is and if it is older than a certain expiry. The network traffic is generated only if the data is expired.

Chart

This module also allows downloading the chart for a given symbol. The chart is downloaded from yet another Yahoo! finance service http://ichart.finance.yahoo.com/t The response of this service is a intra-day chart for the latest day. If a chart exists, the response is of type image/png. This can be used as a test.

Implementation

The following code snippet is from the quotes.py module. This piece works well on 3rd edition phones:
# These times should be set to minimize the network traffic
QUOTEEXPIRY = 60 # 1 Minute
CHARTEXPIRY = 300 # 5 Minutes
CACHEDIR = 'c:\\cache\\'

# If the file does not exist or if the creation time of the
# existing file is older than expiry, then return True
def is_expired(filename, expiry):
    expired = False
    if not os.path.exists(filename):
        expired = True
    else:
        lastmod = os.stat(filename)[ST_MTIME]
        currtime = int(time.time())
        if currtime > lastmod + expiry:
            expired = True
    return expired

# This function downloads the chart for a given symbol
# If the symbol does not have a chart, the function returns
# False, else returns True
def get_chart(symbol):
    retval = True
    filename = CACHEDIR+symbol.upper()+'chart.png'
    if is_expired(filename, CHARTEXPIRY):
        name, status = urllib.urlretrieve('http://ichart.finance.yahoo.com/t?s='+symbol.upper(), filename)
        if status.type != 'image/png':
            retval = False
            os.remove(filename)
    return retval

# Get the CSV from yahoo server and return parsed values
# Format is known and hence the cryptic retval parsing
def get_quote(symbol):
    filename = CACHEDIR+symbol.upper()+'quote.txt'
    if is_expired(filename, QUOTEEXPIRY):
        urllib.urlretrieve('http://quote.yahoo.com/d/quotes.csv?s='+symbol.upper()+'&d=t&f=sl1d1t1c1ohgvj1pp2xwenr', filename)
    f = file(filename)
    data = f.read()
    f.close()
    names = ['sym', 'last', 'date', 'curtime', 'change', 'open', 'high',
             'low', 'vol', 'mcap', 'close', 'pctchg', 'exchange', 'annrange',
             'earnings', 'name', 'peratio']
    values = map(lambda s: s.strip('"'), data.split('\n')[0].split(','))
    return dict(zip(names, values))

The meaning of the format string can be found from the correspondance between the string and the names array.

The complete implementation is located here

Summary

This log is yet another example of power and elegance of Python. The way zip() function simplifies creation of a very usable dictionary out of an array.

46 Comments:

Blogger Unknown said...

You've built quite a useful stock quote tool there! I was wondering however if you could build a similar tool but for funny and intelligent quotes by famous people. If there aren't simple lists of such on the internet I imagine including a text file shouldnt be to hard (individual users could update them themselves!) Oh and to make it perfect, could it also function as a 'screensaver' on standby.. ;D Cheers! And keep up that enthusiasm and good work!!
-Mido

6:08 PM  
Anonymous Anonymous said...

Dear Author geekyprojects.blogspot.com !
You commit an error. I can prove it. Write to me in PM, we will communicate.

10:52 PM  
Anonymous Anonymous said...

Free pills avandamet Drug prednisone Without prescription triphala Get floxin Visa/Mastercard/Amex/eCheck prandin Discount retrovir

2:14 PM  
Anonymous Anonymous said...

This site/article is about giving you an in-depth view of all there is to know about proactol. Remember the days when someone would mention proactol reviews and the usual reaction was huh? Now get rid of all your worries about getting answers to questions you have about proactol discount. We've done your work for you and it's all here, ready for the reading.

12:11 AM  
Anonymous shyam advisory free trial said...

There are so many options and so many markets that there's no way to simplify or systemize investment trading without blowing a brain gasket.
shyam advisory free trial

9:43 PM  
Anonymous Anonymous said...

when is clomid prescribed | buy clomid without prescription uk - how to buy clomid, ovulation after clomid days 5 9

8:46 AM  
Anonymous Anonymous said...

when do you start clomid | price of clomid without insurance - buy generic clomid, 150mg clomid success stories

4:25 AM  
Anonymous Anonymous said...

how long can you be on clomid | http://cheapclomidonline.jimdo.com/#23358 - clomid tablet, does clomid stop your period

12:50 PM  
Anonymous Anonymous said...

clomid for men success rates | [url=http://buycheapclomid.webs.com/#27347]buy clomid without prescriptions uk[/url] - clomid online pharmacy, atet fertility options after clomid

3:55 AM  
Anonymous Anonymous said...

best days to take clomid | where can i buy clomid over the counter - clomid 25 mg, how to take clomid 50mg

3:13 AM  
Anonymous Anonymous said...

how to take clomid to get pregnant | http://buy-clomid-in-usa.webs.com/#95908 - purchase clomid online, clomid dosage pct

12:20 PM  
Anonymous Anonymous said...

can i take clomid if i already ovulate | [url=http://buycheapclomid.jimdo.com/#68119]clomid buy online no prescription[/url] - buy clomid without a prescription, yhow clomid interactions

2:26 AM  
Anonymous Anonymous said...

[url=http://loveepicentre.com/faq.php][img]http://loveepicentre.com/uploades/photos/9.jpg[/img][/url]
miranda cosgrove dating david archuleta [url=http://loveepicentre.com/articles.php]free dating online maine[/url] singles music dating
dating step sister [url=http://loveepicentre.com/map.php]gym rat dating[/url] 100 free online dating gay
online dating love free site [url=http://loveepicentre.com/testimonials.php]dating service mpls mn[/url] ebony lesbian dating

7:23 AM  
Anonymous Anonymous said...

how much clomid to take after cycle | http://buyclomidcheap.webs.com/#33160 - buy clomid nolvadex, how to take clomid for twins

2:32 AM  
Anonymous Anonymous said...

clomid wiki | [url=http://purchaseclomid.jimdo.com/#31735]clomid tablet[/url] - generic clomid at walmart, gcii when do clomid side effects occur

2:55 AM  
Anonymous Anonymous said...

[url=http://loveepicentre.com/advice.php][img]http://loveepicentre.com/uploades/photos/5.jpg[/img][/url]
dating hoax o [url=http://loveepicentre.com/]advice when dating a indian man[/url] magazine dating tips
kids sim dating games [url=http://loveepicentre.com/testimonials.php]free italian dating site[/url] nude dating for russian
testimony college dating [url=http://loveepicentre.com/]dating acronym gu[/url] dating in century village

11:04 PM  
Anonymous Anonymous said...

clomid 50mg twins | how much does clomid cost without insurance - clomid buy no prescription, chances of twins with clomid

6:43 AM  
Anonymous Anonymous said...

does clomid cause cysts | [url=http://ordergenericclomid.webs.com/#17389]ordering clomid online safe[/url] - buying clomid, juok clomid pregnant first cycle

1:44 PM  
Anonymous Anonymous said...

I'm not sure where you're getting your information, but great topic.
I needs to spend some time learning much more or understanding more.
Thanks for excellent info I was looking for this information for my mission.


my homepage - herbal supplement myths

8:16 PM  
Anonymous Anonymous said...

Hmm it seems like your website ate my first comment (it was extremely long) so
I guess I'll just sum it up what I had written and say, I'm thoroughly
enjoying your blog. I too am an aspiring blog writer but I'm still new to everything. Do you have any suggestions for rookie blog writers? I'd certainly appreciate it.


my homepage search engines
My web page > engines optimization seo

10:37 PM  
Anonymous Anonymous said...

Having read this I believed it was really informative.
I appreciate you finding the time and effort to put this article together.
I once again find myself personally spending
a lot of time both reading and commenting. But so what, it was still worth it!



Take a look at my web page :: seo link building
My web page > sponsored links

4:10 AM  
Anonymous Anonymous said...

I read this paragraph completely regarding the resemblance
of latest and previous technologies, it's awesome article.

Visit my weblog ... deaf-worlds.com

2:25 PM  
Anonymous Anonymous said...

Woah! I'm really loving the template/theme of this blog. It's simple,
yet effective. A lot of times it's challenging to get that "perfect balance" between usability and visual appeal. I must say you have done a great job with this. Also, the blog loads very fast for me on Safari. Outstanding Blog!

Review my web-site disability insurance
Also see my webpage - http://ecosy.vn/index.php?do=/blog/1423/picking-trouble-free-plans-of-insurance-tips

1:32 AM  
Anonymous Anonymous said...

Hey there, I think your website might be having browser compatibility issues.
When I look at your blog site in Safari, it looks fine but when
opening in Internet Explorer, it has some overlapping.

I just wanted to give you a quick heads up! Other then that, great
blog!

Also visit my weblog :: make money at home online

7:36 AM  
Anonymous Anonymous said...

whoah this blog is magnificent i love studying your posts.

Keep up the great work! You already know, many individuals are hunting
round for this information, you can aid them greatly.



Here is my homepage - smoking hypnosis rates

10:02 AM  
Anonymous Anonymous said...

Excellent blog here! Also your web site loads up very fast!
What web host are you using? Can I get your affiliate link to
your host? I wish my website loaded up as quickly as yours lol

Here is my website :: online marketing

6:18 PM  
Anonymous Anonymous said...

It is perfect time to make some plans for the longer term and it is time to be happy.
I've learn this post and if I could I wish to counsel you few attention-grabbing things or advice. Perhaps you could write next articles relating to this article. I wish to read more things about it!

my web blog wiki.mlee.de

6:35 PM  
Anonymous Anonymous said...

Thanks for the auspicious writeup. It actually was once a amusement account it.
Look advanced to far brought agreeable from you!
By the way, how could we keep up a correspondence?



Here is my webpage how to convince someone to stop smoking
Also see my web page > cdpcitiesmap2011.com

7:01 PM  
Anonymous Anonymous said...

I go to see day-to-day a few blogs and sites to read
content, however this website provides quality based articles.


My web-site - stop smoking hypnosis
my webpage: how to convince someone to quit smoking

9:52 AM  
Anonymous Anonymous said...

This is a thing to adopt into mind when you need crisis cash and they're able to assist your credit standing continue being intact payday Loans once copies of pay slips and your identity continues to be verified you happen to be able to go shopping for your new car.

9:25 PM  
Anonymous Anonymous said...

I've been surfing on-line greater than 3 hours nowadays, but I never discovered any interesting article like yours. It's pretty value enough for me.
Personally, if all web owners and bloggers made excellent content as you probably did, the
web will likely be a lot more helpful than ever before.


Review my site - business records
my site - www.apparelcycle.com

2:39 AM  
Anonymous Anonymous said...

You're so cool! I do not think I have read through something like that before. So great to discover someone with unique thoughts on this subject. Really.. thank you for starting this up. This site is something that is required on the web, someone with a bit of originality!

Also visit my weblog :: business checks

5:49 AM  
Anonymous Anonymous said...

My partner and I stumbled over here from a different website and thought I might as well check things out.
I like what I see so now i am following you. Look forward
to looking over your web page repeatedly.

my blog: order checks online

5:13 AM  
Anonymous Anonymous said...

Hello! I've been reading your web site for a long time now and finally got the courage to go ahead and give you a shout out from Huffman Tx! Just wanted to tell you keep up the great work!

my homepage :: http://esponjadelufa.com

6:58 AM  
Anonymous Anonymous said...

Appreciate the recommendation. Let me try it out.

my web blog ... best coffee makers

8:39 PM  
Anonymous Anonymous said...

What's up, this weekend is nice designed for me, for the reason that this time i am reading this fantastic informative article here at my residence.

Also visit my weblog - coffee machines

9:50 PM  
Anonymous Anonymous said...

Hello, yes this piece of writing is actually
nice and I have learned lot of things from it on the topic of blogging.
thanks.

my homepage - Calendula-Zeitung.De

1:46 AM  
Anonymous Anonymous said...

Yes! Finally something about clothing tips.

Here is my blog post; http://www.moremead.com/the-right-way-to-design-your-own-clothes-online/

1:47 AM  
Anonymous Anonymous said...

Ones cгedit conсerns liκе IVАs,
CСJs, chaрter 7, dеfault or any
οthег baԁ crеdit rеcοrd ωill not ԁisqualifу νia
аpplуing hеrе Chаnces are lіkelу you ωоn't obtain anyone practically so intimidating--unless you wish that, naturally But, by making competitive investigating online collecting economic issue you could possibly be encountering As they are short-term in nature you should repay just how much within the very limited time frame The C-17 Responsibility Day calculator is designed to help military workers know their duty day limitations It is because the bad credit holders when the whole and has the ultimate needing to demotion, job damage, injury, crash, divorce and so on Same day loans Doing just one fee is far easier than building many to unsecured in regular expenses right up until your next paycheck come into your bank account Individuals who use this method will want to ensure that the lender is but one who will record the payments to the credit reporting businesses Some of them could deal with creditworthiness (PLUS financial products for manages to graduate and parents) and possible borrowers is going to pass or not credit check Nevertheless another thing which each one of you start looking as soon as we think on the buying a automobile is car loans Cells I11up for you to I33 will simply undertake the tip by doing the same process of dragging around the 'paгеnt-formula' found in Cellular I10 Quite a few lenders appearance their company's it tгuly
iѕ a bad сrеdit score militarу bank loаn
In your birthdаy unit card, уou саn сreate humοгous versеs, or simplу wiѕh a
contentеd birthԁaу сelebrаtion One timе ωoгk
wіll bеgin comіng in, it аѕѕists to spend a сοuρlе of minutes aftег eveгy daу tο
be аble to tidy up the οfficе Debt consоlidation is thе prοcedureѕ foг hanԁling νеrу big financiаl prоԁuсts or lоans that you are unablе to pay off ΝАCA cautionѕ propеrty owners who enroll іn its gatheгіngѕ
that moѕt rаteѕ and teгms for pеrsоnаl loаns without hаving ѕeсuritу Hоwever, loω соst ѕecureԁ loans can often
cоnsolidаte obligations and pay the outstandіng ρayments The customeг
is rеquігed to fulfіll the eligіbility disorders
as proviԁed by the lendег Most faѕt caѕh busіnesѕes remoνe thе fax of fіles in thеiг range οf requiгеmеnts
to aрply for οnline іnstant cаsh Βefore making in
additiοn to ρuttіng auto ѕo thеу cаn youг chοіces for
peoplе with a favоrable сredit record ѕсorеs Thеse kіnԁs of private finаncial
ρroducts are ѕometimеs ѕupplіed not on the cоrnerstone οf finanсial
supροгt, but within the suρpοsitіon of one's credit history

my homepage :: http://Www.Badcreditloans180.Co.uk

11:25 AM  
Anonymous Anonymous said...

If you are interested in how to get pregnant after tubal ligation, it is the place to go! However, one shouldn't consider that she cannot get pregnant on any other days of the menstrual cycle. Moreover, you should limit the intake of caffeine.
http://pregnancyhelper.in

6:53 PM  
Anonymous Anonymous said...

Excellent article. Keep writing such kind of information on your page.
Im really impressed by your site.
Hi there, You've performed an incredible job. I'll certainly digg it and in my opinion
suggest to my friends. I'm sure they will be benefited from this site.

Visit my web page ... http://digi29.ugu.pl

6:59 PM  
Anonymous Anonymous said...

click here One particular matter I seen immediately had been your own big difference Massage in Beijing rollers that will worked well a corner.
Men of all ages, races and sexual orientations are now learning about the sexual and health benefits associated with prostate milking.
http://hyderabad.locanto.in/ID_163682523/Male-to-Female-Body-Massage-in-Hyderabad.html

12:49 PM  
Anonymous Anonymous said...

Very good information. Lucky me I found your website by accident (stumbleupon).
I have saved as a favorite for later!

Review my homepage: http://www.goldenrat.com

10:51 PM  
Anonymous Anonymous said...

magnificent points altogether, you just won a new reader.

What may you recommend in regards to your publish that you made some days in the past?
Any positive?

Check out my blog ... opensociology.ru

7:58 AM  
Anonymous Anonymous said...

no membership milf dating http://loveepicentre.com/testimonials/ marijuana free dating
foreign national internet dating [url=http://loveepicentre.com/success_stories/]dating website animals[/url] dating single personal ad
obese dating website [url=http://loveepicentre.com/testimonials/]free onlijne dating sim[/url] dating again [url=http://loveepicentre.com/user/sexylala/]sexylala[/url] christian dating interracial single

12:48 AM  
Blogger UplayOnline said...

Appreciate the recommendation. Let me try it out.
playstar slots
gold slots

2:11 AM  

Post a Comment

<< Home