File size: 5,254 Bytes
92648a6
 
 
 
 
 
 
da243b7
 
 
 
 
 
92648a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da243b7
 
 
 
92648a6
 
 
22f9e5d
 
 
92648a6
1a1204d
22f9e5d
 
1a1204d
 
 
22f9e5d
 
1a1204d
 
 
22f9e5d
 
1a1204d
22f9e5d
 
1a1204d
 
 
 
22f9e5d
1a1204d
 
 
 
 
 
22f9e5d
11e8c44
 
 
 
da243b7
11e8c44
 
 
22f9e5d
 
1a1204d
22f9e5d
 
da243b7
1a1204d
11e8c44
92648a6
11e8c44
92648a6
11e8c44
 
 
da243b7
11e8c44
92648a6
 
 
 
da243b7
 
 
 
92648a6
 
 
 
11e8c44
1a1204d
 
 
22f9e5d
1a1204d
 
22f9e5d
1a1204d
22f9e5d
 
1a1204d
22f9e5d
 
 
 
 
 
1a1204d
22f9e5d
1a1204d
22f9e5d
 
 
1a1204d
92648a6
 
 
 
 
 
 
 
 
 
 
 
22f9e5d
92648a6
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import gradio as gr
import pandas as pd
from datetime import datetime, timedelta
import requests
import json
import os

def verify_api_key():
    api_key = os.environ.get('MISTRAL_API_KEY')
    if not api_key:
        return "ERROR: Mistral API key not found in environment variables"
    return "API key found"

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:
        api_key = os.environ.get('MISTRAL_API_KEY')
        if not api_key:
            return "Error: Mistral API key not found. Please add it to the environment variables."

        # Get last 10 days of data
        last_10_days = df.tail(10)
        
        # Calculate current price (last close)
        current_price = last_10_days.iloc[-1]['Close']
        
        # Format data for prompt
        data_str = f"""Based on the following NIFTY 50 price data for the last 10 days, provide only support levels, resistance levels, target price, and trading setup. Format exactly as shown below:

Support Levels:
- S1: [price] (brief reason)
- S2: [price] (brief reason)
- S3: [price] (brief reason)

Resistance Levels:
- R1: [price] (brief reason)
- R2: [price] (brief reason)
- R3: [price] (brief reason)

Today's Target Price:
- Target ([direction]): [price] (brief reason)

Trading Setup:
- Direction: [Bullish/Bearish]
- Entry Price Range: [range]
- Stop Loss: [price]
- Risk/Reward Ratio: [ratio]

Current price: {current_price}

Data:
"""
        for _, row in last_10_days.iterrows():
            data_str += f"{row['Date']}: O:{row['Open']} H:{row['High']} L:{row['Low']} C:{row['Close']}\n"

        url = "https://api.mistral.ai/v1/chat/completions"
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }
        
        data = {
            "model": "mistral-small",
            "messages": [
                {"role": "system", "content": "You are a price action trader. Provide only the requested levels and setup information in the exact format specified. Do not add any additional analysis or explanation."},
                {"role": "user", "content": data_str}
            ],
            "temperature": 0.7,
            "max_tokens": 500
        }
        
        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():
    api_status = verify_api_key()
    if api_status.startswith("ERROR"):
        return pd.DataFrame(), api_status
    
    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:
    with gr.Column():
        gr.Markdown("# NIFTY 50 Levels and Setup")
        
        # Add refresh button
        refresh_btn = gr.Button("Refresh Data", variant="primary")
        
        # Add outputs
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### Market Data")
                output_table = gr.Dataframe(
                    headers=["Date", "Open", "High", "Low", "Close", "Volume"],
                    wrap=True
                )
            
            with gr.Column(scale=1):
                gr.Markdown("### Trading Levels")
                analysis_output = gr.Textbox(
                    label="Levels and Setup",
                    lines=15,
                    elem_classes="analysis"
                )
    
    # 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],
    )

# Launch the app
demo.launch()