Python 簡小股票價格讀取程序

来源:互联网 发布:淘宝宝贝主图模板 编辑:程序博客网 时间:2024/04/29 22:07

金融問題,好像和中國的股市不相干似的,天天在升。而香港的股市沒有跟隨美國股市帶領,轉向由中資股主導的市場。

然而,股市是很波動的,股市數據也很大量,作為一個普通人,如何穫取自已的所須信息呢?

 


<script type="text/javascript"><!-- google_ad_client = "pub-9858973754388865";/* 468x60, created 17/10/09 */google_ad_slot = "7218176094";google_ad_width = 468;google_ad_height = 60;// --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

以下是由python 制作的小小股票價格讀取器,示範用途,功能不完善

程式環境要求

  • Python 2.5 or Python 2.6
  • Python lxml modules

在此就不仔細說如何,安裝lxml modules 了,請查詢其它相關文章

 

在未進行編程時,先到我們的目標,例如Yahoo! Finance,用IE Developer Tool, 或Firefox 的firebug.快速的讀取源代碼,該價格小格的HTML DOM Tree 識別符號,這有利於我拆解目標網站的資料,如上圖所顯示,我們找到了 ID Tag,但價格那個元素里沒有ID Tag,怎麼做呢,我們先用ID tag 找到我們要的區域,因為ID Tag理應在整個HTML 里只有一個,所以,我們可以很準確找到要的元素,然後再用Class 來找就沒什麼問題了。

 

以下是整個程式代碼

  1. import threading
  2. import urllib
  3. import lxml.html
  4. import time
  5.  
  6. class WorkerThread(threading.Thread):
  7.    
  8.     def __init__(self,task):
  9.         self.task = task
  10.         threading.Thread.__init__(self)
  11.    
  12.     def run(self):
  13.         while True:
  14.             print 'Runging ....'
  15.             if self.task != None:
  16.                 url = 'http://hk.finance.yahoo.com/q?s=%s.hk'%task
  17.                 print 'url:%s'%url
  18.                 f = urllib.urlopen(url)
  19.                 htmlContent = f.read()
  20.                 f.close()
  21.                 print 'finish read web content'
  22.                 html = lxml.html.fromstring(htmlContent)
  23.                 box = html.get_element_by_id('quote-bar-latest')
  24.                 vals = box.find_class('price')
  25.                 if vals is not None and len(vals) > 1:
  26.                     print 'code: %s, Price: %s'%(self.task,vals[0])
  27.                
  28.                 time.sleep(5.0)
  29.                
  30.    
  31.  
  32. def StartWorker(taskList = []):
  33.     for task in taskList:
  34.         WorkerThread(task).start()
  35.    
  36.  
  37. tasks = []
  38. tasks.append('0005')
  39. tasks.append('2007')
  40.  
  41. StartWorker(tasks)

 

這段代碼,只說明了,我們能通過一些大型網絡讀取股票數據,在某些網站,他們的伺服器是做了一些設置,我們并不能大量的讀取,不然,會對我的IP 進行封鎖。也許你會問,我要這數據做什麼用呢。在金融界里,有兩派,一種是依靠技術分析,說的就是用過往股價表現,用特定方程式,估數,股票到達某個價位,就為買入信號,當然,也有賣出信號。而這類分析,就很依賴股價數據。在往後幾篇,我會完善這個小程式,當然,依然會使用Python 作為工具



<script type="text/javascript"><!-- google_ad_client = "pub-9858973754388865";/* 468x60, created 17/10/09 */google_ad_slot = "7218176094";google_ad_width = 468;google_ad_height = 60;// --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

原创粉丝点击