<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by hello this is Hung Min! on Medium]]></title>
        <description><![CDATA[Stories by hello this is Hung Min! on Medium]]></description>
        <link>https://medium.com/@b5031631512567?source=rss-4ad22807e17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*4gBqw4mBjpBnvHRF_Aewrw.jpeg</url>
            <title>Stories by hello this is Hung Min! on Medium</title>
            <link>https://medium.com/@b5031631512567?source=rss-4ad22807e17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:08:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@b5031631512567/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[紀錄一下這次去一個一直很嚮往的startup面試的過程以及自我省思]]></title>
            <link>https://b5031631512567.medium.com/%E7%B4%80%E9%8C%84%E4%B8%80%E4%B8%8B%E9%80%99%E6%AC%A1%E5%8E%BB%E4%B8%80%E5%80%8B%E4%B8%80%E7%9B%B4%E5%BE%88%E5%9A%AE%E5%BE%80%E7%9A%84startup%E9%9D%A2%E8%A9%A6%E7%9A%84%E9%81%8E%E7%A8%8B%E4%BB%A5%E5%8F%8A%E8%87%AA%E6%88%91%E7%9C%81%E6%80%9D-f95961d8a7ed?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f95961d8a7ed</guid>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Mon, 10 May 2021 16:04:41 GMT</pubDate>
            <atom:updated>2021-05-10T17:52:33.227Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Go freight 是一個提供forwarder all-in one service的web-based cloud software 新創公司，屬於vertical SAAS，提供NVOCC一整套的物流、資訊流、金流的解決方案，藉此增加forwarder營運的效率以及系統的整合，也省去NVOCC需要自己開發系統以及後續維護的成本。</blockquote><p>去年看到go freight這家公司就一直很有興趣，有一種「阿就是他了｣的那種感覺，因此一直有在關注職缺的訊息。這次嘗試的職位是QA intern，本來是沒有抱太大的期望，但意外地收到面試的通知。</p><p>只會爬蟲和selenium的我原本認為應該有很大的機會會被電翻，但和QA team manager面談的過程，發現只會一點程式的我，似乎還真的有機會可以嘗試QA這個職位(或是因為manager人太好，所以不忍心電我，甚至還蠻肯定我過去的經驗)，讓我有點受寵若驚，但好的開始也算是成功的一步，因此這幾天還特別會去研究了Python testing BDD。</p><p>第二次直接和CEO Trenton面試，他認為我過去的經驗比較適合嘗試看看key account 的位置，可以結合過去Sales的經驗，做business development或是Account Executive。</p><p>我常常在思考要麼看待業務這個名詞，有時候會認為業務沒什麼專業性，就是一直應酬、被客戶罵到狗血淋頭，每天daily work都很routine，回頭看會覺得生活很空虛，不知道自己到底做了什麼，但有時候也會覺得業務很酷，因為我很享受那種團隊合作以及解決問題的過程，如果能用更科學或是系統化的方法套入業務，的確是一個會穰人想要躍躍欲試的職缺(1.要先加強一下破英文2.比起QA沒有基礎，只能在那邊雷隊員，往sales走好像也比較能夠結合過去經驗帶出自己的價值)，透過和PM或是其他部門的合作，能夠更清楚的描繪出公司現階段或是未來的business value。</p><p>這次Trenton問了很多問題，有些問題後續想想答的還真的是頗爛，沒有把握的很好(果然還是要再多一點自信阿</p><p>Questions:</p><ol><li>自己的優缺點?</li><li>為什麼選擇去讀MBA?</li><li>之前都用什麼方式做新客戶開發?</li><li>認為自己可以勝任sales這個職位嗎?</li><li>QA和Account Executive會比較想要嘗試哪個?</li><li>每個東西都學但會不會都學得不精?</li><li>5年後的目標</li><li>…..</li></ol><p>面談過程，不難發現和其他實習生說的一樣，Trenton是個頭腦清楚且思考很有邏輯的人，對於公司現階段、未來或是產業的觀察，刻劃都很到位，十足展現身為一個新創企業領導人的風範。</p><p>不管後續的結果是好是壞，這次面試都是一個很好的嘗試，和Trenton聊過後，也才發現sales這個職位並沒有以前想像的無趣及空洞，尤其在新創機會做sales，不像傳統業務打游擊戰，透過科技化的系統輔助，business development也很有趣，其實還有很多的know how可以學習。</p><p><strong><em>Hope everything goes well for the final outcome and keep going.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f95961d8a7ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender System(推薦系統)-collaborative filtering(協同過濾)]]></title>
            <link>https://b5031631512567.medium.com/recommender-system-%E6%8E%A8%E8%96%A6%E7%B3%BB%E7%B5%B1-collaborative-filtering-%E5%8D%94%E5%90%8C%E9%81%8E%E6%BF%BE-f3c57ae83792?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c57ae83792</guid>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Sun, 03 May 2020 16:17:55 GMT</pubDate>
            <atom:updated>2020-05-20T08:33:39.904Z</atom:updated>
            <content:encoded><![CDATA[<p>推薦系統(Recommender System)內有分為collaborative filtering(協同過濾)，以及content based兩種model。</p><p>1. collaborative filtering(協同過濾):<br>較為簡單，主要是利用matrix的方式，建立不同商品以及不同消費者間矩陣模型，整合出一個簡單的商業訊息，來幫助預測對於某項產品可能有興趣的消費者or某個消費者可能適合的商品</p><ul><li>優點: 就是因為此模型只單純建立矩陣模型，記錄彼此的對應關係，並不考慮商品本身的特性以及用戶的性質，資料的處理以及儲存較為簡單</li><li>缺點: 但因為不考慮商品以及用戶的特性，矩陣會有稀疏性(例如: 商品太多, 用戶太少)，導致預測失真</li></ul><p>2.content based model複雜很多，主要會透過演算法的方式來進行推薦的模擬，由於內涵較多統計以及現代的數學模型，因此這邊就先不紀錄了</p><p>這邊大概紀錄一下，要如何透過協同過濾的算法來做簡單的推估</p><ol><li>首先先引入資料</li></ol><pre>import numpy as np<br>import pandas as pd</pre><pre>column_names = [&#39;user_id&#39;, &#39;item_id&#39;, &#39;rating&#39;, &#39;timestamp&#39;]</pre><pre>df1 = pd.read_csv(&#39;u.data&#39;, sep=&#39;\t&#39;, names=column_names)<br>movie_titles = pd.read_csv(&quot;Movie_Id_Titles&quot;)</pre><pre>df = pd.merge(df1, movie_titles, on = &quot;item_id&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*dV9P2EZUiGT0Mn9jBUUKwA.png" /><figcaption>共有100003筆資料</figcaption></figure><p>2. 先整理出每部電影評價的平均數以及評分人數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*_p4h7V0V5v56tFsqnez7kA.png" /></figure><p>3. 接著將平均評分數以及評分人數建立成一個新的datasets</p><blockquote>從rating內就可以看出每部電影的評分狀態</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*duiRyj0FRgUdWgHtwl3sHg.png" /></figure><p>4. 接著透過直方圖來看一下資料分布的狀態</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*qbyfJI-ayJ0Uud9Ohk51yw.png" /><figcaption>(可以看出電影主要的評分人數在0~100間)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*eCa4KzbFXdfjjHVnojNo_A.png" /><figcaption>(可以看出電影主要的評分平均落在2.5~4之間)</figcaption></figure><p>5. 協同過濾model最大的核心價值就是透過矩陣模型來做觀察，因此先將資料做個轉換矩陣模式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*aq2VlfmL9vPkQdcuNQz3pg.png" /><figcaption>**原始資料**</figcaption></figure><pre>moviemat = df.pivot_table(index=&#39;user_id&#39;,columns=&#39;title&#39;,values=&#39;rating&#39;)<br>moviemat.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NacPdBk_Uiw4__QR3imZww.png" /><figcaption>利用原始資料轉換成pivot table，顯示出每個user對於每部電影的評分</figcaption></figure><blockquote><strong>由於電影Star Wars (1977)以及Liar Liar (1997)評分的人數都較多，因此用此兩資料作為base，推薦類似的電影給用戶</strong></blockquote><p>6. 首先，先將<strong>Star Wars (1977)</strong>以及<strong>Liar Liar (1997)</strong>的資料從pivot_table拿出</p><pre>starwars_user_ratings = moviemat[&#39;Star Wars (1977)&#39;]<br>liarliar_user_ratings = moviemat[&#39;Liar Liar (1997)&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*mh65xRfqNt3VS6YK0wX4-Q.png" /><figcaption>Starwars和LiarLiar 的所有使用者評分</figcaption></figure><p>7. 接著來看一下電影starwars和liar liar對於其他電影的相關係數，如果相關係數高，且評分的人數不低(設定&gt;100)，代表應該可以推薦相關係數高的電影給喜歡starwars以及liar liar的用戶<br>(雖然相關係數高，但要注意評分的人數，如果評分人數太少(只有1~2人)，即使相關係數高，參考度也不高)</p><pre>similar_to_starwars = moviemat.corrwith(starwars_user_ratings)<br>similar_to_liarliar = moviemat.corrwith(liarliar_user_ratings)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*oY6tiw3qAf7IMr3QkT5bng.png" /></figure><h3>推論</h3><ul><li>和Star Wars(1977)相關係數高的電影有Empire Strikes Back, The (1980)、Return of the Jedi (1983)…，且評分人數都有3~500，具有一定參考價值，因此可以推論說可能喜歡星際大戰的人也會喜歡這些電影</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8UvAx6CpThImj5wdcDaRQ.png" /></figure><ul><li>和Liar Liar (1997)相關係數高的電影有Batman Forever (1995)、Mask, The (1994)…，且評分人數都&gt;100，尚具有一定參考價值，因此可以推論說可能喜歡王牌大騙子的人也會喜歡這些電影</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdzbYLDwm6r8Li72FLsqKg.png" /></figure><p>參考至udemy課程:</p><p>Python for Data Science and Machine Learning Bootcamp(<a href="https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/">https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c57ae83792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[房屋實價登錄爬蟲]]></title>
            <link>https://b5031631512567.medium.com/%E6%88%BF%E5%B1%8B%E5%AF%A6%E5%83%B9%E7%99%BB%E9%8C%84%E7%88%AC%E8%9F%B2-a2426eea849f?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2426eea849f</guid>
            <category><![CDATA[web-crawler]]></category>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Sun, 03 May 2020 09:36:39 GMT</pubDate>
            <atom:updated>2020-05-03T09:37:34.322Z</atom:updated>
            <content:encoded><![CDATA[<p>前一陣子朋友寫了一個永慶房屋實價登錄的爬蟲請我跑，由於有一陣子沒爬蟲了，那就趁著這個機會也來試試看。<br>實際跑起來效能沒有那麼好，可能還有可以有加速的空間。<br>原本想說用BeautifulSoup來寫應該就可以了，但發現如果資料量太多，重複向server丟requests最後會跳error，所以如果資料量大的話，應該還是得透過selenium來定位資料比較可行。</p><p>以下還是分別紀錄用BeautifulSoup和Selenium的方式來爬取資料。</p><h3>BeautifulSoup</h3><blockquote>基本上資料量不大的話，sever不會跳error，但如果資料量太大，通常執行到一半就會當掉了</blockquote><pre>import requests as req<br>from bs4 import BeautifulSoup<br>import pandas as pd<br>import numpy as np</pre><ol><li>載入每頁內容，並儲存成DataFrame形式<br>(總共有11個columns)</li></ol><pre>def get_page_info(url):<br>    <br>    r = req.get(url)<br>    soup = BeautifulSoup(r.text)<br>    <br>    time = []<br>    types = []<br>    address = []<br>    deal_price = []<br>    floor_space = []<br>    unit_price = []<br>    plot = []<br>    floor = []<br>    age = []<br>    parkingspace = []<br>    info = []</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;time&quot;):<br>        time.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(time)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;type&quot;):<br>        types.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(types)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;add&quot;):<br>        address.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(address)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;dealPrice&quot;):<br>        deal_price.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\r&quot;,&quot;&quot;))<br>    info.append(deal_price)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;floorSpace&quot;):<br>        floor_space.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\r&quot;,&quot;&quot;))<br>    info.append(floor_space)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;unitPrice&quot;):<br>        unit_price.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(unit_price)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;plot&quot;):<br>        plot.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(plot)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;floor&quot;):<br>        floor.append(i.text.strip())<br>    info.append(floor)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;age&quot;):<br>        age.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(age)</pre><pre>for i in soup.find_all(&quot;td&quot;, class_=&quot;parkingSpace&quot;):<br>        parkingspace.append(i.text.strip().replace(&quot; &quot;, &quot;&quot;).replace(&quot;\r&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;))<br>    info.append(parkingspace) <br>    <br>    title = [&#39;成交&#39;, &#39;型態&#39;, &#39;地址&#39;, &#39;成交價&#39;, &#39;建坪&#39;, &#39;單價&#39;, &#39;地坪&#39;, &#39;樓別&#39;, &#39;屋齡&#39;, &#39;車位&#39;]<br>    <br>    data = {}<br>    for j in range(len(title)):<br>        data[title[j]] = info[j]</pre><pre>data = pd.DataFrame(data)<br>   <br>    return data</pre><p>2. 找”下一頁”的URL</p><pre>def get_web_https://medium.com/url(url):<br>    <br>    r1 = req.get(url)<br>    soup1 = BeautifulSoup(r1.text)<br>    for i in soup1.find(&quot;ul&quot;, class_=&quot;pagination clearfix&quot;):<br>        <br>        if i.find(&quot;a&quot;) != -1 and &quot;下一頁&quot; in i.find(&quot;a&quot;).text:<br>            notskip = True<br>        else:<br>            notskip = False<br>            <br>        while notskip:<br>            next_page = &quot;<a href="https://evertrust.yungching.com.tw/">https://evertrust.yungching.com.tw</a>&quot;+ i.find(&quot;a&quot;).get(&quot;href&quot;)<br>            url = next_page             <br>            return url</pre><p>3. 將目前永慶頁面上提供的縣市名稱先存成一個list<br>([‘北市’, ‘新北’, ‘桃園’, ‘竹市’, ‘竹縣’, ‘台中’, ‘彰化’, ‘台南’, ‘高雄’, ‘屏東’, ‘宜蘭’, ‘基隆’, ‘南投’, ‘雲林’, ‘苗栗’, ‘嘉市’, ‘嘉縣’, ‘花蓮’, ‘台東’, ‘金門’, ‘澎湖’])</p><pre>url = &quot;<a href="https://evertrust.yungching.com.tw/region/">https://evertrust.yungching.com.tw/region/</a>台北市/不限/1#mainContent&quot;<br>search_cities = []</pre><pre>r = req.get(url)<br>soup = BeautifulSoup(r.text)</pre><pre>for i in soup.find(&quot;ul&quot;, class_=&quot;conditions&quot;):<br>    if i.find(&quot;a&quot;) != -1:<br>        city = i.find(&quot;a&quot;).get(&quot;title&quot;).strip()<br>        city_name = i.find(&quot;a&quot;).text.strip()</pre><pre>search_cities.append(city_name)</pre><p>4. 利用for/while迴圈讀取不同縣市/不同分頁資料</p><pre>import sys</pre><pre>for city in search_cities:<br>    first_page = &quot;<a href="https://evertrust.yungching.com.tw/region/%7B%7D/">https://evertrust.yungching.com.tw/region/{}/</a>不限/1#mainContent&quot;.format(city)</pre><pre>current_page = first_page</pre><pre>#next_page = get_web_url(https://medium.com/current_page)<br>    #dataframe = get_page_info(current_page)</pre><pre>dataframe= []<br>    while current_page:<br>    <br>        data = get_page_info(current_page)<br>        dataframe.append(data)<br>        current_page = get_web_url(https://medium.com/current_page)<br>    <br>    sys.stderr.write(&quot;Write data to file &quot;+city+&quot;...\n&quot;)<br>    full_data = pd.concat(dataframe)</pre><pre>writer = pd.ExcelWriter(&quot;C:/Users/b5031/housing.xlsx&quot;)<br>    full_data.to_excel(writer, encoding = &quot;big5&quot;, sheet_name = city)<br>    writer.save()</pre><h3><strong>Selenium</strong></h3><blockquote>定位資料後，整理完直接寫入csv檔，目前run過一次不會跳error，但應該可以再用一些方次加快速度</blockquote><pre>from selenium import webdriver<br>import time<br>import sys<br>import os<br>import win32api<br>import csv</pre><ol><li>載入每頁內容</li></ol><pre>def load_page_info(td):<br>    info = []<br>    for i in range(0,len(td),10):<br>        try:<br>            if int(td[i].text) &gt; 10000:<br>                info.append(list([td[i].text, td[i+1].text, td[i+2].text.replace(&quot;\n&quot;, &quot; &quot;).encode(sys.stdin.encoding, &quot;replace&quot;).decode(sys.stdin.encoding), td[i+3].text, td[i+4].text, td[i+5].text, td[i+6].text, td[i+7].text, td[i+8].text, td[i+9].text]))<br>        except ValueError:<br>            break       <br>    return info</pre><p>2. 查找永慶頁面上提供的欄位</p><pre>#載入欄位title</pre><pre>url = &quot;<a href="https://evertrust.yungching.com.tw/">https://evertrust.yungching.com.tw</a>&quot;<br>driver = webdriver.Chrome(&quot;C:/Users/chromedriver.exe&quot;)<br>driver.get(url)</pre><pre>titles = driver.find_elements_by_css_selector(&quot;th&quot;)<br>title = []</pre><pre>for i in titles[:-2]:<br>    title.append(i.text)<br>    <br>print(title)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*jas9Lih5cXVn9656Z7n6CQ.png" /></figure><p>3. 查找永慶頁面上提供的縣市名稱</p><pre>url = &quot;<a href="https://evertrust.yungching.com.tw/">https://evertrust.yungching.com.tw</a>&quot;<br>driver = webdriver.Chrome(&quot;C:/Users/chromedriver.exe&quot;)<br>driver.get(url)</pre><pre>cities = driver.find_elements_by_css_selector(&quot;dd&quot;)</pre><pre>city_list = cities[0].text.split(&quot;\n&quot;)<br>print(city_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azCTKlNRjL8TYuQaOJRfRg.png" /></figure><p>4. 設定要存入的資料夾</p><pre>def create_folder():<br>    path = &quot;C:\\Users\\&quot; + win32api.GetUserName() + &quot;\\housing&quot;</pre><pre>try:<br>        if not os.path.exists(path):<br>            os.mkdir(path)<br>    except:<br>        print(&quot;error path&quot;)</pre><p>5. 執行主程式<br>(由於如果沒有設定篩選資料量會太大，因此這邊下面有設定查詢條件來簡化資料量，主要確認程式可以順利執行)</p><pre>url = &quot;<a href="https://evertrust.yungching.com.tw/region/%e5%8f%b0%e5%8c%97%e5%b8%82/%e4%b8%8d%e9%99%90?kw=&amp;dt=&amp;t=3&amp;a=1&amp;c=&amp;x=25.0329694&amp;y=121.5654177&amp;d=3">https://evertrust.yungching.com.tw/region/%e5%8f%b0%e5%8c%97%e5%b8%82/%e4%b8%8d%e9%99%90?kw=&amp;dt=&amp;t=3&amp;a=1&amp;c=&amp;x=25.0329694&amp;y=121.5654177&amp;d=3</a>&quot;<br>driver = webdriver.Chrome(&quot;C:/Users/chromedriver.exe&quot;)<br>driver.get(url)</pre><pre>cities = driver.find_elements_by_css_selector(&quot;dd&quot;)</pre><pre>city_list = cities[0].text.split(&quot;\n&quot;)<br>driver.refresh()</pre><pre>driver.get(url)<br>driver.implicitly_wait(2)</pre><pre>create_folder()  #首先先創建資料夾</pre><pre>    <br>#針對城市爬取資料</pre><pre>for i in range(1,3):<br>    sys.stderr.write(&quot;Is writing data to csv file &quot; + city_list[i-1] +&quot;...\n&quot;)<br>    time.sleep(2)<br>    city_click = driver.find_element_by_xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=&#39;wrap&#39;]/div[1]/div/div[2]/dl[1]/dd/ul/li[{}]/a&quot;.format(i))<br>    city_click.click()<br>    <br>    keepgoing = True<br>    <br>    city_name = city_list[i-1]<br>    <br>    data = []<br>    while keepgoing:</pre><pre>#print(driver.current_url)</pre><pre>td = driver.find_elements_by_css_selector(&quot;td&quot;)<br>        info = load_page_info(td)<br>        data.append(info)<br>            <br>        next_paging_available = []<br>        for i in driver.find_elements_by_xpath(&#39;/html/body/div[1]/div/div[2]/div[1]/div[4]/ul/li&#39;):<br>            if i.text == &quot;下一頁&quot;:<br>                next_paging_available.append(i)</pre><pre>if next_paging_available == []:<br>            keepgoing = False<br>            break<br>        else:<br>            driver.implicitly_wait(2)<br>            next_paging_available[0].click()</pre><pre>titles = [&#39;成交&#39;, &#39;型態&#39;, &#39;地址&#39;, &#39;成交價&#39;, &#39;建坪&#39;, &#39;單價&#39;, &#39;地坪&#39;, &#39;樓別&#39;, &#39;屋齡&#39;, &#39;車位&#39;]</pre><pre>path = &quot;C:/Users/{0}/housing/{1}.csv&quot;.format(win32api.GetUserName(),city_name)<br>    <br>    with open(path, &quot;w&quot;, newline = &quot;&quot;) as csvfile:<br>        writer = csv.writer(csvfile)</pre><pre>writer.writerow(titles)<br>        for i in range(len(data)):<br>            writer.writerows(data[i])</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2426eea849f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression(羅吉斯回歸) & Support Vector Machine(SVM)做A/B分類]]></title>
            <link>https://b5031631512567.medium.com/logistic-regression-%E7%BE%85%E5%90%89%E6%96%AF%E5%9B%9E%E6%AD%B8-support-vector-machine-svm-%E5%81%9Aa-b%E5%88%86%E9%A1%9E-82aa5e5edaf8?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/82aa5e5edaf8</guid>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 15:42:19 GMT</pubDate>
            <atom:updated>2020-05-20T07:11:15.327Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logistic Regression(羅吉斯回歸) 和Support Vector Machine(SVM)做A/B項的二元分類</h3><p>可透過Logistic Regression和SVM來幫助我們做A/B項的二元分類，同時也可以得出A和B的機率是多少，但SVM可以將平面投影到空間中，做出非線性的分類線，分類效果更好。<br>以下用iris資料做範例，分別用Logistic Regression和SVM來做分類</p><h3><strong>Logistic Regression</strong></h3><p>Logistic Regression是一個平滑曲線，所以A和B發生的機率是互補的，當判斷成A的機率越大，判斷成B的機率越小(斷成A類的機率 = 1-判斷成B的機率)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*9_CLAfBWwfbdvEi0FWiR6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*FZZTRGraMsTgGCsr-9Fkfg.png" /></figure><p>以下利用datasets中iris資料集用Logistic Regression來做training</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn import datasets<br></pre><pre>iris = datasets.load_iris()</pre><pre>X = iris[&quot;data&quot;]<br>y = iris[&quot;target&quot;]</pre><pre>X = pd.DataFrame(X, columns = iris[&quot;feature_names&quot;])<br>y = pd.DataFrame(y, columns = [&quot;target&quot;])<br>data = pd.concat([X,y], axis = 1)<br>data</pre><pre>data = data[data[&quot;target&quot;].isin([0,1])][[&quot;sepal length (cm)&quot;,&quot;petal length (cm)&quot;,&quot;target&quot;]]<br>data      </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*8VDjL2FK2ShN_PkYFwHpTA.png" /></figure><ol><li>Logistic Regression必須先做特徵縮放</li></ol><pre>from sklearn.preprocessing import StandardScaler</pre><pre>X = data.loc[:,[&quot;sepal length (cm)&quot;,&quot;petal length (cm)&quot;]]<br>y = data.target</pre><pre>sc = StandardScaler()<br>X_std = sc.fit_transform(X)</pre><p>2. 將資料區分為訓練集&amp;測試集</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train,X_test,y_train,y_test = train_test_split(X_std,y, test_size = 0.3, random_state = 0)</pre><p>3. 引入Logistic Regression model做training</p><pre>from sklearn.linear_model import LogisticRegression</pre><pre>lr = LogisticRegression(solver = &quot;lbfgs&quot;)<br>lr.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*lP3CCfC42e32BQ2lPO7RfQ.png" /></figure><p>4. 用預測值和原本y_test的資料作比較，看看正確率有多少，由於error是0，代表在這個model內，資料被100%完整分類</p><pre>error = 0<br>for i,j in enumerate(lr.predict(X_test)):<br>    if y_test.values[i] != j:<br>        error = error+1       <br>print(error)</pre><blockquote>可以用predict.proba_來顯示y 值 A/B類預測的機率</blockquote><pre>lr.predict_proba(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*LGu-CxV7LSMldbAGG3w64w.png" /></figure><p>5. 最後視覺化training好的分界線</p><pre>from mlxtend.plotting import plot_decision_regions</pre><pre>plot_decision_regions(X_train, np.array(y_train), clf = lr)<br>plt.xlabel(&quot;sepal length (cm) [standardlized]&quot;)<br>plt.ylabel(&quot;petal length (cm)&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*8NhJ3fOulY0XOgXXQUTmLg.png" /></figure><h3><strong>Support Vector Machine</strong></h3><p>由於羅吉斯回歸的分界線並不是非常直覺，因此利用SVM來嘗試做一個更好的分類法。<br>SVM是透過定義出一個分界線，此分界線分別到A和B資料都有最大的Margin。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*xdbgMhbIbxgbmWFXlJcFMA.png" /></figure><p>以下利用datasets中iris資料集用SVM來做training</p><pre>iris = datasets.load_iris()</pre><pre>X = iris[&quot;data&quot;]<br>y = iris[&quot;target&quot;]</pre><pre>X = pd.DataFrame(X, columns = iris[&quot;feature_names&quot;])<br>y = pd.DataFrame(y, columns = [&quot;target&quot;])<br>data = pd.concat([X,y], axis = 1)<br>data</pre><pre>data = data[data[&quot;target&quot;].isin([0,1])][[&quot;sepal length (cm)&quot;,&quot;petal length (cm)&quot;,&quot;target&quot;]]<br>data</pre><ol><li>和羅吉斯回歸一樣先做特徵縮放</li></ol><pre>from sklearn.preprocessing import StandardScaler</pre><pre>X = data.loc[:,[&quot;sepal length (cm)&quot;,&quot;petal length (cm)&quot;]]<br>y = data.target</pre><pre>sc = StandardScaler()<br>X_std = sc.fit_transform(X)</pre><p>2. 將資料區分為訓練集&amp;測試集</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train,X_test,y_train,y_test = train_test_split(X_std,y, test_size = 0.3, random_state = 0)</pre><p>3. 引入SVM model做training</p><pre>from sklearn.svm_model import SVC</pre><pre>svm = SVC(kernel = &quot;linear&quot;, probability = True)<br>svm.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*kFcMCTh9JwWhqjDTJK-Kog.png" /></figure><blockquote>可選擇是否要kernel設為線性（SVM的Kernel可以換成非線性, ex: ebf），並將Probability設為True</blockquote><p>4. 用預測值和原本y_test的資料作比較，看看正確率有多少，由於error是0，代表在這個model內，資料被100%完整分類。且用metrics.accuracy計算，正確率也是1.0</p><pre>error = 0<br>for i,j in enumerate(lr.predict(X_test)):<br>    if y_test.values[i] != j:<br>        error = error+1       <br>print(error)</pre><pre>from sklearn import metrics<br>metrics.accuracy_score(svm.predict(X_test), y_test)</pre><blockquote>SVM同樣可以用predict.proba_來顯示y 值 A/B類預測的機率</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*lVDEbE6Y_Z2t7L-TTn1D-g.png" /></figure><p>5. 最後同樣視覺化training好的分界線，可以看出SVM畫出的分界線較羅吉斯回歸來的漂亮(有最大Margin的特性)</p><pre>plot_decision_regions(X_train, np.array(y_train), clf = svm)</pre><pre>plt.xlabel(&quot;sepal length (cm) [standardlized]&quot;)<br>plt.ylabel(&quot;petal length (cm)&quot;)</pre><pre>plt.legend(loc = &quot;upper left&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*-r5Gx8QU8hjhfgpF8pP0IA.png" /></figure><p>參考至:</p><ol><li>[資料分析&amp;機器學習] 第3.3講：線性分類-邏輯斯回歸<a href="https://medium.com/jameslearningnote/%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%AC%AC3-3%E8%AC%9B-%E7%B7%9A%E6%80%A7%E5%88%86%E9%A1%9E-%E9%82%8F%E8%BC%AF%E6%96%AF%E5%9B%9E%E6%AD%B8-logistic-regression-%E4%BB%8B%E7%B4%B9-a1a5f47017e5">https://medium.com/jameslearningnote/%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%AC%AC3-3%E8%AC%9B-%E7%B7%9A%E6%80%A7%E5%88%86%E9%A1%9E-%E9%82%8F%E8%BC%AF%E6%96%AF%E5%9B%9E%E6%AD%B8-logistic-regression-%E4%BB%8B%E7%B4%B9-a1a5f47017e5</a></li><li>[資料分析&amp;機器學習] 第3.4講：支援向量機<br><a href="https://medium.com/jameslearningnote/%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%AC%AC3-4%E8%AC%9B-%E6%94%AF%E6%8F%B4%E5%90%91%E9%87%8F%E6%A9%9F-support-vector-machine-%E4%BB%8B%E7%B4%B9-9c6c6925856b">https://medium.com/jameslearningnote/%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%AC%AC3-4%E8%AC%9B-%E6%94%AF%E6%8F%B4%E5%90%91%E9%87%8F%E6%A9%9F-support-vector-machine-%E4%BB%8B%E7%B4%B9-9c6c6925856b</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82aa5e5edaf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在jupyter 上顯示圖片]]></title>
            <link>https://b5031631512567.medium.com/%E5%9C%A8jupyter-%E4%B8%8A%E9%A1%AF%E7%A4%BA%E5%9C%96%E7%89%87-eb149a7e7824?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb149a7e7824</guid>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 17:47:50 GMT</pubDate>
            <atom:updated>2020-04-26T17:47:50.351Z</atom:updated>
            <content:encoded><![CDATA[<pre>from IPython.display import Image<br>url = &quot;圖片路徑&quot;</pre><pre>display(Image(url = url, width = 400, height=400))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb149a7e7824" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Output當月累積個股資訊]]></title>
            <link>https://b5031631512567.medium.com/output%E7%95%B6%E6%9C%88%E7%B4%AF%E7%A9%8D%E5%80%8B%E8%82%A1%E8%B3%87%E8%A8%8A-7772e625ed5a?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/7772e625ed5a</guid>
            <category><![CDATA[web-crawler]]></category>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 19:18:04 GMT</pubDate>
            <atom:updated>2020-04-27T01:17:58.686Z</atom:updated>
            <content:encoded><![CDATA[<h3>當月/年累積個股資訊(爬蟲)</h3><blockquote><strong>因為證交所的網站有提供API，直接爬取股價資訊，就可以不用用selenium把EXCEL資料都下載下來再作input</strong></blockquote><blockquote><strong>這次就練習利用request/BeautifulSoup 爬取股票資訊，並用pandas圖表畫，再用matplotlib做個簡單的視覺化</strong></blockquote><p><strong>證交所股價可利用以下網址查詢:<br>(輸入日期&amp;股票代碼)</strong></p><pre><a href="https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&amp;date=">https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&amp;date=</a>&quot;+ date + &quot;&amp;stockNo=&quot;+ stock_number</pre><pre>date = 20200424<br>stcok number = 3037</pre><pre>import pandas_datareader as pdr<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime<br>import requests as req<br>from bs4 import BeautifulSoup <br>import json</pre><ul><li>設定pandas 顯示</li></ul><pre>pd.set_option(&quot;display.width&quot;, None)<br>pd.set_option(&quot;display.max_columns&quot;, None)<br>pd.set_option(&quot;display.max_rows&quot;, None)</pre><ul><li>用日期查找 “當月” 個股資訊</li></ul><pre>def craw_stock(stock_number, date):</pre><pre>url_stocl_info = &quot;<a href="https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&amp;date=">https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&amp;date=</a>&quot;+ date + &quot;&amp;stockNo=&quot;+ stock_number<br>    r = req.get(url_stocl_info)</pre><pre>soup = BeautifulSoup(r.text, &quot;html.parser&quot;)<br>    datas = soup.table.find_all(&quot;td&quot;)</pre><pre>stock_data = []<br>    for i in datas:<br>        stock_data.append(i.text)</pre><pre>s =[]<br>    for i in range(0,len(stock_data),9):<br>       s.append(stock_data[i:i+9])<br>    <br>    stock = pd.DataFrame(s, columns = s[0])<br>    stock = stock.drop(0, axis = 0)<br>    <br>    date = []<br>    for i in stock[&quot;日期&quot;]:<br>        date.append(str(int(i[:3])+1911) + i[3:])<br>    stock[&quot;日期&quot;] = date<br>    stock= stock.set_index(&quot;日期&quot;)    <br>    stock.index = pd.to_datetime(stock.index, format = &quot;%Y/%m/%d&quot;)<br>    <br>    stock[&quot;成交股數&quot;]= stock[&quot;成交股數&quot;].str.replace(&quot;,&quot;,&quot;&quot;)<br>    stock[&quot;成交金額&quot;]= stock[&quot;成交金額&quot;].str.replace(&quot;,&quot;,&quot;&quot;)<br>    stock[&quot;成交筆數&quot;]= stock[&quot;成交筆數&quot;].str.replace(&quot;,&quot;,&quot;&quot;)<br>    stock[&quot;漲跌價差&quot;]= stock[&quot;漲跌價差&quot;].str.replace(&quot;X&quot;,&quot;&quot;)<br>    <br>    stock.loc[:,[&#39;成交股數&#39;,&#39;成交金額&#39;,&#39;開盤價&#39;,&#39;最高價&#39;,&#39;最低價&#39;,&#39;收盤價&#39;,&#39;漲跌價差&#39;,&#39;成交筆數&#39;]] = stock.loc[:,[&#39;成交股數&#39;,&#39;成交金額&#39;,&#39;開盤價&#39;,&#39;最高價&#39;,&#39;最低價&#39;,&#39;收盤價&#39;,&#39;漲跌價差&#39;,&#39;成交筆數&#39;]].astype(float) <br>        <br>    return stock</pre><ul><li>Key in 欲爬取的股票代號&amp;時間</li></ul><pre>date = input(&quot;please key in date: &quot;)<br>stock_number = input(&quot;please key in stock number: &quot;)</pre><pre>stock_data = craw_stock(stock_number, date)</pre><blockquote>EX: 設定日期為20200424，股票代號3037</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*3_dKA6YUm010iN3YxQZAjQ.png" /></figure><ul><li>Output</li></ul><pre>new_date = []<br>    <br>for i in stock_data.index:<br>    new_date.append(i.date())<br>another_stock_data = stock_data.copy()<br>another_stock_data.index = new_date<br>another_stock_data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*yjynahUDbvehwvJctl-k5w.png" /></figure><ul><li>比較一下日成交量</li></ul><pre>another_stock_data.loc[:,[&quot;成交股數&quot;]].plot(kind = &quot;bar&quot;, figsize = (8,6))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*M6FL_7q-gmqrGXlGRNHdbQ.png" /></figure><ul><li>比較一下 開盤價/收盤價/最高價/最低價的價位分布</li></ul><pre>stock_data.loc[:,[&quot;開盤價&quot;,&quot;最高價&quot;,&quot;最低價&quot;,&quot;收盤價&quot;]].plot(kind = &quot;box&quot;,, figsize = (10,6))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*sjt0up9TjrVJZqBc4f_Zag.png" /></figure><ul><li>比較一下當月股價變化</li></ul><pre>stock_data.loc[:,[&quot;開盤價&quot;,&quot;最高價&quot;,&quot;最低價&quot;,&quot;收盤價&quot;]].plot(figsize = (12,8))<br>plt.ylabel(&quot;股價&quot;)<br>plt.title(stock_number)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*E535OTI1TS_yWIk9ogsOZw.png" /></figure><ul><li>表格呈現的時候也可以用顏色來區分漲幅</li></ul><pre>#改變顯示顏色<br>def displaycolor(value):<br>    if value &gt; 0:<br>        color = &quot;red&quot;<br>    elif value &lt; 0:<br>        color = &quot;green&quot;<br>    else:<br>        color = &quot;black&quot;<br>    return &quot;color: {}&quot;.format(color)</pre><pre>display_stock = another_stock_data.style.applymap(displaycolor, subset=[&quot;漲跌價差&quot;])<br>display_stock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*oZpDYskOIEC-b2DXe-MoUw.png" /></figure><blockquote><strong>可以更複雜一點，整合一下當年其他月的股價</strong></blockquote><p>(顯示設定年份 “累計至當月為止” 的個股的資訊)</p><pre>def find_year_month_info(year, month, stock_num):<br>    <br>    months =[]<br>    <br>    if month &gt;1:<br>        for i in range(2,int(month)+1):<br>            if i &lt; 10:<br>                months.append(str(year) + &quot;0&quot; + str(i) + &quot;01&quot;)<br>            else:<br>                months.append(str(year) + str(i) + &quot;01&quot;)<br>                <br>        first_month_info = craw_stock(str(stock_num), str(year)+&quot;0101&quot;)<br>    <br>        for month in months:<br>            each_month_info = craw_stock(str(stock_num), month)<br>            data = pd.concat([first_month_info,each_month_info], axis = 0)<br>            first_month_info = data      <br>            <br>        yearly_data = data<br>        <br>    else:<br>        month = str(year) + &quot;0101&quot;<br>        yearly_data = craw_stock(str(stock_num), month)<br>    <br>    return yearly_data</pre><ul><li>輸入股票資訊以及欲擷取年分</li></ul><pre>year = int(input(&quot;please key in a year: &quot;))<br>month = int(input(&quot;please key in a month: &quot;))<br>stock_num = int(input(&quot;please key in a stock number: &quot;))</pre><pre>yearly_stock_info = find_year_month_info(year,month,stock_num)<br>yearly_stock_info</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*lGgYJww06DWx8CillLMRTA.png" /></figure><ul><li>加入5日均價、10日均價、20日均價</li></ul><pre>week = yearly_stock_info[&quot;收盤價&quot;].rolling(window=5).mean()<br>month = yearly_stock_info[&quot;收盤價&quot;].rolling(window=10).mean()<br>season = yearly_stock_info[&quot;收盤價&quot;].rolling(window=20).mean()</pre><pre>yearly_stock_info[&quot;5日平均(收盤)&quot;] = week<br>yearly_stock_info[&quot;10日平均(收盤)&quot;] = month<br>yearly_stock_info[&quot;20日平均(收盤)&quot;] = season</pre><pre>yearly_stock_info</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3ZWLCz_s6wimBfT4bN4Aw.png" /></figure><ul><li>呈現5日線、10日線、20日線</li></ul><pre>yearly_stock_info.loc[:, [&quot;收盤價&quot;, &quot;5日平均(收盤)&quot;, &quot;10日平均(收盤)&quot;, &quot;20日平均(收盤)&quot;]].plot(figsize = (12,8))<br>plt.ylabel(&quot;股價&quot;)<br>plt.title(stock_num)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*uYWeDSdEls9gpsvwTZGNDg.png" /></figure><ul><li>將股價/成交量變化共同呈現</li></ul><pre>from matplotlib.dates import WeekdayLocator, DateFormatter, MonthLocator</pre><pre>x = yearly_stock_info.loc[:, [&quot;收盤價&quot;, &quot;5日平均(收盤)&quot;, &quot;10日平均(收盤)&quot;, &quot;20日平均(收盤)&quot;]]</pre><pre>fig,ax1 = plt.subplots(figsize = (12,8))</pre><pre>ax2 = ax1.twinx()</pre><pre>ax1.plot(x.index, x.values,&quot;-&quot;)<br>ax1.set_ylabel(&quot;價格&quot;)<br>ax1.legend([&quot;收盤價&quot;, &quot;5日平均(收盤)&quot;, &quot;10日平均(收盤)&quot;, &quot;20日平均(收盤)&quot;], loc = &quot;best&quot;)<br>ax1.set_ylim([0,50])</pre><pre>ax2.bar(x.index, yearly_stock_info.loc[:,&quot;成交股數&quot;]/10000)<br>ax2.set_ylabel(&quot;成交股數(萬張)&quot;)<br>ax2.set_ylim([0,20000])<br>ax2.legend([&quot;成交股數&quot;], loc = &quot;upper left&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*ReJ_TX09drBkaxF2NIQW0A.png" /></figure><blockquote><strong>改變日期顯示方式</strong></blockquote><pre>weekday_locator = WeekdayLocator(byweekday =(0), interval = 1)  #byweekday = (0) ==&gt;禮拜一為基準<br>ax2.xaxis.set_minor_locator(weekday_locator)<br>ax2.xaxis.set_minor_formatter(DateFormatter(&quot;%d\n%a&quot;))<br>ax2.xaxis.grid(True, &quot;minor&quot;)  #增加格線</pre><pre>ax2.xaxis.set_major_locator(MonthLocator())<br>ax2.xaxis.set_major_formatter(DateFormatter(&quot;\n\n\n%b\n%Y&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*yWeKK65qy_UbvakX37wKRQ.png" /></figure><ul><li>將成交價格和成交量分別用不同表格呈現(共用Y軸)</li></ul><pre>plt.style.use(&quot;seaborn-whitegrid&quot;)<br>sns.set(font = &quot;Microsoft JhengHei&quot;)</pre><pre>x1 = yearly_stock_info.loc[:, [&quot;收盤價&quot;, &quot;5日平均(收盤)&quot;, &quot;10日平均(收盤)&quot;, &quot;20日平均(收盤)&quot;]]</pre><pre>fig, (ax3,ax4), = plt.subplots(2,1, sharex = True ,sharey=False,figsize = (16,10))</pre><pre>ax3.plot(x1)<br>ax3.set_ylabel(&quot;價格&quot;)<br>ax3.legend([&quot;收盤價&quot;, &quot;5日平均(收盤)&quot;, &quot;10日平均(收盤)&quot;, &quot;20日平均(收盤)&quot;], loc = &quot;best&quot;)<br>ax3.set_ylim([20,50])</pre><pre>ax4.bar(x1.index, yearly_stock_info.loc[:,&quot;成交股數&quot;]/10000)<br>ax4.set_ylabel(&quot;成交股數(萬張)&quot;)<br>ax4.set_ylim([0,10000])<br>ax4.legend([&quot;成交股數&quot;], loc = &quot;upper right&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1_J7PxcacbGEmWcscTw5A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7772e625ed5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[每日股價查詢 (用sched來定時執行)]]></title>
            <link>https://b5031631512567.medium.com/%E6%AF%8F%E6%97%A5%E8%82%A1%E5%83%B9%E6%9F%A5%E8%A9%A2-%E7%94%A8sched%E4%BE%86%E5%AE%9A%E6%99%82%E5%9F%B7%E8%A1%8C-d9bd442ab134?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9bd442ab134</guid>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 18:17:40 GMT</pubDate>
            <atom:updated>2020-04-25T18:17:40.141Z</atom:updated>
            <content:encoded><![CDATA[<pre>from IPython.display import display, clear_output<br>from urllib.request import urlopen<br>import requests as req<br>import pandas as pd<br>from datetime import datetime<br>import sched<br>import time<br>import json</pre><pre>s = sched.scheduler(time.time, time.sleep)</pre><pre>def stock_table(stock_number_list):<br>    <br>    clear_output(wait=True)<br>    <br>    stock_num  = &quot;|&quot;.join(&quot;tse_{}.tw&quot;.format(i) for i in stock_number_list)<br>    <br>    url = &quot;<a href="http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=">http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=</a>&quot; + stock_num <br>    r = req.get(url)<br>    info  = json.loads(r.text)<br>    info = info[&quot;msgArray&quot;]<br>    <br>    info_index = [&#39;c&#39;,&#39;n&#39;,&#39;z&#39;,&#39;tv&#39;,&#39;v&#39;,&#39;o&#39;,&#39;h&#39;,&#39;l&#39;,&#39;y&#39;]<br>    columns = [&#39;股票代號&#39;,&#39;公司簡稱&#39;,&#39;當盤成交價&#39;,&#39;當盤成交量&#39;,&#39;累積成交量&#39;,&#39;開盤價&#39;,&#39;最高價&#39;,&#39;最低價&#39;,&#39;昨收價&#39;]<br>    <br>    <br>    stockinfo_table = pd.DataFrame(info, columns = info_index)<br>    stockinfo_table.columns = columns<br>    <br>    stockinfo_table = stockinfo_table.astype({&#39;當盤成交價&#39;: &quot;float&quot;, &#39;當盤成交量&#39;:&quot;int64&quot;, &#39;累積成交量&#39;:&quot;int64&quot;, &#39;開盤價&#39;:&quot;float&quot;, &#39;最高價&#39;:&quot;float&quot;, &#39;最低價&#39;:&quot;float&quot;,&#39;昨收價&#39;:&quot;float&quot;})<br>    <br>    stockinfo_table[&quot;漲跌幅&quot;] = (stockinfo_table[&quot;當盤成交價&quot;] - stockinfo_table[&quot;昨收價&quot;])/stockinfo_table[&quot;昨收價&quot;] * 100<br>    <br>    now = datetime.now()<br>    <br>    print(&quot;更新時間: &quot; + str(now.date()) +&quot; &quot;+ str(now.hour) + &quot;:&quot; +str(now.minute) + &quot;:&quot;+str(now.second))<br>    <br>    # 設定開始和結束時間<br>    start_time = datetime.strptime(str(now.date()) +&quot; 9:30&quot;, &quot;%Y-%m-%d %H:%M&quot;)<br>    end_time = datetime.strptime(str(now.date()) +&quot; 13:30&quot;, &quot;%Y-%m-%d %H:%M&quot;)<br>    <br>    s1 = stockinfo_table<br>    s1.insert(0,&quot;公司&quot;,s1[&quot;股票代號&quot;] + s1[&quot;公司簡稱&quot;])<br>    s1 = s1.drop([&quot;股票代號&quot;,&quot;公司簡稱&quot;],axis =1)<br>    <br>    s1 = s1.set_index(&quot;公司&quot;)<br>    <br>    display(s1)<br>    <br>    if now &gt; start_time and now &lt; end_time:<br>        s.enter(5,0, stock_table, argument=(stock_number_list,))</pre><pre># 輸入股票代號<br>stock_list = [&quot;1101&quot;,&quot;2449&quot;,&quot;3037&quot;]</pre><pre># 每秒定時器<br>s.enter(1, 0, stock_table, argument = (stock_list,))<br>s.run()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9bd442ab134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Numpy隨機資料產ㄕㄥ]]></title>
            <link>https://b5031631512567.medium.com/numpy%E9%9A%A8%E6%A9%9F%E8%B3%87%E6%96%99%E7%94%A2%E3%84%95%E3%84%A5-1e3407a0c366?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e3407a0c366</guid>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 18:22:10 GMT</pubDate>
            <atom:updated>2020-04-24T06:48:37.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>Numpy隨機資料生成</h3><p><strong>以下針對numpy產生資料做紀錄:</strong></p><ol><li>np.arange()</li><li>np.linspace()</li><li>np.random.rand()</li><li>np.random.randn()</li><li>np.random.randint()</li><li>np.random.normal()</li></ol><h3>np.arange()</h3><p>在設定範圍內依照特定間距產生樣本</p><blockquote>np.arange(start, stop, step)</blockquote><pre><strong>np.arange(10)</strong></pre><pre>array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])</pre><pre><strong>np.arange(1,10,1.15)</strong></pre><pre>array([1.  , 2.15, 3.3 , 4.45, 5.6 , 6.75, 7.9 , 9.05])</pre><h3>np.linspace()</h3><p>在設定範圍內隨機產生特定個數樣本</p><blockquote>np.linspace(start, stop, numbers = 50)</blockquote><pre><strong>np.linspace(2,20,12)</strong></pre><pre>array([ 2.        ,  3.63636364,  5.27272727,  6.90909091,  8.54545455,<br>       10.18181818, 11.81818182, 13.45454545, 15.09090909, 16.72727273,<br>       18.36363636, 20.        ])</pre><h3><strong>np.random.rand()</strong></h3><p>在[0, 1)之間隨機建立樣本(可能是負的或正的，可能大於一或小於一), 也可以直接依照矩陣數量建立樣本矩陣</p><blockquote>np.random.rand(size=None)</blockquote><pre><strong>np.random.rand(4)</strong></pre><pre>array([0.82895873, 0.24789485, 0.05861842, 0.67981728])<br></pre><pre><strong>np.random.rand(4,3)</strong></pre><pre>array([[0.50697565, 0.33304797, 0.57181477],<br>       [0.61532069, 0.14069479, 0.22535965],<br>       [0.46405704, 0.11240661, 0.37105515],<br>       [0.49260754, 0.77442024, 0.62665992]])</pre><h3>np.random.randn()</h3><p>在標準正態分佈中取樣本, 也可以直接依照矩陣數量建立樣本矩陣</p><blockquote>np.random.randn(size=None)</blockquote><pre><strong>np.random.randn(4)</strong></pre><pre>array([-0.31134112,  0.08473262,  0.60517773,  0.10242074])</pre><pre><strong>np.random.randn(4,3)</strong></pre><pre>array([[-0.78873302,  1.55817292, -1.68795836],<br>       [ 0.09835133,  0.09360053,  1.24971226],<br>       [-1.01054862,  1.09350517, -0.16274011],<br>       [-0.0268381 ,  1.4226099 ,  0.32185495]])<br></pre><pre><strong>sns.set_style(&quot;darkgrid&quot;)<br>sns.distplot(pd.DataFrame(np.random.randn(1000)), bins = 30, kde = False)<br>plt.show()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*7ySH-YcPRNtsIAe9I8T-1A.png" /></figure><h3>np.random.randint()</h3><p>在設定範圍內隨機產生樣本(整數)</p><blockquote>np.random.randint(low, high=None, size=None)</blockquote><pre><strong>np.random.randint(4, size=10)</strong></pre><pre>array([0, 1, 2, 3, 0, 0, 1, 1, 2, 1])</pre><pre><strong>np.random.randint(1,50, size=15)</strong></pre><pre>array([37,  7,  6, 24, 24, 14, 41, 10,  1, 11, 10, 13, 17, 47, 47])</pre><h3>np.random.normal()</h3><p>在設定範圍內隨機產生樣本(整數)</p><blockquote>np.random.normal(loc=0.0, scale=1.0, size=None)</blockquote><ul><li>loc: 此機率分布的均值(float)</li><li>scale: 此機率分布的標準差(float)，代表機率分布的寬度</li><li>size: 輸出的樣本數(default = None，只輸出一個值)<br>scale: 此機率分布的標準差(float)，代表機率分布的寬度</li></ul><pre><strong>np.random.normal(size = 4)  #產生平均數0,標準差為1的4個樣本</strong></pre><pre>array([-0.76789012, -1.39233309,  1.30984173, -0.47902428])</pre><pre><strong>np.random.normal(size = (4,4))  #產生平均數0,標準差為1的4*4個樣本矩陣</strong></pre><pre>array([[ 0.98596023,  0.61075608,  2.99441743,  0.39507854],<br>       [-1.59725249, -0.72849313,  0.61931494, -0.09978018],<br>       [-0.87905493, -1.65510712,  1.18838466,  1.2847209 ],<br>       [-0.13504899, -0.48032731, -1.22022779,  1.25957313]])</pre><pre><strong>np.random.normal(1,4,size = 1000) #產生平均數1,標準差為4的1000個樣本<br>sns.distplot(np.random.normal(1,4,size = 1000), bins = 20)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*anmvqK1DD7UGqyGIrfffIw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e3407a0c366" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matplotlib 圓餅圖]]></title>
            <link>https://b5031631512567.medium.com/matplotlib-%E5%9C%93%E9%A4%85%E5%9C%96-dc31e1e84725?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc31e1e84725</guid>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 07:36:48 GMT</pubDate>
            <atom:updated>2020-04-23T07:36:48.522Z</atom:updated>
            <content:encoded><![CDATA[<pre>data = [1500,2000,3000,15000,15000]<br>category = [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;]<br>color = [&quot;red&quot;, &quot;lightblue&quot;, &quot;pink&quot;, &quot;green&quot;, &quot;orange&quot;]<br>separeted = (0, 0, 0, 0.3, 0.3)</pre><pre>plt.pie(data,                            <strong><em>#資料數值</em></strong><br>        labels = category,               <strong><em>#數值標籤</em></strong><br>        autopct = &quot;%.0f%%&quot;,              <strong><em>#數值百分比(留到百分比幾位)</em></strong><br>        colors = color                   <strong><em>#顏色</em></strong><br>        explode = separeted,             <strong><em>#是否有突出資料</em></strong><br>        radius = 1.5,                    <strong><em>#半徑</em></strong><br>        pctdistance = 0.65,              <strong><em>#數值與圓餅圖的圓心距離</em></strong><br>        center = (-10,0),                <strong><em>#圓心座標</em></strong><br>        textprops = {&quot;fontsize&quot; : 12},   <strong><em>#文字大小<br></em></strong>        labeldistance = 1.1,             <strong><em>#標籤顯示位置</em></strong><br>        shadow = True)                   <strong><em>#是否有陰影</em></strong></pre><pre>plt.axis(&#39;equal&#39;)      <em>#讓圓餅圖比例相等 </em>          <br>plt.legend(loc = &quot;center right&quot;)<br>plt.title(&quot;圓餅圖&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*7X1thPXArO0-a6lFDoTbUw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc31e1e84725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matplotlib 多圖顯示(subplot/subplot2grid)]]></title>
            <link>https://b5031631512567.medium.com/matplotlib-%E5%A4%9A%E5%9C%96%E9%A1%AF%E7%A4%BA-subplot-subplot2grid-85ad12eea1d8?source=rss-4ad22807e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ad12eea1d8</guid>
            <dc:creator><![CDATA[hello this is Hung Min!]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 06:15:50 GMT</pubDate>
            <atom:updated>2020-06-11T17:06:14.855Z</atom:updated>
            <content:encoded><![CDATA[<h3>Matplotlib 多圖顯示(subplot/subplot2grid/Subplots)</h3><p>以下紀錄三種方法:</p><ol><li>plt.subplot()</li><li>plt.subplot2grid()</li><li>plt.subplots()</li></ol><h3><strong>plt.subplot()</strong></h3><blockquote><strong>均勻做圖</strong></blockquote><p>plt.subplot(2,2,1): 表示把窗口分成2行2列， 並指定位置於位置1<br>plt.subplot(2,2,1): 表示把窗口分成2行2列， 並指定位置於位置2</p><pre>plt.subplot(2,2,1) <br>plt.plot([0,1],[0,2])</pre><pre>plt.subplot(2,2,2)<br>plt.plot([0,1],[0,4])</pre><pre>plt.subplot(2,2,3)<br>plt.plot([0,1],[0,5])</pre><pre>plt.subplot(2,2,4)<br>plt.plot([0,1],[0,6])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*s1g7tTHqbDZhZ6Y6qGhRKw.png" /></figure><blockquote><strong>不均勻做圖(大小不同)</strong></blockquote><p>plt.subplot(3,5,(1,2)): 表示把窗口分成3行5列， 並指定位置於位置1~2<br>plt.subplot(3,5,(3,5)): 表示把窗口分成3行5列， 並指定位置於位置3~5</p><p>plt.subplot(3,4,6): 表示把窗口重新分成3行4列， 並指定位置於位置6(會用新的窗口重新計算位置)<br>plt.subplot(3,4,(7,8)): 表示把窗口重新分成3行4列， 並指定位置於位置7~8(會用新的窗口重新計算位置)</p><pre>plt.subplot(3,5,(1,2))<br>pltplt.subplot(3,5,(3,5))<br>plt.tight_layout()</pre><pre>plt.subplot(3,4,6)<br>plt.subplot(3,4,(7,8))<br>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*xi7uxwKZZULMJnovWGcz6Q.png" /></figure><h3>plt.subplot2grid()</h3><p>plt.subplot2grid((3,3),(0,0), colspan = 3)</p><ol><li>使用plt.subplot2grid()做圖</li><li>(3,3): 表示把窗口分成3行3列</li><li>(0,0): 表示從未置(0,0)開始做圖</li><li>colspan: column範圍</li><li>rowspan: row範圍</li></ol><pre>ax1 = plt.subplot2grid((3,3),(0,0), colspan = 3)<br>ax2 = plt.subplot2grid((3,3),(1,0), colspan = 2, rowspan = 1)<br>ax3 = plt.subplot2grid((3,3),(1,2), colspan = 1, rowspan = 2)</pre><pre>ax4 = plt.subplot2grid((3,3),(2,0), colspan = 1, rowspan = 1)<br>ax4.scatter([1, 2], [2, 2])<br>ax4.set_xlabel(&#39;ax4_x&#39;)<br>ax4.set_ylabel(&#39;ax4_y&#39;)</pre><pre>ax5 = plt.subplot2grid((3,3),(2,1), colspan = 1, rowspan = 1)</pre><pre>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*XKYG3n_rhkVYqDLMhDx3ww.png" /></figure><h3>plt.subplots()</h3><ol><li>使用plt.subplot2s()做圖</li><li>(2,2): 表示把窗口分成2行2列</li><li>ax1, ax2 代表第一行由左至右的兩個位置(座標(1,1), (1,2))</li><li>ax3, ax4 代表第二行由左至右的兩個位置(座標(2,1), (2,2))</li><li>sharex: 是否共享座標軸<em>X (使用相同座標軸)</em></li><li>sharey: 是否共享座標軸 <em>(使用相同座標軸)</em></li></ol><pre>f, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2, 2, sharex = False ,sharey=False,figsize=(10,6))</pre><pre>data = np.arange(1,10,0.5)</pre><pre>df1 =  pd.DataFrame(data)<br>df2 =  pd.DataFrame(data**2)<br>df3 =  pd.DataFrame(data**3)<br>df4 =  pd.DataFrame(data**4)</pre><pre>ax1.plot(df1)<br>ax2.plot(df2)<br>ax3.plot(df3)<br>ax4.plot(df4)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*0lmug8rykX-QN90vZOqoYw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ad12eea1d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>