Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,12 +11,16 @@ def verify_api_key():
|
|
11 |
return "ERROR: Mistral API key not found in environment variables"
|
12 |
return "API key found"
|
13 |
|
14 |
-
def
|
15 |
try:
|
16 |
end_date = datetime.now()
|
17 |
-
start_date = end_date - timedelta(days=
|
18 |
|
19 |
-
|
|
|
|
|
|
|
|
|
20 |
|
21 |
headers = {
|
22 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
@@ -45,46 +49,54 @@ def fetch_nifty_data():
|
|
45 |
print(f"Error fetching data: {str(e)}")
|
46 |
return pd.DataFrame()
|
47 |
|
48 |
-
def
|
49 |
try:
|
50 |
api_key = os.environ.get('MISTRAL_API_KEY')
|
51 |
if not api_key:
|
52 |
return "Error: Mistral API key not found. Please add it to the environment variables."
|
53 |
|
54 |
-
# Get last
|
55 |
-
|
56 |
|
57 |
-
# Calculate current price
|
58 |
-
current_price =
|
|
|
|
|
59 |
|
60 |
# Format data for prompt
|
61 |
-
data_str = f"""
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
- S1: [price] (brief reason)
|
65 |
-
- S2: [price] (brief reason)
|
66 |
-
- S3: [price] (brief reason)
|
67 |
|
68 |
-
|
69 |
-
-
|
70 |
-
-
|
71 |
-
-
|
|
|
72 |
|
73 |
-
|
74 |
-
-
|
|
|
|
|
|
|
75 |
|
76 |
-
Trading Setup:
|
77 |
-
-
|
78 |
-
- Entry Price Range:
|
79 |
-
- Stop Loss:
|
80 |
-
-
|
|
|
81 |
|
82 |
-
|
|
|
83 |
|
84 |
-
|
85 |
"""
|
86 |
-
for _, row in
|
87 |
-
data_str += f"{row['Date']}: O:{row['Open']} H:{row['High']} L:{row['Low']} C:{row['Close']}\n"
|
88 |
|
89 |
url = "https://api.mistral.ai/v1/chat/completions"
|
90 |
|
@@ -96,11 +108,11 @@ Data:
|
|
96 |
data = {
|
97 |
"model": "mistral-small",
|
98 |
"messages": [
|
99 |
-
{"role": "system", "content": "You are
|
100 |
{"role": "user", "content": data_str}
|
101 |
],
|
102 |
"temperature": 0.7,
|
103 |
-
"max_tokens":
|
104 |
}
|
105 |
|
106 |
response = requests.post(url, headers=headers, json=data)
|
@@ -113,51 +125,59 @@ Data:
|
|
113 |
except Exception as e:
|
114 |
return f"Error getting analysis: {str(e)}"
|
115 |
|
116 |
-
def
|
117 |
api_status = verify_api_key()
|
118 |
if api_status.startswith("ERROR"):
|
119 |
return pd.DataFrame(), api_status
|
120 |
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
return df, analysis
|
124 |
|
125 |
# Create Gradio interface
|
126 |
with gr.Blocks() as demo:
|
127 |
with gr.Column():
|
128 |
-
gr.Markdown("#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
-
# Add
|
131 |
-
|
132 |
|
133 |
# Add outputs
|
134 |
with gr.Row():
|
135 |
with gr.Column(scale=1):
|
136 |
-
gr.Markdown("###
|
137 |
output_table = gr.Dataframe(
|
138 |
headers=["Date", "Open", "High", "Low", "Close", "Volume"],
|
139 |
wrap=True
|
140 |
)
|
141 |
|
142 |
with gr.Column(scale=1):
|
143 |
-
gr.Markdown("### Trading
|
144 |
analysis_output = gr.Textbox(
|
145 |
-
label="
|
146 |
-
lines=
|
147 |
elem_classes="analysis"
|
148 |
)
|
149 |
|
150 |
-
# Set up
|
151 |
-
|
152 |
-
fn=
|
153 |
-
|
154 |
-
)
|
155 |
-
|
156 |
-
# Initial load of data
|
157 |
-
demo.load(
|
158 |
-
fn=show_nifty_data_and_analysis,
|
159 |
outputs=[output_table, analysis_output],
|
160 |
)
|
161 |
|
162 |
-
# Launch the app
|
163 |
-
demo.launch()
|
|
|
11 |
return "ERROR: Mistral API key not found in environment variables"
|
12 |
return "API key found"
|
13 |
|
14 |
+
def fetch_stock_data(symbol):
|
15 |
try:
|
16 |
end_date = datetime.now()
|
17 |
+
start_date = end_date - timedelta(days=30) # Changed to 30 days
|
18 |
|
19 |
+
# Add .NS suffix for NSE stocks if not present
|
20 |
+
if not symbol.endswith('.NS') and not symbol.startswith('^'):
|
21 |
+
symbol = f"{symbol}.NS"
|
22 |
+
|
23 |
+
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?period1={int(start_date.timestamp())}&period2={int(end_date.timestamp())}&interval=1d"
|
24 |
|
25 |
headers = {
|
26 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
|
|
49 |
print(f"Error fetching data: {str(e)}")
|
50 |
return pd.DataFrame()
|
51 |
|
52 |
+
def get_swing_trade_analysis(df, symbol):
|
53 |
try:
|
54 |
api_key = os.environ.get('MISTRAL_API_KEY')
|
55 |
if not api_key:
|
56 |
return "Error: Mistral API key not found. Please add it to the environment variables."
|
57 |
|
58 |
+
# Get last 30 days of data
|
59 |
+
last_30_days = df.tail(30)
|
60 |
|
61 |
+
# Calculate current price and other metrics
|
62 |
+
current_price = last_30_days.iloc[-1]['Close']
|
63 |
+
avg_volume = last_30_days['Volume'].mean()
|
64 |
+
price_change = ((current_price - last_30_days.iloc[0]['Close']) / last_30_days.iloc[0]['Close']) * 100
|
65 |
|
66 |
# Format data for prompt
|
67 |
+
data_str = f"""Analyze the following stock data for {symbol} for swing trading suitability.
|
68 |
+
Current Price: {current_price}
|
69 |
+
30-Day Price Change: {price_change:.2f}%
|
70 |
+
Average Daily Volume: {avg_volume:,.0f}
|
71 |
|
72 |
+
Please provide a comprehensive swing trading analysis in the following format:
|
|
|
|
|
|
|
73 |
|
74 |
+
Price Action Analysis:
|
75 |
+
- Trend Analysis:
|
76 |
+
- Key Support Levels:
|
77 |
+
- Key Resistance Levels:
|
78 |
+
- Volume Analysis:
|
79 |
|
80 |
+
Swing Trading Suitability:
|
81 |
+
- Overall Rating (1-10):
|
82 |
+
- Risk Level (Low/Medium/High):
|
83 |
+
- Suggested Position Size:
|
84 |
+
- Recommended Holding Period:
|
85 |
|
86 |
+
Trading Setup (if suitable):
|
87 |
+
- Entry Strategy:
|
88 |
+
- Entry Price Range:
|
89 |
+
- Stop Loss:
|
90 |
+
- Target Prices (multiple levels):
|
91 |
+
- Risk/Reward Ratio:
|
92 |
|
93 |
+
Key Observations:
|
94 |
+
- List 3-4 critical points about price action and volume patterns
|
95 |
|
96 |
+
Last 30 days data:
|
97 |
"""
|
98 |
+
for _, row in last_30_days.iterrows():
|
99 |
+
data_str += f"{row['Date']}: O:{row['Open']} H:{row['High']} L:{row['Low']} C:{row['Close']} V:{row['Volume']:,.0f}\n"
|
100 |
|
101 |
url = "https://api.mistral.ai/v1/chat/completions"
|
102 |
|
|
|
108 |
data = {
|
109 |
"model": "mistral-small",
|
110 |
"messages": [
|
111 |
+
{"role": "system", "content": "You are an experienced swing trader specializing in price action analysis. Provide detailed, actionable analysis focusing on price action patterns, volume analysis, and swing trading suitability. Be specific with numbers and levels."},
|
112 |
{"role": "user", "content": data_str}
|
113 |
],
|
114 |
"temperature": 0.7,
|
115 |
+
"max_tokens": 1000
|
116 |
}
|
117 |
|
118 |
response = requests.post(url, headers=headers, json=data)
|
|
|
125 |
except Exception as e:
|
126 |
return f"Error getting analysis: {str(e)}"
|
127 |
|
128 |
+
def analyze_stock(symbol):
|
129 |
api_status = verify_api_key()
|
130 |
if api_status.startswith("ERROR"):
|
131 |
return pd.DataFrame(), api_status
|
132 |
|
133 |
+
if not symbol:
|
134 |
+
return pd.DataFrame(), "Please enter a stock symbol"
|
135 |
+
|
136 |
+
df = fetch_stock_data(symbol)
|
137 |
+
if df.empty:
|
138 |
+
return df, f"Unable to fetch data for symbol: {symbol}"
|
139 |
+
|
140 |
+
analysis = get_swing_trade_analysis(df, symbol)
|
141 |
return df, analysis
|
142 |
|
143 |
# Create Gradio interface
|
144 |
with gr.Blocks() as demo:
|
145 |
with gr.Column():
|
146 |
+
gr.Markdown("# Stock Swing Trading Analysis")
|
147 |
+
|
148 |
+
# Add input for stock symbol
|
149 |
+
stock_input = gr.Textbox(
|
150 |
+
label="Enter Stock Symbol (e.g., RELIANCE, INFY, TATAMOTORS, or ^NSEI for Nifty50)",
|
151 |
+
placeholder="Enter stock symbol...",
|
152 |
+
info="For NSE stocks, you can enter the symbol directly (e.g., RELIANCE). For indices, use ^ prefix (e.g., ^NSEI)"
|
153 |
+
)
|
154 |
|
155 |
+
# Add analyze button
|
156 |
+
analyze_btn = gr.Button("Analyze Stock", variant="primary")
|
157 |
|
158 |
# Add outputs
|
159 |
with gr.Row():
|
160 |
with gr.Column(scale=1):
|
161 |
+
gr.Markdown("### Historical Data (Last 30 Days)")
|
162 |
output_table = gr.Dataframe(
|
163 |
headers=["Date", "Open", "High", "Low", "Close", "Volume"],
|
164 |
wrap=True
|
165 |
)
|
166 |
|
167 |
with gr.Column(scale=1):
|
168 |
+
gr.Markdown("### Swing Trading Analysis")
|
169 |
analysis_output = gr.Textbox(
|
170 |
+
label="Analysis Results",
|
171 |
+
lines=20,
|
172 |
elem_classes="analysis"
|
173 |
)
|
174 |
|
175 |
+
# Set up analyze button click event
|
176 |
+
analyze_btn.click(
|
177 |
+
fn=analyze_stock,
|
178 |
+
inputs=[stock_input],
|
|
|
|
|
|
|
|
|
|
|
179 |
outputs=[output_table, analysis_output],
|
180 |
)
|
181 |
|
182 |
+
# Launch the app with sharing enabled
|
183 |
+
demo.launch(share=True)
|