如何撈取台美股所有的股號的資料並儲存於SQLite? Part 1

閱讀時間約 4 分鐘
  • 文內如有投資理財相關經驗、知識、資訊等內容,皆為創作者個人分享行為。
  • 有價證券、指數與衍生性商品之數據資料,僅供輔助說明之用,不代表創作者投資決策之推介及建議。
  • 閱讀同時,請審慎思考自身條件及自我決策,並應有為決策負責之事前認知。
  • 方格子希望您能從這些分享內容汲取投資養份,養成獨立思考的能力、判斷、行動,成就最適合您的投資理財模式。

在此系列文章,我們將討論如何在Google Colab的環境下,撈取所有台美股的股票代碼,並獲取相關細節,最後將獲取的資訊存取於SQLite資料庫中。

raw-image

在此篇文章中,我們先來探討如何獲取所有的股票代碼。



步驟1

  • stocksymbol註冊帳號並獲取API金鑰。
  • 於Colab筆記本中安裝stocksymbol。
!pip install stocksymbol

步驟2

  • 在存取於Google Drive中的SQLite資料庫Stock.db中建立資料表Tickers。
import sqlite3

con = sqlite3.connect('/content/drive/MyDrive/data/Stock.db')

cursor = con.cursor()

query = """
CREATE TABLE "Tickers"
(
[symbol] varchar(50) NOT NULL,
[longName] varchar(255) ,
[exchange] varchar(255) ,
[market] varchar(255),
PRIMARY KEY(symbol)
)
"""

cursor.execute(query)

con.commit()

cursor.close()

步驟3

  • 開始對於所有股票代碼進行撈取並轉換成DataFrame。
from stocksymbol import StockSymbol

api_key = 'Your API Key'
ss = StockSymbol(api_key)

# get symbol list based on market
symbol_list_us = ss.get_symbol_list(market="US")
symbol_list_tw = ss.get_symbol_list(market="TW")

import pandas as pd

df_us = pd.DataFrame(symbol_list_us)
df_tw = pd.DataFrame(symbol_list_tw)

步驟4

  • 將獲取的訊息存入Stock.db中的資料表Tickers。
con = sqlite3.connect('/content/drive/MyDrive/data/Stock.db')

for row in df_us.to_records(index=False):
con.execute(" INSERT INTO Tickers (symbol, longName, exchange, market) VALUES (?, ?, ? ,?) ", (str(row[0]),str(row[2]), str(row[3]) , str(row[4])) )
con.commit()

for row in df_tw.to_records(index=False):
con.execute(" INSERT INTO Tickers (symbol, longName, exchange, market) VALUES (?, ?, ? ,?) ", (str(row[0]),str(row[2]), str(row[3]) , str(row[4])) )
con.commit()

我們獲取一萬多筆資料,在接下來的文章,我們將會對此資料進行像是PE, moving average等相關資料的撈取。

raw-image



Thank you and Enjoy it! You can check this for English version!

Enjoy it! If you want to support Informula, you can buy us a coffee here :)

𝗕𝘂𝘆 𝗺𝗲 𝗮 𝗰𝗼𝗳𝗳𝗲𝗲

Thank you and more to come :)


6會員
17內容數
Informula 作為上班族的臨時急救包,介紹一些簡單的程式工具、資料處理、數據分析、網路爬蟲應用等。
留言0
查看全部
發表第一個留言支持創作者!