分级基金一般分为母基金和A/B份额的子基金。母基金可以通过拆分转换成A/B份额的子基金,A/B份额的子基金也可以通过合并方式转换成母基金。A/B份额的子基金可以进行场内交易,A/B份额的交易价格和它的净值价格不同,也就是会有折/溢价。根据A/B份额子基金的交易价格可以计算出母基金的净值,如果与母基金公布的净值相差较大,则可以通过合并、拆分进行套利交易。
于是想写个小程序监视每天分级基金的净值和交易价格,并且计算出净值差,判断是否存在套利机会。思路也比较简单,通过sinajs提供的股票数据接口获取每天的交易行情数据,然后解析出自己关注的数据,计算结果。
#-*- coding:utf-8 -*-
import urllib2
def download_html(url):
f = urllib2.urlopen(url)
return f.read()
def parse_line(line):
context = line.split('"')
return context[1].split(',')
def parse_html(html):
lines = html.split('\n')
items = []
for line in lines:
if len(line.strip()) == 0:
continue
item = parse_line(line)
items.append(item)
return items
def parse_items(items):
sa = float(items[0][2])
fa = float(items[1][1])
sb = float(items[2][2])
fb = float(items[3][1])
fc = float(items[4][1])
sda = items[0][-3]
fda = items[1][-2]
sdb = items[2][-3]
fdb = items[3][-2]
fdc = items[4][-2]
assert(sda == sdb)
assert(fda == fdb)
assert(fda == fdc)
sc = (sa + sb) / 2
pp = 100.0 * (sc - fc) / fc
return (fda, sa, fa, sb, fb, fc, sc, pp)
def parse_fund(a, b, c):
url = 'http://hq.sinajs.cn/list=sz%s,f_%s,sz%s,f_%s,f_%s' % (a, a, b, b, c)
html = download_html(url)
items = parse_html(html)
return parse_items(items)
def play_game():
a = '150018'
b = '150019'
c = '161812'
fund = parse_fund(a, b, c)
print '%s : %5.3f, %5.3f, %5.3f, %5.3f, %5.3f, %5.3f, %5.3f%%' % (fund[0], fund[1], fund[2], fund[3], fund[4], fund[5], fund[6], fund[7])
def test_download_html():
#url = 'http://www.baidu.com'
a = '150018'
b = '150019'
c = '161812'
url = 'http://hq.sinajs.cn/list=sz%s,f_%s,sz%s,f_%s,f_%s' % (a, a, b, b, c)
data = download_html(url)
assert(not data is None)
print data.decode('gb2312').encode('utf-8')
def test_parse_line():
line = 'var hq_str_sz150018="银华稳进,0.920,0.920,0.926,0.927,0.917,0.926,0.927,252350769,232719342.807,1568101,0.926,3017105,0.925,171000,0.924,110372,0.923,377600,0.922,952500,0.927,2176743,0.928,4024900,0.929,748300,0.930,136000,0.931,2013-01-18,15:45:52,00";'
item = parse_line(line)
assert(not item is None)
print item
def test_parse_html():
test_html = '''
var hq_str_sz150018="银华稳进,0.920,0.920,0.926,0.927,0.917,0.926,0.927,252350769,232719342.807,1568101,0.926,3017105,0.925,171000,0.924,110372,0.923,377600,0.922,952500,0.927,2176743,0.928,4024900,0.929,748300,0.930,136000,0.931,2013-01-18,15:45:52,00";
var hq_str_f_150018="银华稳进,1.003,1.16,1.003,2013-01-17,78.5548";
var hq_str_sz150019="银华锐进,0.692,0.685,0.703,0.715,0.683,0.702,0.703,994795375,697633497.324,3654630,0.702,4710800,0.701,7029806,0.700,388100,0.699,2360200,0.698,2244363,0.703,16549500,0.704,4911900,0.705,7603137,0.706,5983500,0.707,2013-01-18,15:45:52,00";
var hq_str_f_150019="银华锐进,0.605,0.605,0.615,2013-01-17,78.5548";
var hq_str_f_161812="银华深证100指数分级,0.804,0.883,0.809,2013-01-17,21.8818";
'''
items = parse_html(test_html)
assert(not items is None)
for item in items:
print item
if __name__ == '__main__':
play_game()
#test_download_html()
#test_parse_line()
#test_parse_html()