初學者的Python金融分析日記 EP2 – 將抓到的資料整理成資料庫

簡單教學 – 建立一個sqlite檔案,整理抓到的csv檔案

這個簡單的教學分為三個部份,第一個部份我們會利用glob以及pandas套件來讀取我們抓來的2014-2019年的台股資料,第二個部份為建立一個sqlite檔案來存入我們的資料庫,第三個部份為進一步整理為用個股來分的資料庫

最後的檔案可以在這邊取得

時間資料庫

股票代號資料庫

第一部份 讀取我們抓到的資料

當我們用EP1的程式抓取大量的表單之後,如果我們簡單用迴圈加to_csv方法,會發現現在我們的資料夾裡面已經堆滿的大量的csv檔案了,我們要如何使用程式來整理我們的檔案勒?如果用pandas一個一個讀入顯然很沒有效率,這邊我們使用glob套件一次讀入所有的csv檔案吧

import pandas as pd
import sqlite3
import glob

'''
glob套件是用來查找符合特定規則的文件名,跟我們用搜尋跳出來的結果差不多,這邊我們查詢副檔名為csv的檔案並存為一個列表的形式。
'''
All_csv_file = glob.glob('*.csv')

第二部份 創建資料庫,存成以時間為一張張表的資料庫

我們這邊會使用sqlite來存取我們抓下來的股價資料

  • python內建sqlite套件,我們無須特安裝
  • 支援完整sql語法查詢我們的資料
  • 使用以及轉移方便,一個資料庫就像一個本地文件一樣

在這邊,我們直接使用DataFrame提供把DataFrame存入Sql資料庫當作表格的方法。

dbname = 'TWStock.db'
#連接到我們的資料庫,如果沒有的話會重新建一個
db = sqlite3.connect(dbname)
%%time
for file_name in All_csv_file:
    pd.read_csv(file_name).iloc[:,1:].to_sql(file_name.replace('.csv',''),db,if_exists='replace')

在這邊我們直接用迴圈將每一個抓到的每日收盤資料當作一張張的表存進去sqlite資料庫檔案裡,我們對應的表單名就像”20140623″這樣的格式。

如何讀取資料庫的表格

我們這邊簡單介紹如何讀取sqlite檔案裡面的表格

pd.read_sql(con=db,sql='SELECT * FROM "20180611"')

我們可以利用pandas.DataFrame下內建的讀取sql的方法直接讀取,其中con參數要選我們連接的資料庫物件,sql參數要用字串寫想要執行的sql命令,這邊SELECT * 代表選全部的欄位,FROM “2o180611″代表從這張表單拉出資料。

這樣基本上我們就建好資料庫了,但如果我們整理股票代號當做我們資料庫的表單怎麼做?

第三部份 整理出以個股為一張張表的資料庫

total_df = pd.DataFrame()
for date in dates_list:
    df = pd.read_sql(con=db,sql='SELECT * FROM' + ' "'+ date +'"')
    df['Date'] = date
    total_df = total_df.append(df)

在這邊,我們先把每天收盤資料拉出來,大概有1200多交易天資料(我抓到20146月左右),所以這邊會執行1200多次拉資料的動作,接下來合成一張大表(total_df)

total_df的shape(1203195,18),120萬行,18欄位。 接下來我們建立一個新的資料庫並取名叫’TWStock_2’。

dbname_2 = 'TWStock_2'
db2 = sqlite3.connect(dbname_2)

接下來我們利用groupby方法將我們的大表轉換成用股票代號來分的小表,並將一個個的小表存進去資料庫內

total_dict = dict(tuple(total_df.groupby('證券代號')))
for key in total_dict.keys():
    df = total_dict[key].iloc[:,2:]
    df['Date'] = pd.to_datetime(df['Date'])
    df = df.sort_values(by=['Date'])
    df.to_sql(key,db2,if_exists='replace')
Share

2 thoughts on “初學者的Python金融分析日記 EP2 – 將抓到的資料整理成資料庫

  1. I’m also commenting to let you be aware of of the cool discovery my child encountered checking your blog. She came to understand a lot of details, including how it is like to have a marvelous coaching heart to get folks easily fully grasp a variety of complicated issues. You actually did more than my desires. I appreciate you for delivering such good, dependable, edifying and also cool guidance on that topic to Ethel.

  2. Thank you for every one of your hard work on this web page. My aunt really loves making time for research and it is simple to grasp why. We all notice all relating to the powerful ways you render vital tips and tricks via your website and therefore welcome response from website visitors on this topic while our own simple princess is without question understanding so much. Take pleasure in the rest of the year. Your performing a very good job.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *