Skip to content

Commit

Permalink
Update to most recent develop version
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianJacta committed Oct 4, 2024
1 parent 17c5733 commit efa5b77
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 27 deletions.
90 changes: 65 additions & 25 deletions src/main_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,77 +7,114 @@


def get_stock_data(ticker, start, end):
ticker_data = yf.download(ticker, start, end) # downloading the stock data from START to TODAY
ticker_data = yf.download(
ticker, start, end
) # downloading the stock data from START to TODAY
ticker_data.reset_index(inplace=True) # put date in the first column
ticker_data['Date'] = pd.to_datetime(ticker_data['Date']).dt.tz_localize(None)
ticker_data["Date"] = pd.to_datetime(ticker_data["Date"]).dt.tz_localize(None)
return ticker_data


def get_data_from_range(state):
print("GENERATING HIST DATA")
start_date = state.start_date if type(state.start_date)==str else state.start_date.strftime("%Y-%m-%d")
end_date = state.end_date if type(state.end_date)==str else state.end_date.strftime("%Y-%m-%d")
start_date = (
state.start_date
if type(state.start_date) == str
else state.start_date.strftime("%Y-%m-%d")
)
end_date = (
state.end_date
if type(state.end_date) == str
else state.end_date.strftime("%Y-%m-%d")
)

state.data = get_stock_data(state.selected_stock, start_date, end_date)
if len(state.data) == 0:
notify(state, "error", f"Not able to download data {state.selected_stock} from {start_date} to {end_date}")
notify(
state,
"error",
f"Not able to download data {state.selected_stock} from {start_date} to {end_date}",
)
return
notify(state, 's', 'Historical data has been updated!')
notify(state, 'w', 'Deleting previous predictions...')
state.forecast = pd.DataFrame(columns=['Date', 'Lower', 'Upper'])
notify(state, "s", "Historical data has been updated!")
notify(state, "w", "Deleting previous predictions...")
state.forecast = pd.DataFrame(columns=["Date", "Lower", "Upper"])


def create_candlestick_chart(data):
fig = go.Figure()
fig.add_trace(go.Candlestick(x=data['Date'],
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name='Candlestick'))
fig.update_layout(margin=dict(l=30, r=30, b=30, t=30), xaxis_rangeslider_visible=False)
fig.add_trace(
go.Candlestick(
x=data["Date"],
open=data["Open"],
high=data["High"],
low=data["Low"],
close=data["Close"],
name="Candlestick",
)
)
fig.update_layout(
margin=dict(l=30, r=30, b=30, t=30), xaxis_rangeslider_visible=False
)
return fig


def generate_forecast_data(data, n_years):
# FORECASTING
df_train = data[['Date', 'Close']]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"}) # This is the format that Prophet accepts
df_train = data[["Date", "Close"]]
df_train = df_train.rename(
columns={"Date": "ds", "Close": "y"}
) # This is the format that Prophet accepts

m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=n_years * 365)
fc = m.predict(future)[['ds', 'yhat_lower', 'yhat_upper']].rename(columns={"ds": "Date", "yhat_lower": "Lower", "yhat_upper": "Upper"})
fc = m.predict(future)[["ds", "yhat_lower", "yhat_upper"]].rename(
columns={"ds": "Date", "yhat_lower": "Lower", "yhat_upper": "Upper"}
)
print("Process Completed!")
return fc


def forecast_display(state):
notify(state, 'i', 'Predicting...')
notify(state, "i", "Predicting...")
state.forecast = generate_forecast_data(state.data, state.n_years)
notify(state, 's', 'Prediction done! Forecast data has been updated!')
notify(state, "s", "Prediction done! Forecast data has been updated!")

if len(forecast) == 0 or len(data) == 0:
return -1
return int((forecast.loc[len(forecast)-1, 'Lower'] - forecast.loc[len(data), 'Lower'])/forecast.loc[len(data), 'Lower']*100)
return int(
(forecast.loc[len(forecast) - 1, "Lower"] - forecast.loc[len(data), "Lower"])
/ forecast.loc[len(data), "Lower"]
* 100
)


def pessimistic_forecast_display(forecast, data):
if len(forecast) == 0 or len(data) == 0:
return -1
return int((forecast.loc[len(forecast)-1, 'Lower'] - forecast.loc[len(data), 'Lower'])/forecast.loc[len(data), 'Lower']*100)
return int(
(forecast.loc[len(forecast) - 1, "Lower"] - forecast.loc[len(data), "Lower"])
/ forecast.loc[len(data), "Lower"]
* 100
)


def optimistic_forecast_display(forecast, data):
if len(forecast) == 0 or len(data) == 0:
return -1
return int((forecast.loc[len(forecast)-1, 'Upper'] - forecast.loc[len(data), 'Upper'])/forecast.loc[len(data), 'Upper']*100)
return int(
(forecast.loc[len(forecast) - 1, "Upper"] - forecast.loc[len(data), "Upper"])
/ forecast.loc[len(data), "Upper"]
* 100
)


if __name__ == "__main__":
# Parameters for retrieving the stock data
start_date = "2015-01-01"
end_date = date.today().strftime("%Y-%m-%d")
selected_stock = 'AAPL'
selected_stock = "AAPL"
n_years = 1

#### Getting the data, make initial forcast and build a front end web-app with Taipy GUI
Expand All @@ -89,7 +126,9 @@ def optimistic_forecast_display(forecast, data):
partial_md = "<|{forecast}|table|>"
dialog_md = "<|{show_dialog}|dialog|partial={partial}|title=Forecast Data|on_action={lambda state: state.assign('show_dialog', False)}|>"

page = dialog_md + """<|toggle|theme|>
page = (
dialog_md
+ """<|toggle|theme|>
<|container|
# Stock Price **Analysis**{: .color-primary} Dashboard
Expand Down Expand Up @@ -170,6 +209,7 @@ def optimistic_forecast_display(forecast, data):
<br/>
"""
)

# Run Taipy GUI
gui = Gui(page)
Expand Down
5 changes: 3 additions & 2 deletions src/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
taipy==3.1
yfinance==0.1.96
numpy==1.24.2
taipy==4.0.0.dev6
yfinance==0.2.41
holidays==0.24
prophet==1.1.2
plotly

0 comments on commit efa5b77

Please sign in to comment.