todo
import yfinance as yf
from datetime import datetime, timedelta
import pandas as pd
import plotly.graph_objects as go
from sklearn.linear_model import LinearRegression
display=pd.options.display
display.max_columns=None
display.max_rows=None
display.width=None
display.max_colwidth=None
current=datetime.now()
ticker='GC=F'
ma1=3#20
ma2=5#60
df = yf.download(ticker, '1970-01-01', current, auto_adjust=True)
fig=go.Figure()
fig.add_trace(
go.Scatter(x=df.index, y=df['Close'].values, mode='lines',
name=f'{ticker} 實際股價',
line=dict(color='royalblue', 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)
)
fig.update_layout(layout)
train=df[['Close']][:]
train['s1']=train['Close'].rolling(window=ma1).mean()
train['s2']=train['Close'].rolling(window=ma2).mean()
train['next_day_price'] = train['Close'].shift(-1)
train=train.dropna()
x_train=train[['s1','s2']].values
y_train=train['next_day_price'].values
model=LinearRegression()
model.fit(x_train, y_train)
pred=df
pred['s1']=pred['Close'].rolling(window=ma1).mean()
pred['s2']=pred['Close'].rolling(window=ma2).mean()
pred=pred.dropna()
pred['predict_price']=model.predict(pred[['s1', 's2']].values)
s=(pred.tail(1).index + timedelta(days=1))[0]#.values[0]
dates=pd.date_range(s, periods=10)
for d in dates:
c = pred.tail(1)["predict_price"].values[0]
pred.loc[d] = [0, 0, 0, c, 0, 0, 0, 0]
s1 = pred.tail(ma1)['Close'].mean()
s2 = pred.tail(ma2)['Close'].mean()
p = model.predict([[s1,s2]])[0]
pred.iloc[pred.shape[0] - 1, 5] = s1
pred.iloc[pred.shape[0] - 1, 6] = s2
pred.iloc[pred.shape[0] - 1, 7] = p
pred['predict_price']=pred['predict_price'].shift(1)
pred=pred.dropna()
fig.add_trace(
go.Scatter(x=pred.index, y=pred['predict_price'].values, mode='lines',
name=f'{ticker} 預測股價',
line=dict(color='orange', width=1)
)
)
print(pred.tail(20))
fig.show()
todo