Py.Cafe

adamschroeder.m/

pandas-dash-stock-trends

Stock Trends with Pandas and Dash

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
from langchain_openai import ChatOpenAI
from dash import Dash, html, dcc, callback, Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd

# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")  # Create a .env file and write: OPENAI_API_KEY="insert-your-openai-token"
llm = ChatOpenAI(model_name="gpt-4", openai_api_key="")

# data from https://www.kaggle.com/datasets/nelgiriyewithana/world-stock-prices-daily-updating
df_stocks = pd.read_csv("https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/LangChain/Agents/Pandas-Agent/World-Stock-Prices-Data-small.csv")
df_stocks['Date'] = pd.to_datetime(df_stocks['Date'], utc=True)
df_stocks['Date'] = df_stocks['Date'].dt.date


app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = [
    dcc.Markdown("# Pandas Agent in Dash App"),
    dcc.Dropdown(id='stock-picker',
                 options=sorted(df_stocks['Ticker'].unique()),
                 value=['AAPL','TSLA'], multi=True),
    dcc.Graph(id='line-chart', figure={}),
    dcc.Loading(dcc.Markdown(id='answer-space'),
                overlay_style={"visibility":"visible", "opacity": .5, "backgroundColor": "white"},
                custom_spinner=html.H2(
                    ["Pandas AI analyzing data", dbc.Spinner(color="danger")])
                )
]


@callback(
    Output('line-chart', 'figure'),
    Input('stock-picker', 'value')
)
def activate_agent(stocks_chosen):
    # Create the figure
    df = df_stocks[df_stocks['Ticker'].isin(stocks_chosen)]
    print(df.head())
    fig = px.line(df, x='Date', y='High', color='Ticker')
    return fig


@callback(
    Output('answer-space', 'children'),
    Input('stock-picker', 'value')
)
def activate_agent(stocks_chosen):
    # Use pandas agent to analyze the dataset
    df = df_stocks[df_stocks['Ticker'].isin(stocks_chosen)]
    agent = create_pandas_dataframe_agent(llm=llm, 
                                          df=df,
                                          max_iterations=2,
                                          verbose=True,
                                          agent_type="tool-calling",
                                          handle_parsing_errors=True)
    response = agent.invoke("What is the dataset telling us about the performance of the stocks? "
                            "Only consider the 'High' and the 'Ticker' columns. "
                            "Please provide a summary at the end.")
    print(response)
    return response["output"]