I am trying to build a web app for practice with Dash where it takes input as a start_date & end_date from a Dataframe of SPY, and shows cumulative returns in a form of line-graph & gauge.
it shows error as TypeError: Invalid comparison between dtype=datetime64[ns] and str.
I would appreciate any help,PS: I still need to code for gauge output, but its showing me error with graph output as well.
Here’s my code:
import pandas as pd
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
import datetime as dt
import yfinance as yf
spy = yf.download("SPY", start= "2000-01-01", end = "2023-12-05")
spy = spy.reset_index()
from dash import Dash, html, dcc
import dash_daq as daq
from dash.dependencies import Output, Input
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
load_figure_template("SLATE")
app = Dash(__name__,external_stylesheets=[dbc.themes.SLATE])
app.layout = html.Div([
dbc.Row([html.H1("SPY Returns during dates selected", style = {'text-align': 'center'})]),
#html.Br,
dbc.Row([
dbc.Col([
dcc.DatePickerRange(
id = "date_picker",
min_date_allowed = spy["Date"].min(),
max_date_allowed = spy["Date"].max(),
initial_visible_month = spy["Date"].min(),
start_date = spy["Date"].min(),
end_date = spy["Date"].max())
]),
dbc.Col([
html.Div([
html.H3("Total Returns"),
daq.Gauge(
id = "Our Gauge",
label = "Returns",
value = 100,
color={"gradient":True,"ranges":{"green":[0,6],"yellow":[6,8],"red":[8,10]}},
labelPosition = "bottom")
])
]),
dbc.Row([
html.Div([
html.H3("Graph showing the returns"),
# html.Br,
dcc.Graph(id = 'Graph'),
])
])
])
])
@app.callback(
[Output("Our Gauge","Gauge")],
[Output("Graph", "figure")],
[Input("date_picker", "start_date"),Input("date_picker", "end_date")]
)
def plot_graph(start_date, end_date):
df = spy[spy["Date"].between("start_date","end_date")]
df["returns"] = df["Adj Close"].pct_change(1)
df["cum_returns"] = (1 + df["returns"].cumprod())*100
figure = px.line(df,
x = df["Date"],
y = df["cum_returns"])
return figure
if __name__ == "__main__":
app.run(debug = True, port = 2022)