程式碼:
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
startday = '2021-11-03'
endday = '2021-11-12'
ticker_list = ['2303.TW','2610.TW','2618.TW']
data = pd.DataFrame(columns=ticker_list)
for ticker in ticker_list:
data[ticker] = yf.download(ticker, startday,endday)['Adj Close']
ans=data.head()
data.plot(figsize=(8,12))
plt.legend()
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title("股票7天內收盤價變化折線圖", fontsize=16)
plt.ylabel('收盤價', fontsize=14)
plt.xlabel('日期', fontsize=14)
plt.grid(which="major", color='k', linestyle='-.', linewidth=0.5)
fmt_day = mdates.DayLocator() # provides a list of days
plt.gca().xaxis.set_major_locator(fmt_day)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.show()```
不必那麼複雜。
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
startday = '2021-11-03'
endday = '2021-11-12'
ticker_list = ['2303.TW','2610.TW','2618.TW']
data = pd.DataFrame(columns=ticker_list)
for ticker in ticker_list:
data[ticker] = yf.download(ticker, startday,endday)['Adj Close']
data.head()
# 這一行就夠了
data.plot(kind='line', figsize=(8,12))