iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 26
0
AI & Data

python 入門到分析股市系列 第 26

[Day26] 財報爬蟲和分析

前言

今天是鐵人的第26天,主要介紹爬取財報的資料,和財報的基本分析。

安裝的套件

需要的套件requests,如果沒有這個套件用以下的語法新增

pip install requests

預先載入套件

介紹底下的圖表之前先預先載入需要的套件

# basic
import numpy as np
import pandas as pd

# get data
import pandas_datareader as pdr

# visual
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

#requests
import requests

爬取財報的資料 - 營益

資料來源

網站:公開資訊觀測站
爬取的內容:

  1. 營益分析表

要分析的function

def remove_td(column):
    remove_one = column.split('<')
    remove_two = remove_one[0].split('>')
    return remove_two[1].replace(",", "")

def translate_dataFrame(response):
     # 拆解內容
    table_array = response.split('<table')
    tr_array = table_array[1].split('<tr')
    
    # 拆解td
    data = []
    index = []
    column = []
    for i in range(len(tr_array)):
        td_array = tr_array[i].split('<td')
        if(len(td_array)>1):
            code = remove_td(td_array[1])
            name = remove_td(td_array[2])
            revenue  = remove_td(td_array[3])
            profitRatio = remove_td(td_array[4])
            profitMargin = remove_td(td_array[5])
            preTaxIncomeMargin = remove_td(td_array[6])
            afterTaxIncomeMargin = remove_td(td_array[7])
            if(type(code) == float):
                data.append([code, revenue, profitRatio, profitMargin, preTaxIncomeMargin, afterTaxIncomeMargin])
                index.append(name)
            if( i == 1 ):
                column.append(code)
                column.append(revenue)
                column.append(profitRatio)
                column.append(profitMargin)
                column.append(preTaxIncomeMargin)
                column.append(afterTaxIncomeMargin)
                
    return pd.DataFrame(data=data, index=index, columns=column)

抓取資料的程式

def financial_statement(year, season):

    if year >= 1000:
        year -= 1911
        
    url = 'http://mops.twse.com.tw/mops/web/ajax_t163sb06'
    form_data = {
        'encodeURIComponent':1,
        'step':1,
        'firstin':1,
        'off':1,
        'TYPEK':'sii',
        'year': year,
        'season': season,
    }

    response = requests.post(url,form_data)
    response.encoding = 'utf8'
    
    df = translate_dataFrame(response.text)
    return df

stock = financial_statement(107,2)
stock = stock.astype(float)

抓取到的資料如下圖
https://ithelp.ithome.com.tw/upload/images/20181106/2011139090XgNFaF3f.png

營利分析

抓取完資料之後要來做簡單幾個例子的分析,示範如下

  • 只拿某個股票的營利
stock.loc['一零四']
# 輸出結果
公司代號          3130
營業收入        782.06
毛利率(%)       89.89
營業利益率(%)     21.27
稅前純益率(%)     22.96
稅後純益率(%)     18.55
Name: 一零四, dtype: object
  • 拿兩個以上的股票
stock.loc[['華新科','一零四']]

https://ithelp.ithome.com.tw/upload/images/20181106/20111390llGKr5S41R.png

  • 畫出毛利率的分布圖
plt.rcParams['axes.unicode_minus']=False
fig = plt.figure(figsize=(10, 6))
stock['毛利率(%)'].hist(bins=range(-100,100) , label="毛利率(%)")
plt.legend()

https://ithelp.ithome.com.tw/upload/images/20181106/20111390kyvNiBVLhm.png

  • 利用DataFrame來選股
    設定以下的條件
  1. 毛利率(%)大於30
  2. 營業利益率(%)大於30
cond1 = stock['毛利率(%)'] > 30
cond2 = stock['營業利益率(%)'] > 30
stock[cond1 & cond2]

https://ithelp.ithome.com.tw/upload/images/20181106/201113900MzVC5Su5N.png


心得

今天學習了如何抓取財報的資料,並且轉成DataFrame,再用DataFrame來設條件選取想要的股票。這是一個非常基礎的示範。各位讀者也可以設定自己想要的條件來抓取股票

參考網站

FinLab

之前的章節


上一篇
[Day25]繪製K線圖
下一篇
[Day27]投資組合的風險評估 - 算術平均數
系列文
python 入門到分析股市30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
fetnet615102
iT邦新手 4 級 ‧ 2019-10-09 00:13:36

出現錯誤:
ndexError Traceback (most recent call last)
df = translate_dataFrame(response.text)
tr_array = table_array[1].split('tr')
IndexError: list index out of range

我要留言

立即登入留言