Python查股價
請使用 Colab 練習
條件篩選股票
import requests
from io import StringIO
import pandas as pd
import numpy as np
#查詢日期
datestr = '20220819'
r = requests.post('http://www.twse.com.tw/exchangeReport/MI_INDEX?response=csv&date=' + datestr + '&type=ALL')
df = pd.read_csv(StringIO("\n".join([i.translate({ord(c): None for c in ' '})
for i in r.text.split('\n')
if len(i.split('",')) == 17 and i[0] != '='])), header=0 , thousands=",")
#條件篩選,5<本益比<15 且 收盤價<300 且 (成交股數/1000)>10000張
df.loc[(pd.to_numeric(df['本益比'], errors='coerce') < 15) & (pd.to_numeric(df['本益比'], errors='coerce') > 5) & (pd.to_numeric(df['收盤價'], errors='coerce') < 300) & (pd.to_numeric(df['成交股數'], errors='coerce')/1000 > 10000)]
畫個股1,5,20,60日平均線
#先安裝yfinance套件,只要裝一次即可
!pip install yfinance
#導入套件
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#設定爬蟲股票代號
sid = '2330'
#設定爬蟲時間,以日為單位
start = datetime.datetime.now() - datetime.timedelta(days=180)
end = datetime.date.today()
#導入pandas_datareader
from pandas_datareader import data
#導入fix_yahoo_finance
import yfinance as yf
#把資料抓到本機
yf.pdr_override()
# 取得股票資料,上櫃就改成.TWO
stock_yf = yf.download(sid+'.TW', start, end)
stock_yf.tail(10)
#如果加上如下這段就會畫出圖形
#線型圖,收盤價、5日均線、20日均線、60日均線
stock_yf['Adj Close'].plot(figsize=(16, 8))
stock_yf['Adj Close'].rolling(window=5).mean().plot(figsize=(16, 8), label='5_Day_Mean')
stock_yf['Adj Close'].rolling(window=20).mean().plot(figsize=(16, 8), label='20_Day_Mean')
stock_yf['Adj Close'].rolling(window=60).mean().plot(figsize=(16, 8), label='60_Day_Mean')
#顯示側標
plt.legend(loc='upper right', shadow=True, fontsize='x-large')
#顯示標題
plt.title(sid)
畫個股收盤價及成交量
#先安裝twstock套件,只要裝一次即可
!pip install twstock
import twstock as t
import pandas as p
import plotly.express as e
#在('')裡面 打股票代碼
stockID = '2330'
stock = t.Stock(stockID)
date = stock.date #日期
price = stock.price #收盤價
amount = stock.capacity #成交量
data = p.DataFrame({'日期':date, '收盤價':price})
result = e.line(data, x='日期', y='收盤價', title=stockID+'股價')
result.show()
data = p.DataFrame({'日期':date, '成交量':amount})
result = e.bar(data, x='日期', y='成交量', title=stockID+'成交量')
result.show()
畫個股K線圖
#先安裝twstock套件,只要裝一次即可
!pip install twstock
#m分鐘: 1m
#h小時: 1h
#d天: 1d
#wk週: 1wk
#mo月: 1mo
#y年: 1y
#period期間
#選項: 1d 5d 1mo 3mo 6mo 1y 2y 5y 10y
#interval間隔多久
#選項: 1m 2m 5m 15m 30m 60m 90m
import yfinance as y
import pandas as p
import plotly.graph_objects as g
#上市股: '股票代碼.tw'
#上櫃股: '股票代碼.two'
stockID = '2330.tw'
stock = y.download(stockID, period='1d', interval='1m')
data = stock.reset_index()
data.columns = ['現在時間', '開盤價', '最高價', '最低價', '收盤價', '調整後收盤價', '成交量']
data['現在時間'] = p.to_datetime(data['現在時間'].dt.strftime('%Y-%m-%d %H:%M'))
data['成交量'] //= 1000 #把單位從成交股數換成成交張數
result = g.Figure()
#成交量的圖
result.add_trace(
g.Bar(
name = '成交量',
x = data['現在時間'],
y = data['成交量'],
yaxis = 'y2',
marker_color = '#99ccff'
)
)
#k線圖
result.add_trace(
g.Candlestick(
name = '',
x = data['現在時間'],
open = data['開盤價'],
high = data['最高價'],
low = data['最低價'],
close = data['收盤價'],
increasing_line_color = '#fd5047',
increasing_fillcolor = '#f29696',
decreasing_line_color = '#3d9970',
decreasing_fillcolor = '#91c2b3'
)
)
result.update_layout(
title = stockID,
hovermode = 'x unified', #滑鼠停在圖上的時候會有資訊卡
#xaxis_rangeslider_visible = False, #x軸座標的小圖,可以用來滑動上面的圖
yaxis = dict(
title = '股價'
),
yaxis2 = dict(
overlaying = 'y',
visible = False
),
font = dict(
size = 10
)
)
result.show()
畫個股K,D線
Python wrapper for TA-Lib (http://ta-lib.org/)
https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html
#Colab安裝Talib的解法
https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html
#Colab安裝Talib的解法
!wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
!tar -xzvf ta-lib-0.4.0-src.tar.gz
%cd ta-lib
!./configure --prefix=/usr
!make
!make install
!pip install Ta-Lib
import talib
#先安裝yfinance套件,只要裝一次即可
!pip install yfinance
#導入套件
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#設定爬蟲股票代號
sid = '2330'
#設定爬蟲時間,以日為單位
start = datetime.datetime.now() - datetime.timedelta(days=180)
end = datetime.date.today()
#導入pandas_datareader
from pandas_datareader import data
#導入fix_yahoo_finance
import yfinance as yf
#finance
import talib
#把資料抓到本機
yf.pdr_override()
# 取得股票資料,上櫃就改成.TWO
stock_yf = yf.download(sid+'.TW', start, end)
#算出K,D值
stock_yf['k'], stock_yf['d'] = talib.STOCH(stock_yf['High'],
stock_yf['Low'],
stock_yf['Close'],
fastk_period=5,
slowk_period=3,
slowk_matype=0,
slowd_period=3,
slowd_matype=0)
#算出RSI值
stock_yf['rsi5']=talib.RSI(stock_yf['Close'], timeperiod=5)
stock_yf['rsi10']=talib.RSI(stock_yf['Close'], timeperiod=10)
stock_yf["upper"],stock_yf["middle"],stock_yf["lower"] = talib.BBANDS(stock_yf["Close"], timeperiod=20, nbdevup=2.1, nbdevdn=2.1, matype=0)
stock_yf
#畫出KD線
stock_yf['k'].rolling(window=1).mean().plot(figsize=(16, 8), label='k')
stock_yf['d'].rolling(window=1).mean().plot(figsize=(16, 8), label='d')
#畫出rsi5及rsi10線
stock_yf['rsi5'].rolling(window=1).mean().plot(figsize=(16, 8), label='rsi5')
stock_yf['rsi10'].rolling(window=1).mean().plot(figsize=(16, 8), label='rsi10')
#顯示側標
plt.legend(loc='upper left', shadow=True, fontsize='x-large')
#顯示標題
plt.title(sid)