Last active
October 30, 2017 15:45
-
-
Save xywei/fb02529ccebbde1647359c84b755141c to your computer and use it in GitHub Desktop.
A Scraper for Shareholding Data (Shanghai)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
""" | |
Stock Connect Northbound Shareholding Search By Date - Shanghai Connect | |
""" | |
__copyright__ = "Copyright (C) 2017 Xiaoyu Wei" | |
__license__ = """ | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
""" | |
import requests | |
import re | |
from bs4 import BeautifulSoup | |
import datetime | |
def download_shareholdings(day, | |
month, | |
year, | |
sort_method='default', | |
filename=None): | |
if sort_method == 'default': | |
sort_method = '' | |
print('Downloading shareholdings data ', year, month, day, '..') | |
# {{{ scraping data | |
print(' Requesting data..') | |
url = 'http://www.hkexnews.hk/sdw/search/mutualmarket.aspx' | |
headers = { | |
"User-Agent": | |
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36" | |
} | |
s = requests.Session() | |
s.headers.update(headers) | |
r = s.get(url) | |
soup = BeautifulSoup(r.content, "html.parser") | |
viewstate = soup.select("#__VIEWSTATE")[0]['value'] | |
eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value'] | |
viewstategenerator = soup.select("#__VIEWSTATEGENERATOR")[0]['value'] | |
today = datetime.date.today() | |
date = format(today.year, '04d') + format(today.month, '02d') + format( | |
today.day, '02d') | |
form_data = { | |
'__EVENTVALIDATION': eventvalidation, | |
'__VIEWSTATE': viewstate, | |
'__VIEWSTATEGENERATOR': viewstategenerator, | |
'today': date, | |
'sortBy': sort_method, | |
'alertMsg': '', | |
'btnSearch.x': '39', | |
'btnSearch.y': '3', | |
'ddlShareholdingDay': format(day, '02d'), | |
'ddlShareholdingMonth': format(month, '02d'), | |
'ddlShareholdingYear': format(year, '04d') | |
} | |
r = s.post(url, data=form_data) | |
dessert = BeautifulSoup(r.content, "html.parser") | |
# }}} | |
# {{{ post processing | |
print(' Post-prcessing..') | |
data = dessert.find_all('table', {'class': | |
'result-table'})[0].find_all('tr') | |
header = data[0].find_all('th') | |
header_contents = [i.contents for i in header] | |
keys = [] | |
for h in header_contents: | |
key_comps = [str(s) for s in h] | |
key = ''.join(key_comps).replace('\n', '').replace('\r', '').replace( | |
'<br/>', ' ') | |
key = re.sub(r'<img alt=.+>', '', key) | |
key = key.rstrip().lstrip() | |
keys.append(key) | |
values = [] | |
# skip a blank tr | |
for row in data[2:]: | |
cols = row.find_all('td') | |
col_contents = [ | |
''.join(i.contents).replace('\n', '').replace('\r', | |
'').lstrip().rstrip() | |
for i in cols | |
] | |
values.append(col_contents) | |
# cleaning figures | |
for val in values: | |
val[1] = '"' + val[1] + '"' | |
val[2] = val[2].replace(',', '') | |
val[3] = val[3].replace('%', '') | |
for vv in val: | |
vv = vv.rstrip().lstrip() | |
# extract actual shareholding date | |
hold_date = ''.join( | |
dessert.find("div", {"id": "pnlResult"}).findChildren()[0] | |
.contents).replace('\n', '').replace( | |
'\r', '').lstrip().rstrip().split(' ')[-1] | |
# print(' Actual shareholding date:', hold_date) | |
hold_day, hold_month, hold_year = hold_date.split('/') | |
# output filename | |
if filename == None or len(filename) == 0: | |
csv_filename = 'shareholdings-' + hold_year + hold_month + hold_day + '-sorted_by_' + sort_method + '.csv' | |
else: | |
csv_filename = filename | |
print(' Output written in', csv_filename) | |
# dump into a csv | |
f = open(csv_filename, 'w') | |
for i in range(len(keys)): | |
f.write(keys[i]) | |
if i < len(keys) - 1: | |
f.write(',') | |
else: | |
f.write('\n') | |
for r in values: | |
for j in range(len(r)): | |
f.write(r[j]) | |
if j < len(r) - 1: | |
f.write(',') | |
else: | |
f.write('\n') | |
f.close() | |
# }}} | |
# vim: fdm=marker |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
import sc | |
# query info | |
days = [5, 10, 15, 20] | |
month = 10 | |
year = 2017 | |
# optional | |
# other options are: stockcode, stockname, Shareholding, ShareholdingPercent | |
sort_method = 'default' | |
# optional, set None to use auto-generated filename | |
output_filename = None | |
for day in days: | |
sc.download_shareholdings(day, month, year, sort_method, output_filename) | |
print('Done.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment