SlideShare a Scribd company logo
Python爬蟲攻防戰
- 攻防與金融大數據分析班
David Chiu
2017/04/30
關於我
 大數軟體有限公司創辦人
 前趨勢科技工程師
 ywchiu.com
 大數學堂
http://www.largitdata.com/
 粉絲頁
https://www.facebook.com/largitdata
 R for Data Science Cookbook
https://www.packtpub.com/big-data-and-
business-intelligence/r-data-science-cookbook
 Machine Learning With R Cookbook
https://www.packtpub.com/big-data-and-
business-intelligence/machine-learning-r-
cookbook
2
Machine Learning With R Cookbook
(机器学习与R语言实战) & R for Data Science Cookbook
Author: David (YU-WEI CHIU) Chiu
3
 所有課程補充資料、投影片皆位於
https://github.com/ywchiu/pyfinance
課程資料
4
抓取上市股市EPS 資料
5
請求 Request
回應 Response
網頁網頁連結器
Web Connector
資料剖析
Data Parser
資料中心
Data Center
爬蟲是怎麼運作的
6
如何抓取上市股市EPS 資料
7
http://mops.twse.com.tw/mops/web/t163sb19
進入公開資訊觀測站
8
觀察連結位置
9
1. 點選Network
2. 點選XHR
2. 點選連結
import requests
payload = {
'encodeURIComponent':'1',
'step':'1',
'firstin':'1',
'TYPEK':'sii',
'code':'',
'year':'104',
'season':'03'
}
res = requests.post('http://mops.twse.com.tw/mops/web/ajax_t163sb19', data=payload)
res.encoding= 'utf-8'
soup = bs(res.text)
讀取EPS資料
10
dfs = pd.read_html(soup.prettify('utf-8'), encoding= 'utf-8', header=0)
dfall = []
for df in dfs:
dfall.append(df[df['公司代號'].str.match('^[0-9]+')])
只抓取公司代號有數字的
11
刪除掉不必要的列
stockdf = pd.concat(dfall, ignore_index=True)
列出所有公司第三季的EPS
12
stockdf[stockdf['營業收入']==stockdf['營業收入'].max()]
猜猜誰是獲利王
13
stockdf.sort_values( by= ‘營業收入’,
ascending=False).head()
根據營業收入排序
14
由大到小做排序
df1 = stockdf.groupby(['產業別'], sort=False)['營業
收入'].max()
print df1
根據產業別統計
15
%pylab inline
df1.plot.pie()
使用matplotlib 繪圖
16
讓圖片在下方出現
 切換到matplotlib 設定目錄下
C:Anaconda2Libsite-packagesmatplotlibmpl-data
 修改matplotlibrc (將註解#拿掉)
font.family : sans-serif
font.sans-serif : Microsoft YaHei, …
如何讓matplotlib 出現中文?
17
增加微軟雅黑字體
zhfont = mpl.font_manager.FontProperties(
fname='C:UsersUsertwmtmTW.ttf')
plt.title('中文', fontproperties=zhfont)
指定中文字型
18
Windows10 要改成ttc
def getEPS(year, season):
dfall = []
payload = {
'encodeURIComponent':'1',
'step':'1',
'firstin':'1',
'TYPEK':'sii',
'code':'',
'year':year,
'season':season
}
res = requests.post('http://mops.twse.com.tw/mops/web/ajax_t163sb19', data=payload)
res.encoding= 'utf-8'
soup = bs(res.text)
dfs = pd.read_html(soup.prettify('utf-8'), encoding= 'utf-8', header=0)
for df in dfs:
dfall.append(df[df['公司代號'].str.match('^[0-9]+')])
return dfall
定義函式
19
dftotal = []
seasons = ['01','02','03','04']
for year in range(102,105):
for season in seasons:
dftotal.extend(getEPS(year, season))
批次執行102年到105 年的資料
20
stockdf = pd.concat(dftotal, ignore_index=True)
len(stockdf)
合併所有的Data Frame
21
 stockdf[stockdf['公司代號'] == '2330']
篩選出台積電股票
22
df2330 = stockdf[stockdf['公司代號'] == '2330']
df2330.plot(kind='line', rot=0)
繪製折線圖
23
圖表資料抓取
24
抓取財報狗的資訊
25
https://statementdog.com/analysis/tpe#2330
找出呼叫資料的進入點
26
1. 點選Network
2. 點選XHR
3. 點選連結
import requests
headers = {
'X-Requested-With':'XMLHttpRequest',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87
Safari/537.36',
}
rs = requests.session()
res =
rs.get('https://statementdog.com/analysis/analysis_ajax/2330/2011/1/20
16/4/1', headers = headers)
json = res.text
抓取圖表資料
27
jdf = pd.read_json(json)
jdf
使用Pandas讀取JSON
28
使用Selenium 模擬使用者動作
29
使用Selenium Plugin
30
https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/
使用Selenium Plugin 錄製動作
31
匯出Selenium 腳本
32
 https://github.com/mozilla/geckodriver/releases
下載GeckoDriver
33
將geckodriver 放到使用者目錄下
https://sites.google.com/a/chromium.org/chromedriver/
下載ChromeDriver
34
將chromedriver 放到使用者目錄下
# -*- coding: utf-8 -*-
from selenium import webdriver
from bs4 import BeautifulSoup
import unittest, time, re
driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.get("http://justdata.yuanta.com.tw/z/zk/zk00-f.asp")
soup = BeautifulSoup(driver.page_source)
print soup
driver.close()
執行Selenium 腳本
35
需要執行pip install selenium
可以切換成ChromeDriver
買賣日報表資料抓取
36
破解買賣日報表查詢系統
37
http://bsr.twse.com.tw/bshtm/
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/48.0.2564.116 Safari/537.36'
}
rs = requests.session()
r2 = rs.get('http://bsr.twse.com.tw/bshtm/bsMenu.aspx', headers = headers)
抓取bsMenu.aspx
38
使用GET 抓取bsMenu.aspx
payload = {
'__EVENTTARGET':'',
'__EVENTARGUMENT':'',
'__LASTFOCUS':'',
'RadioButton_Normal':'RadioButton_Normal',
'TextBox_Stkno':'2330',
'CaptchaControl1':'E3QL8'
'btnOK':'查詢'
}
for inp in soup.select('input[type==hidden]'):
payload[inp['id']] = inp['value']
r3 = rs.post('http://bsr.twse.com.tw/bshtm/bsMenu.aspx', data=payload, headers = headers)
需要POST 資訊
39
必須從上一頁的Hidden Value 擷取
如何破解Captcha
OCR 辨認裡面數字
 pytesser
https://code.google.com/p/pytesser/
 ocropus
https://code.google.com/p/ocropus/
 Google Vision API
https://cloud.google.com/vision/
40
大數學堂
http://largitdata.com/course/37
http://largitdata.com/course/38
r4 =
rs.get('http://bsr.twse.com.tw/bshtm/bsContent.aspx?v=t',
headers = headers)
print r4.text
使用GET 取得分點進出資訊
41
http://www.dama2.com/
打碼兔
42
從Google Trend
分析金融交易行為
43
 Google Trend 包含使用的搜尋行為,是否可以利
用使用者的搜尋行為判斷股票漲跌?
Google Trend
44
 http://www.nature.com/articles/srep01684
使用Pandas 實作論文
45
Preis, T., Moat, H. S., & Stanley, H. E. (2013). Quantifying trading behavior in
financial markets using Google Trends. Scientific reports, 3.
 Python for Data Analysis
源自於R
Table-Like 格式
提供高效能、簡易使用的資料格式(Data Frame)讓使用
者可以快速操作及分析資料
Pandas
46
可參照 pandas_in_finance.ipynb
 讀取 GoogleTrendsData
import pandas as pd
data = pd.read_csv('data/GoogleTrendsData.csv',
index_col='Date', parse_dates=True)
data.head()
讀取Google Trend 資料
47
%pylab inline
data.plot(subplots=True)
繪製GoogleTrend 與股價的關係
48
data['debt_mavg'] = pd.rolling_mean(data.debt, 3)
data.head()
算出Search Word 三週的移動平均
49
debt 的三週移動平均
data['debt_mavg'] = data.debt_mavg.shift(1)
data.head(10)
將三週平均資料平移一天
50
data['order'] = 0
# 黃金交叉做多
data['order'][data.debt > data.debt_mavg] = -1
# 死亡交叉做空
data['order'][data.debt < data.debt_mavg] = 1
data.head(10)
設定買賣策略
51
採取隔週買賣動作
e.g. 如果dept > dept_mavg
當週第一天買進道瓊,次
週第一天交易日末賣出
data['ret_djia'] = data.djia.pct_change()
data.head()
計算道瓊報酬
52
 報酬t是根據t-1週計算的,但買賣策略是發生在t
週,但在t+1周賣出,因此必須要將報酬平移一日
data['ret_djia'] = data['ret_djia'].shift(-1)
根據買賣日調整
53
data['ret_google'] = data.order * data.ret_djia
data.head(10)
計算根據Search Term 買賣的報酬
54
(1 + data.ret_google).cumprod().plot();
(1 + data.ret_djia).cumprod().plot();
觀察資金變化
55
it=(it−1+it−1⋅rt)=(1+rt)⋅it−1,i0=1
利用Search Term 做決策比
隨機買賣報酬要好很多
 試著用 Google Trend 對「流感」的搜尋擬定對康
那香(9919)的投資策略?
範例: 流感 v.s.康那香(9919)
56
可參照 googletrend_flu.ipynb
57

More Related Content

What's hot (20)

PDF
NumPyが物足りない人へのCython入門
Shiqiao Du
 
PPTX
[DL輪読会]ViNG: Learning Open-World Navigation with Visual Goals
Deep Learning JP
 
PDF
CVPR 2020 報告
cvpaper. challenge
 
PPTX
가명/익명정보 활용 Best Practice : 데이터 3법 3시간 완성 세미나 [2강 박경희 변호사] 201006
법무법인 디라이트 / D'LIGHT Law Group
 
PDF
This is toast ui calendar presentation
kasikasikasi
 
PDF
Trivia Scoresheet
Amanda Innes
 
PDF
(文献紹介)エッジ保存フィルタ:Side Window Filter, Curvature Filter
Morpho, Inc.
 
PDF
The Forward-Forward Algorithm
taeseon ryu
 
PDF
Simple and Effective Knowledge-Driven Query Expansion for QA-Based Product At...
Rakuten Group, Inc.
 
PDF
CTF for ビギナーズ バイナリ講習資料
SECCON Beginners
 
PDF
ブロックチェーン系プロジェクトで着目される暗号技術
MITSUNARI Shigeo
 
PDF
Embedded User Assistance Best Practices, Scott DeLoach, ClickStart
Scott DeLoach
 
PDF
局所特徴量と統計学習手法による物体検出
MPRG_Chubu_University
 
PPTX
コードの自動修正によって実現する、機能開発を止めないフレームワーク移行
gree_tech
 
PPTX
SfM Learner系単眼深度推定手法について
Ryutaro Yamauchi
 
PDF
[DL輪読会]自動運転技術の課題に役立つかもしれない論文3本
Deep Learning JP
 
PDF
SwiftのDI方法につい て最近考えてた話
Yahoo!デベロッパーネットワーク
 
PDF
[DL輪読会]DNN-based Source Enhancement to Increase Objective Sound Quality Asses...
Deep Learning JP
 
PDF
いまさら聞けないarmを使ったNEONの基礎と活用事例
Fixstars Corporation
 
PDF
GPGPU Seminar (GPGPU and CUDA Fortran)
智啓 出川
 
NumPyが物足りない人へのCython入門
Shiqiao Du
 
[DL輪読会]ViNG: Learning Open-World Navigation with Visual Goals
Deep Learning JP
 
CVPR 2020 報告
cvpaper. challenge
 
가명/익명정보 활용 Best Practice : 데이터 3법 3시간 완성 세미나 [2강 박경희 변호사] 201006
법무법인 디라이트 / D'LIGHT Law Group
 
This is toast ui calendar presentation
kasikasikasi
 
Trivia Scoresheet
Amanda Innes
 
(文献紹介)エッジ保存フィルタ:Side Window Filter, Curvature Filter
Morpho, Inc.
 
The Forward-Forward Algorithm
taeseon ryu
 
Simple and Effective Knowledge-Driven Query Expansion for QA-Based Product At...
Rakuten Group, Inc.
 
CTF for ビギナーズ バイナリ講習資料
SECCON Beginners
 
ブロックチェーン系プロジェクトで着目される暗号技術
MITSUNARI Shigeo
 
Embedded User Assistance Best Practices, Scott DeLoach, ClickStart
Scott DeLoach
 
局所特徴量と統計学習手法による物体検出
MPRG_Chubu_University
 
コードの自動修正によって実現する、機能開発を止めないフレームワーク移行
gree_tech
 
SfM Learner系単眼深度推定手法について
Ryutaro Yamauchi
 
[DL輪読会]自動運転技術の課題に役立つかもしれない論文3本
Deep Learning JP
 
SwiftのDI方法につい て最近考えてた話
Yahoo!デベロッパーネットワーク
 
[DL輪読会]DNN-based Source Enhancement to Increase Objective Sound Quality Asses...
Deep Learning JP
 
いまさら聞けないarmを使ったNEONの基礎と活用事例
Fixstars Corporation
 
GPGPU Seminar (GPGPU and CUDA Fortran)
智啓 出川
 

Similar to 20170430 python爬蟲攻防戰-攻防與金融大數據分析班 (9)

PDF
廣宣學堂Python金融爬蟲原理班 20170416
Paul Chao
 
PDF
Data Crawler using Python (I) | WeiYuan
Wei-Yuan Chang
 
PDF
Python crawling tutorial
Chen-Ming Yang
 
PDF
[系列活動] Python爬蟲實戰
台灣資料科學年會
 
PDF
網頁爬蟲入門 Python web crawler at 淡江大學 20170930
Tim Hong
 
PDF
Py ladies 0928
Chia-Yi Yen
 
PDF
Py ladies 0928
Yen_CY
 
PDF
20130325 mldm monday spide r
Chia-Chi Chang
 
PDF
python 實戰資料科學工作坊
David Chiu
 
廣宣學堂Python金融爬蟲原理班 20170416
Paul Chao
 
Data Crawler using Python (I) | WeiYuan
Wei-Yuan Chang
 
Python crawling tutorial
Chen-Ming Yang
 
[系列活動] Python爬蟲實戰
台灣資料科學年會
 
網頁爬蟲入門 Python web crawler at 淡江大學 20170930
Tim Hong
 
Py ladies 0928
Chia-Yi Yen
 
Py ladies 0928
Yen_CY
 
20130325 mldm monday spide r
Chia-Chi Chang
 
python 實戰資料科學工作坊
David Chiu
 
Ad

More from Paul Chao (12)

PPTX
AI與大數據數據處理 Spark實戰(20171216)
Paul Chao
 
PDF
企業導入微服務實戰 - updated
Paul Chao
 
PDF
企業導入微服務實戰 - updated
Paul Chao
 
PDF
廣宣學堂: 企業導入微服務實戰
Paul Chao
 
PDF
廣宣學堂: 機器視覺初探 10152017
Paul Chao
 
PDF
Python網站框架絕技: Django 完全攻略班
Paul Chao
 
PDF
開放運算&GPU技術研究班
Paul Chao
 
PDF
廣宣學堂: 容器進階實務 - Docker進深研究班
Paul Chao
 
PDF
廣宣學堂: R programming for_quantitative_finance_0623
Paul Chao
 
PDF
Docker workshop 0507 Taichung
Paul Chao
 
PDF
Introduction to Golang final
Paul Chao
 
PDF
手把手帶你學Docker 03042017
Paul Chao
 
AI與大數據數據處理 Spark實戰(20171216)
Paul Chao
 
企業導入微服務實戰 - updated
Paul Chao
 
企業導入微服務實戰 - updated
Paul Chao
 
廣宣學堂: 企業導入微服務實戰
Paul Chao
 
廣宣學堂: 機器視覺初探 10152017
Paul Chao
 
Python網站框架絕技: Django 完全攻略班
Paul Chao
 
開放運算&GPU技術研究班
Paul Chao
 
廣宣學堂: 容器進階實務 - Docker進深研究班
Paul Chao
 
廣宣學堂: R programming for_quantitative_finance_0623
Paul Chao
 
Docker workshop 0507 Taichung
Paul Chao
 
Introduction to Golang final
Paul Chao
 
手把手帶你學Docker 03042017
Paul Chao
 
Ad

20170430 python爬蟲攻防戰-攻防與金融大數據分析班