2010年8月2日 星期一

可轉債自動報價查詢 II

可轉債, CB, 自動化查詢, 股票, 金融

改進了之前的 script ,全部改成 python 來寫。可由標準輸入檔案讀入想查詢的台灣股市上市上櫃公司代號,完畢後輸出成 html table 並發信至指定的電郵信箱。


usage:

python thisscript.py < stocklist.txt


這支 script 基本上做了下面的事情:

1. 依代號查網頁 (tw.stock.yahoo.com)

2. 解析網頁資料

3. 輸出成 html table

4. 寄信 with attachment



#! /usr/bin/env python
# -*- coding: big5 -*-
import urllib2, re, sys, csv
import smtplib
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.utils import COMMASPACE

html = '<html><table border="1" style="border-collapse:collapse;" borderColor=black>\n'
html = html + '<tr><th>代碼</th><th>HTTP</th><th>名稱</th><th>成交價</th><th>漲跌</th><th>買進</th><th>賣出</th>'
html = html + '<th>張數</th><th>昨收</th><th>開盤</th><th>最高</th><th>最低</th></tr>\n'
data = []
for line in sys.stdin:
F1, F2, F3, F4, F5 = '', '', '', '', ''
F1 = re.match('\d+', line).group(0)
url = 'http://tw.stock.yahoo.com/q/q?s=' + F1
myrequest = urllib2.Request(url)
myrequest.add_header('User-Agent', 'Mozilla 5.0')
try:
content = urllib2.urlopen(myrequest)
F2 = 'OK'
except:
F2 = 'Failed'
c = content.read()
m = re.search(r'href="/q/bc\?s=\d+">(\d+.*?)</a>', c)
F3 = m.group(1) if m else '-'
m = re.search(r'nowrap><b>(\d+.?\d+|\d+|-)</b></td>', c)
F4 = m.group(1) if m else '-'
m = re.search(r'nowrap><font color=#......>(▽\d+.\d+|△\d+.\d+|\d+.\d+|-)', c)
F5 = m.group(1) if m else '-'
F6 = re.findall(r'wrap>(\d+.?\d+|\d+|-)</td>', c)
data.append([F1, F2, F3, F4, F5]+F6[1:])
for line in sorted(data, key=lambda x: float(x[3]) if (x[3] <> '-') else x[3]):
result = ''
for x in line:
result = result + x + ','
result = re.sub(',' , '</td><td>', result)
result = '<tr><th>'+result+'</tr>\n'
result = re.sub(r'<th>(\d+)</td>', r'<th>\1</th>', result)
html = html + result

html = html + '</table></html>\n'

tt = datetime.now().timetuple()

me = "sender@email.address"
you = ['recipient1@email.address', 'recipient2@email.address']

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "CB Report " + str(tt[0]) + "-" + str(tt[1]) + "-"  + str(tt[2]) + " "  + str(tt[3]) + ":"  + str(tt[4]) + ":"  + str(tt[5])
msg['From'] = me
msg['To'] = COMMASPACE.join(you)

# Create the body of the message (a plain-text and an HTML version).
# text = """ <html><b>test</b></html> """
# html = """ this is html data """
# Record the MIME types of both parts - text/plain and text/html.
# part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html', _charset='Big5') # _charset is important to avoid bad characters

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
#msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()