做了个从google finance取股价的脚本
Pubdate:2011-10-28 09:30:44 Categories: python, 财经 1916 ViewsTags: python, 股票
如题,比较实用,可以从google finance抓取股价,监测买入和卖出价格。顺便曝光一下我的持仓和操作手法。其中的float()不接受有千分位的字符串,在网上蠢蠢地找了一下午也没找到办法,结果到邮件列表一问就有人(chuan)帮忙给出答案了。
num = '1,000.00'
num = float(num.replace(',', ''))
又有人(pansz)说:
直接用 locale 模块带的转换工具。 locale.atof ,这个连去千位都不需要了。
啊,python总是给人一种眼前一亮的感觉。后一种刚看到,还没试。贴代码如下:
#/bin/env python
import sys
import time, datetime
import re, urllib
def get_quote(symbol):
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read().decode('utf-8')
find_quote = re.search(r'\<span\sid="ref_\d+.*">(.+)<', content)
find_range = re.search(r'\<td\sclass="val">(.+)\n',content)
if find_quote:
quote = find_quote.group(1)
range_val = find_range.group(1)
else:
quote = 'no quote available for: %s' % symbol
try:
return float(quote.replace(',','')),\
float(range_val.split('-')[0].replace(',','')),\
float(range_val.split('-')[1].replace(',',''))
except:
return float(quote.replace(',','')),0,0
def main():
#print get_quote('ibm') #168.28
closetime = datetime.datetime(
datetime.datetime.now().year,
datetime.datetime.now().month,
datetime.datetime.now().day,15,5)
while True :
companyfile = open('companys')
print ' symbol |current| min | max | buy | sell |flag'
for line in companyfile:
symbol,middle_price_str = line.split(',')
middle_price = float(middle_price_str)
current_price,min_price,max_price = get_quote(symbol)
operation = '='
buy_price = round(middle_price/1.05,2)
sell_price = round(middle_price*1.05,2)
if min_price <= buy_price and min_price > 0:
operation = "+"
#print '%s'%'\a',
sys.stdout.write('\a')
if max_price >= sell_price:
operation += "-"
sys.stdout.write('\a')
print '%s|%*s|%*s|%*s|%*s|%*s|%s'%(
symbol,7,current_price,7,min_price,
7,max_price,7,buy_price,7,sell_price,operation)
if datetime.datetime.now() >= closetime:
break
else:
time.sleep(100)
'''Output-->
symbol |current| min | max | buy | sell |flag
SHA:000001|2473.41|2456.18|2483.76|2285.71| 2520.0|=
SHA:600036| 12.35| 12.25| 12.55| 11.81| 13.02|=
SHA:600221| 6.19| 6.09| 6.32| 5.8| 6.39|=
SHA:600360| 4.96| 4.88| 4.98| 4.62| 5.09|=
SHA:600362| 28.43| 28.2| 29.08| 27.65| 30.48|=
SHA:600900| 6.52| 6.46| 6.59| 6.02| 6.64|=
SHE:000709| 3.87| 3.83| 3.92| 3.66| 4.03|=
SHE:000868| 9.63| 9.56| 9.75| 9.05| 9.97|=
SHE:000983| 20.01| 19.63| 20.2| 18.93| 20.87|=
'''
if __name__ == "__main__":
main()
很粗糙,还在持续改进中。用到的数据文件companys的格式如下,这几只股票都是我目前持仓的:
SHA:000001,2400
SHA:600036,11.81
SHA:600221,6.09
SHA:600360,4.85
SHA:600362,27.65
SHA:600900,6.32
SHE:000709,3.84
SHE:000868,9.5
SHE:000983,18.93
Comments(0)