全文共1559字,預計學習時長9分鐘
圖源:pixabay
無論數據科學家還是機器學習工程師,部署數據科學項目都是他們所需要的一項至關重要的能力。傳統部署機器學習模型的方法是利用Django、Flask等已經建立好的框架,然而這種方法非常耗時,常常令人望而卻步。有沒有簡單一點的方法呢?
本文是基於筆者在YouTubevideo上發佈的同名視頻創作的,二者搭配食用效果更佳。
股票web app概述
現在我們要構建一個顯示股價與股票成交量的簡單web app,會用到Python中的streamlit和yfinance兩個庫。這個app理論上是要利用yfinance庫從雅虎財經調取市場歷史數據,然後把數據保存在數據框架中,最後作爲streamlit 的輸入參數顯示出線形圖表。
圖源:unsplash
安裝必備庫
在這篇教程中,我們將用到兩個需要安裝的Python庫,streamlit 和yfinance。通過下面的pip install命令可以輕鬆地安裝streamlit:
pip install streamlit
同理按照以下命令完成 yfinance的安裝:
pip install yfinance
web app代碼
這次構建web app的代碼一共不到20行,如果不算註釋的話代碼只有14行。
import yfinance as yf
import streamlit as st
st.write("""
# Simple StockPrice App
Shown are the stockclosing price and volume of Google!
""")
# https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75
#define the tickersymbol
tickerSymbol ='GOOGL'
#get data on thisticker
tickerData = yf.Ticker(tickerSymbol)
#get the historicalprices for this ticker
tickerDf = tickerData.history(period='1d', start='2010-5-31', end='2020-5-31')
# Open HighLowClose Volume Dividends StockSplits
st.line_chart(tickerDf.Close)
st.line_chart(tickerDf.Volume)
代碼逐行解釋
現在,我們來詳細看看上面這些代碼:
· 第一行和第二行——輸入yfinance,命名爲yf同時輸入streamlit,命名爲st。
· 四至七行——用 st.write() 函數輸出文本內容,輸出文本爲markdown格式。
· 九至十六行——用yfinance庫從雅虎財經中調取市場歷史數據。
· 十一行——定義股票代碼爲 GOOGL。
· 十三行——用yf.Ticker()函數創建tickerData變量,顧名思義該變量爲股票代碼數據。需要注意的是tickerData是一個股票代碼對象,如果把tickerData當作命令運行可以得到這樣的輸出 yfinance.Ticker object <GOOGL>。
· 十五行——創建tickerDf 數據框架,定義日期範圍(從2010年5月31日到2020年5月31日)以及時段(1天)。
· 十八行到十九行——用st.line_chart()函數畫出線性圖表(收盤價格數據來自十五行代碼中定義的tickerDf數據框架中的收盤與成交量數據)。
運行web app
代碼保存在名爲myapp.py的文件之後,啓動命令提示符(或者是微軟Windows系統裏的Power Shell),運行下面的命令:
streamlit run myapp.py
然後可以看到以下信息:
> streamlit run myapp.pyYou can now view your Streamlit app in yourbrowser.Local URL: http://localhost:8501
Network URL: http://10.0.0.11:8501
不久一個網頁窗口就會彈出,直接跳去如下所示的http://localhost:8501這個創建好的web app。
股價web app截屏
Bingo!你已經成功用Python創建了自己的第一個web app!
圖源:unsplash
自定義web app
以上是最基本的,如果你想讓自定義web app變得更有趣一點呢?
import yfinance as yf
import streamlit as st
st.write("""
# Simple StockPrice App
Shown are the stock**closing price** and ***volume*** of Google!
""")
#https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75
#define the tickersymbol
tickerSymbol ='GOOGL'
#get data on thisticker
tickerData = yf.Ticker(tickerSymbol)
#get the historicalprices for this ticker
tickerDf = tickerData.history(period='1d', start='2010-5-31', end='2020-5-31')
# Open HighLowClose Volume Dividends StockSplits
st.write("""
## Closing Price
""")
st.line_chart(tickerDf.Close)
st.write("""
## Volume
""")
st.line_chart(tickerDf.Volume)
讓我們花點時間來理解上面的代碼:
· 第六行——注意這裏需在“closing price” 前後各用兩個星號來加粗“closing price” ,如下所示:**closingprice**。還要注意“volume”斜體加粗,前後各用三個星號,如下所示:***volume***。
· 十八至二十行和二十二至二十五行——在收盤價格和成交量圖表上方加入一個markdown格式的標題。
更新後的web app截屏
成功了!現在這個web app可以自動更新了。構建你的第一個web app,就是這麼簡單,快去上手操作一下吧!
一起分享AI學習與發展的乾貨
歡迎關注全平臺AI垂類自媒體 “讀芯術”
(添加小編微信:dxsxbb,加入讀者圈,一起討論最新鮮的人工智能科技哦~)