Skip to content

Instantly share code, notes, and snippets.

@zqqf16
Last active August 29, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zqqf16/670de72a126c53221266 to your computer and use it in GitHub Desktop.
Save zqqf16/670de72a126c53221266 to your computer and use it in GitHub Desktop.
抓取基金收益信息
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import requests
import unicodedata
import re
from datetime import datetime
from operator import itemgetter
_ALL_FUNDS = [
['华商价值共享', '630016', 460.94],
['华商主题精选股票', '630011', 531.00],
['兴全合润分级股票', '163406', 737.82],
['易稳健收益A', '110007', 940.37],
]
class Fund(object):
_url_format = '''http://fund.eastmoney.com/f10/F10DataApi.aspx?\
type=lsjz&code={}&page=1&per=5'''.format
def __init__(self, name, code, share):
self.name = name
self.code = code
self.share = share
self.records = []
self.total = 0
def fetch(self):
url = self._url_format(self.code)
request = requests.get(url)
if not request.ok:
print('Failed to fetch fund: {}'.format(self.name))
return
results = self._parase_data(request.text)
records = []
for i in results:
records.append(
{
'date': i[0],
'net': i[1],
'gains': i[2],
'value': i[1]*self.share,
}
)
self.records = sorted(records, key=itemgetter('date'), reverse=True)
self.total = self.records[0]['value']
def _parase_data(self, html):
tr_re = re.compile(r'<tr>(.*?)</tr>')
item_re = re.compile(r'''<td>(\d{4}-\d{2}-\d{2})</td>
<td.*?>(.*?)</td>
<td.*?>(.*?)</td>
<td.*?>(.*?)</td>
<td.*?>(.*?)</td>
<td.*?>(.*?)</td>
<td.*?></td>''', re.X)
result = []
for line in tr_re.findall(html):
match = item_re.match(line)
if match:
entry = match.groups()
date = datetime.strptime(entry[0], '%Y-%m-%d')
result.append(
[date, float(entry[1]), entry[3]]
)
return result
def width(string):
width = 0
for c in string:
if unicodedata.east_asian_width(c) in ('F', 'W', 'A'):
width += 2
else:
width += 1
return width
def color(gains):
green = '\033[0m\033[49;32m↓\033[0m'
red = '\033[0m\033[49;31m↑\033[0m'
if (gains.startswith('-')):
return green
else:
return red
def main():
''' Main function'''
funds = []
for i in _ALL_FUNDS:
fund = Fund(*i)
fund.fetch()
funds.append(fund)
fund_format = '{:<10}{:>10.2f}{:>10}{:>10.2f} {}'.format
for f in funds:
print(f.name)
for record in f.records:
print(fund_format(
record['date'].strftime('%Y-%m-%d'),
record['net'],
record['gains'],
record['value'],
color(record['gains']),
))
print()
total = sum([f.total for f in funds])
print('总额: {:.2f}\n'.format(total))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment