Py.Cafe

maartenbreddels/

ai-dataframe-explore-langchain

Interactive Stock Performance Analysis with Langchain, Plotly and Solara

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# check out https://solara.dev/ for documentation
# or https://github.com/widgetti/solara/
# And check out https://py.cafe/maartenbreddels for more examples
import solara
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
from langchain_openai import ChatOpenAI
import pandas as pd
import plotly.express as px
from typing import List

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



stocks = solara.reactive(['AAPL','TSLA'])

@solara.component
def Page():
    with solara.Card(
        "Stocks assistant",
    ):
        solara.SelectMultiple(values=stocks, all_values=sorted(df_stocks['Ticker'].unique()), label="")
        # solara.FigurePlotly(fig)

        async def ask_ai():
            if openai_api_key is None:
                return "`OPENAI_API_KEY` is not set"

            # Use pandas agent to analyze the dataset
            df = df_stocks[df_stocks['Ticker'].isin(stocks.value)]
            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"]
        
        # re-runs only when the stocks changes
        result = solara.lab.use_task(ask_ai, dependencies=[stocks.value])

        if result.pending:
            solara.ProgressLinear()
            solara.Markdown("*Asking AI to analyse the performance of the stock*")
        
        else:
            df = df_stocks[df_stocks['Ticker'].isin(stocks.value)]
            print(df.head())
            fig = px.line(df, x='Date', y='High', color='Ticker')
            display(fig)
            solara.Markdown(result.value)
requirements.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
solara==1.43
https://py.cafe/files/maartenbreddels/tiktoken-demo/tiktoken-0.7.0-cp312-cp312-pyodide_2024_0_wasm32.whl
pandas
openai
jiter @ https://py.cafe/files/maartenbreddels/pandas-dash-stock-trends/jiter-0.6.1-cp312-cp312-pyodide_2024_0_wasm32.whl
langchain
langchain-openai
langchain-experimental
dash_bootstrap_components
tabulate
httpx


greenlet # mock