Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
import snowflake.connector
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
from decimal import Decimal
|
| 7 |
+
from datetime import date, datetime
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# Initialize OpenAI client
|
| 11 |
+
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
|
| 12 |
+
|
| 13 |
+
def fetch_trades_of_the_day():
|
| 14 |
+
"""
|
| 15 |
+
Fetches RSI data from Snowflake, calculates future return percentages based on a lead value,
|
| 16 |
+
and returns the data as a formatted JSON string.
|
| 17 |
+
|
| 18 |
+
Parameters:
|
| 19 |
+
- horizon (int): Number of days to use in the lead function to calculate future return. Default is 21.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
- json_data (str): Formatted JSON string containing the RSI data.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def custom_json_serializer(obj):
|
| 26 |
+
""" Custom JSON serializer for handling date objects and Decimal types """
|
| 27 |
+
if isinstance(obj, (datetime, date)):
|
| 28 |
+
return obj.isoformat() # Convert date/datetime to ISO format
|
| 29 |
+
elif isinstance(obj, Decimal):
|
| 30 |
+
return float(obj) # Convert Decimal to float
|
| 31 |
+
raise TypeError(f"Type {type(obj)} not serializable")
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
# Establish connection to Snowflake
|
| 35 |
+
conn = snowflake.connector.connect(
|
| 36 |
+
user=userdata.get('SNOWFLAKE_USER'),
|
| 37 |
+
password=userdata.get('SNOWFLAKE_PW'),
|
| 38 |
+
account=userdata.get('SNOWFLAKE_ACCOUNT'),
|
| 39 |
+
warehouse=userdata.get('SNOWFLAKE_WH'),
|
| 40 |
+
database=userdata.get('SNOWFLAKE_DB'),
|
| 41 |
+
schema='RESEARCHDATA'
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Define the query
|
| 45 |
+
query = """SELECT
|
| 46 |
+
TICKER,
|
| 47 |
+
RSI_CURRENT,
|
| 48 |
+
RSI_CONDITION,
|
| 49 |
+
CONSECUTIVE_DAYS_IN_RSI_CONDITION,
|
| 50 |
+
HISTORICAL_OCCURRENCES,
|
| 51 |
+
MEDIAN_FORWARD_5DAY_RETURN_PERCENT,
|
| 52 |
+
AVG_FORWARD_5DAY_RETURN_PERCENT,
|
| 53 |
+
POSITIVE_RATE,
|
| 54 |
+
NEGATIVE_RATE
|
| 55 |
+
|
| 56 |
+
FROM researchdata.RSI_TRADE_OF_THE_DAY
|
| 57 |
+
|
| 58 |
+
ORDER BY trade_rank;"""
|
| 59 |
+
|
| 60 |
+
# Execute the query and fetch data
|
| 61 |
+
cur = conn.cursor()
|
| 62 |
+
rows = cur.execute(query).fetchall()
|
| 63 |
+
columns = [desc[0] for desc in cur.description] # Get column names
|
| 64 |
+
|
| 65 |
+
# Close the cursor and connection
|
| 66 |
+
cur.close()
|
| 67 |
+
conn.close()
|
| 68 |
+
|
| 69 |
+
# Convert the rows into a list of dictionaries (for JSON serialization)
|
| 70 |
+
result = [dict(zip(columns, row)) for row in rows]
|
| 71 |
+
|
| 72 |
+
# Convert the result to a formatted JSON string, with the custom serializer
|
| 73 |
+
json_data = json.dumps(result, indent=4, default=custom_json_serializer)
|
| 74 |
+
|
| 75 |
+
return json_data
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"Failed to connect to Snowflake: {e}")
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
# Function to interact with the OpenAI assistant
|
| 82 |
+
def interact_with_assistant(user_input):
|
| 83 |
+
thread = client.beta.threads.create()
|
| 84 |
+
|
| 85 |
+
client.beta.threads.messages.create(
|
| 86 |
+
thread_id=thread.id,
|
| 87 |
+
role="user",
|
| 88 |
+
content=user_input,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
run = client.beta.threads.runs.create(
|
| 92 |
+
thread_id=thread.id,
|
| 93 |
+
assistant_id='asst_WeygFo0phjmDVfjzyM9zktgl', # Replace with your actual assistant ID
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
while run.status != 'completed':
|
| 97 |
+
run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
|
| 98 |
+
|
| 99 |
+
if run.status == 'requires_action':
|
| 100 |
+
tool_outputs = []
|
| 101 |
+
for tool_call in run.required_action.submit_tool_outputs.tool_calls:
|
| 102 |
+
if tool_call.function.name == "fetch_trades_of_the_day":
|
| 103 |
+
output = fetch_trades_of_the_day()
|
| 104 |
+
tool_outputs.append({"tool_call_id": tool_call.id, "output": output})
|
| 105 |
+
|
| 106 |
+
client.beta.threads.runs.submit_tool_outputs(
|
| 107 |
+
thread_id=thread.id,
|
| 108 |
+
run_id=run.id,
|
| 109 |
+
tool_outputs=tool_outputs
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
messages = client.beta.threads.messages.list(thread_id=thread.id)
|
| 113 |
+
return messages.data[0].content[0].text.value
|
| 114 |
+
|
| 115 |
+
# Gradio interface
|
| 116 |
+
iface = gr.Interface(
|
| 117 |
+
fn=interact_with_assistant,
|
| 118 |
+
inputs="text",
|
| 119 |
+
outputs="text",
|
| 120 |
+
title="Stock Market Assistant",
|
| 121 |
+
description="Ask questions about the stock market and get insights based on RSI data."
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
iface.launch()
|