|
程式碼如同書中內容,但運行後卻開啟了https://www.msn.com/zh-tw/?cobrand=acer17win10.msn.com&ocid=ACERDHP17&pc=ACTE這個網頁,想請教為何如此? def twodigit(n): if(n < 10): retstr ='0' + str(n) else: retstr = str(n) return retstr
def convertDate(date): str1 = str(date) yearstr = str1[:3] realyear = str(int(yearstr) + 1911) realdate = realyear + str1[4:6] + str1[7:9] return realdate
import requests import json, csv import pandas as pd import os import time import matplotlib.pyplot as plt from plotly.graph_objs import Scatter, Layout from plotly.offline import plot
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei'] plt.rcParams['axes.unicode_minus'] = False
pd.options.mode.chained_assignment = None #取消顯示pandas資料重設警告
urlbase = 'https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=2021' urltail = '01&stockNo=2317&_=1653659486856' filepath = 'stockyear2021.csv'
if not os.path.isfile(filepath): #如果檔案不存在則建立檔案 for i in range(1,13): url_twse = urlbase + twodigit(i) + urltail res = requests.get(url_twse) jdata = json.loads(res.text)
outputfile = open(filepath, 'a', newline='', encoding='utf-8') #開啟儲存檔案 outputwriter = csv.writer(outputfile) if i==1: outputwriter.writerow(jdata['fields']) for dataline in (jdata['data']): outputwriter.writerow(dataline) time.sleep(0.5) outputfile.close()
pdstock = pd.read_csv(filepath, encoding='utf-8') for i in range(len(pdstock['日期'])): #轉換日期為西元格式 pdstock['日期'][i] = convertDate(pdstock['日期'][i])
pdstock['日期'] = pd.to_datetime(pdstock['日期'])
data = [ Scatter(x=pdstock['日期'], y=pdstock['收盤價'], name='收盤價'), Scatter(x=pdstock['日期'], y=pdstock['最低價'], name='最低價'), Scatter(x=pdstock['日期'], y=pdstock['最高價'], name='最高價') ]
plot({"data": data, "layout": Layout(title='2021年個股統計圖')}, auto_open=True) |