Py.Cafe

maartenbreddels/

pandas-dash-stock-trends

Stock Trends with Pandas and Dash

DocsPricing
  • app.py
  • jiter-0.6.1-cp311-cp311-emscripten_3_1_46_wasm32.whl
  • jiter-0.6.1-cp312-cp312-pyodide_2024_0_wasm32.whl
  • 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
try:
    import pycafe
    reason = """We need an OpenAI API key to generate text.

    Go to [OpenAI](https://platform.openai.com/account/api-keys) to get one.

    Or read [this](https://www.rebelmouse.com/openai-account-set-up) article for
    more information.

    Or read more [about secrets on PyCafe](/docs/secrets)
    """

    openai_api_key = pycafe.get_secret("OPENAI_API_KEY", reason=reason)
except ModuleNotFoundError:
    openai_api_key = os.environ.get("OPENAI_API_KEY")

llm = ChatOpenAI(model_name="gpt-4", openai_api_key=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

# import langchain_core
# config = langchain_core.runnables.config.RunnableConfig(max_concurrency=1)




@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,
                                          allow_dangerous_code=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.")
    return response["output"]

import asyncio
requirements.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
https://py.cafe/files/maartenbreddels/tiktoken-demo/tiktoken-0.7.0-cp312-cp312-pyodide_2024_0_wasm32.whl
dash
pandas
openai
jiter @ https://py.cafe/files/maartenbreddels/pandas-dash-stock-trends/jiter-0.6.1-cp312-cp312-pyodide_2024_0_wasm32.whl
# < 1.40  # newer versions require jiter
langchain
langchain-openai
langchain-experimental
greenlet # mock
dash_bootstrap_components
tabulate
httpx