Spaces:
Sleeping
Sleeping
| import pandas as pd | |
| import openai | |
| import gradio as gr | |
| import requests | |
| import yfinance as yf | |
| import json # Import json module | |
| import os | |
| openai.api_key = os.getenv('yek_oaipen') | |
| def stock_price(ticker): | |
| stock = yf.Ticker(ticker) | |
| price = stock.history(period='1d') | |
| latest_price = price['Close'].iloc[0] | |
| cashflow = stock.cashflow | |
| return latest_price,cashflow | |
| functions =[ | |
| { | |
| "name": "stock_price", | |
| "description": "Get the current stock price", | |
| # "strict": True, | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "symbol": { | |
| "type": "string", | |
| "description": "The stock symbol" | |
| } | |
| }, | |
| "additionalProperties": False, | |
| "required": [ | |
| "symbol" | |
| ] | |
| } | |
| } | |
| ] | |
| #function will be used in the below code. structure is copied from the documentation. | |
| def stock_chat(user_message): | |
| messages=[] | |
| messages.append({"role": "user", "content": user_message}) | |
| messages.append({"role": "assistant", "content": "You are a stock information bot. Answer only related to stock information."}) | |
| # Sending Initial Message to OpenAI | |
| response = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", | |
| temperature = 0, | |
| max_tokens=50, | |
| top_p=0.5, | |
| frequency_penalty=0, | |
| presence_penalty=0, | |
| messages=messages, | |
| functions=functions | |
| ) | |
| #Handling Function Calls and Fetching stocks Data | |
| try: | |
| function_call = response['choices'][0]['message']['function_call'] | |
| arguments = eval(function_call['arguments']) | |
| # arguments = json.loads(function_call['arguments']) | |
| # Fetch stocks data using the extracted arguments | |
| stock_data = stock_price(arguments['symbol']) | |
| # Append the function call and stocks data to the messages | |
| messages.append({"role": "assistant", "content": None, "function_call": {"name": "stock_price", "arguments": str(arguments)}}) | |
| messages.append({"role": "function", "name": "stock_price", "content": str(stock_data)}) | |
| #magic of llm | |
| response = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", | |
| messages=messages | |
| ) | |
| return response['choices'][0]['message']['content'] | |
| except Exception as e: | |
| return "I'm here to provide stocks information. Please ask me questions related to Stock Market." | |
| # Gradio Interface | |
| iface = gr.Interface( | |
| fn=stock_chat, | |
| inputs=gr.Textbox(lines=2, placeholder="Ask me about stock info like - prices, financial, cashflow...", label="Stock Queries"), | |
| outputs=gr.Textbox(label="Your stock query result using Openai advanced model"), | |
| title="Stock Information Assistant By Parvez Alam", | |
| description="Ask me about stock prices and financial data.", | |
| theme="default" | |
| ) | |
| iface.launch() | |