Spaces:
Sleeping
Sleeping
import gradio as gr | |
import pandas as pd | |
from datetime import datetime, timedelta | |
import requests | |
import json | |
import os | |
def fetch_nifty_data(): | |
try: | |
end_date = datetime.now() | |
start_date = end_date - timedelta(days=15) | |
url = f"https://query1.finance.yahoo.com/v8/finance/chart/%5ENSEI?period1={int(start_date.timestamp())}&period2={int(end_date.timestamp())}&interval=1d" | |
headers = { | |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' | |
} | |
response = requests.get(url, headers=headers) | |
data = response.json() | |
timestamps = data['chart']['result'][0]['timestamp'] | |
quote = data['chart']['result'][0]['indicators']['quote'][0] | |
df = pd.DataFrame({ | |
'Date': [datetime.fromtimestamp(ts).strftime('%Y-%m-%d') for ts in timestamps], | |
'Open': quote['open'], | |
'High': quote['high'], | |
'Low': quote['low'], | |
'Close': quote['close'], | |
'Volume': quote['volume'] | |
}) | |
numeric_columns = ['Open', 'High', 'Low', 'Close'] | |
df[numeric_columns] = df[numeric_columns].round(2) | |
return df | |
except Exception as e: | |
print(f"Error fetching data: {str(e)}") | |
return pd.DataFrame() | |
def get_mistral_analysis(df): | |
try: | |
# Get last 10 days of data | |
last_10_days = df.tail(10) | |
# Format data for prompt | |
data_str = "this is the last 10 days data for nifty index, Open\tHigh\tLow\tClose\n" | |
for _, row in last_10_days.iterrows(): | |
data_str += f"{row['Open']}\t{row['High']}\t{row['Low']}\t{row['Close']}\n" | |
data_str += "so i need you to give me the setup for today by priceaction levels" | |
# Mistral API endpoint | |
url = "https://api.mistral.ai/v1/chat/completions" | |
headers = { | |
"Content-Type": "application/json", | |
"Authorization": f"Bearer {os.environ.get('MISTRAL_API_KEY')}" | |
} | |
data = { | |
"model": "mistral-tiny", | |
"messages": [{"role": "user", "content": data_str}] | |
} | |
response = requests.post(url, headers=headers, json=data) | |
if response.status_code == 200: | |
return response.json()['choices'][0]['message']['content'] | |
else: | |
return f"Error: {response.status_code} - {response.text}" | |
except Exception as e: | |
return f"Error getting analysis: {str(e)}" | |
def show_nifty_data_and_analysis(): | |
df = fetch_nifty_data() | |
analysis = get_mistral_analysis(df) if not df.empty else "Unable to fetch data" | |
return df, analysis | |
# Create Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("# NIFTY 50 Analysis with Mistral AI") | |
gr.Markdown("Displays the last 15 days of trading data and AI analysis for NIFTY 50 index") | |
# Add refresh button | |
refresh_btn = gr.Button("Refresh Data and Analysis") | |
# Add outputs | |
with gr.Row(): | |
with gr.Column(): | |
gr.Markdown("### Historical Data") | |
output_table = gr.Dataframe() | |
with gr.Column(): | |
gr.Markdown("### Mistral AI Analysis") | |
analysis_output = gr.Textbox(label="Price Action Analysis", lines=10) | |
# Set up refresh button click event | |
refresh_btn.click( | |
fn=show_nifty_data_and_analysis, | |
outputs=[output_table, analysis_output], | |
) | |
# Initial load of data | |
demo.load( | |
fn=show_nifty_data_and_analysis, | |
outputs=[output_table, analysis_output], | |
) | |
demo.launch() |