Plotly 台灣股市分析

安裝套件

本例需安裝套件

pip install plotly yfinance

完整代碼

如前所說的,Plotly 在使用上非常困難,所以才會有plotly-express的產生。底下的代碼, 就是使用plotly展現台股每日大盤指數,可見得在撰寫上的確很麻煩。

#!/usr/bin/python3
import plotly
import yfinance as yf
from datetime import datetime
import plotly.graph_objects as go
import numpy as np
file='plotly28.html'

current=datetime.now()
df=yf.download("^TWII", '2025-01-01', current, auto_adjust=True)
df.columns=df.columns.droplevel(1)

x=range(df.shape[0])
y=df['Close'].values.reshape(-1)
f=np.poly1d(np.polyfit(x,y,10))
reg=f(x)
trace1=go.Scatter(
    x=df.index,
    y=df['Close'],
    mode='lines+markers',
    name='大盤指數',
    line=dict(color='royalblue', width=2)
)
trace2=go.Scatter(
    x=df.index,
    y=reg,
    mode='lines',
    name='迴歸線',
    line=dict(color='orange', width=2)
)
layout=go.Layout(
    dragmode="pan",
    title_text="台灣股市分析",
    xaxis=go.layout.XAxis(
        rangeselector=dict(
            buttons=[
                dict(count=1,label="1 month",step="month",stepmode="backward"),
                dict(count=6,label="6 month",step="month",stepmode="backward"),
                dict(count=1,label="1 year",step="year",stepmode="backward"),
                dict(count=1,label="1 day",step="day",stepmode="todate"),
                dict(step="all")
            ]
        ),
        rangeslider=dict(visible=True),
        #type="date", 有沒有都沒差
    ),
    yaxis=dict(fixedrange=False)
)
datas=[trace1, trace2]
fig=go.Figure(data=datas, layout=layout)
fig.show()

plotly.offline.plot(fig,filename=file, auto_open=False)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *