DivyaShah2025's picture
Update app.py
c7c5a4e verified
"""
NSE F&O Analyzer Application
"""
import gradio as gr
import logging
import traceback
import os
import sys
# Add nse_modules to path
sys.path.append(os.path.join(os.path.dirname(__file__), 'nse_modules'))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class NSEAnalyzerApp:
def __init__(self):
print("🟑 Starting NSE Analyzer App init...")
try:
# Import NSE modules
print("🟑 Importing NSE modules...")
from nse_modules.single_day_download import SingleDayDownload
from nse_modules.batch_download import BatchDownload
from nse_modules.data_summary import DataSummary
from nse_modules.ai_analysis import AIAnalysis, run_ai_analysis
# Initialize NSE modules
self.single_day_download = SingleDayDownload()
self.batch_download = BatchDownload()
self.data_summary = DataSummary()
self.AIAnalysis = AIAnalysis # Store class reference
self.run_ai_analysis = run_ai_analysis # Store function reference
print("🟑 Creating interface...")
self.interface = self.create_interface()
print("🟒 Interface created successfully")
# In your NSEAnalyzerApp.__init__() method, add:
import os
print(f"πŸ“ Current working directory: {os.getcwd()}")
print(f"πŸ“ Contents of current directory: {os.listdir('.')}")
print(f"πŸ“ /data directory exists: {os.path.exists('/data')}")
if os.path.exists('/data'):
print(f"πŸ“ Contents of /data: {os.listdir('/data')}")
except Exception as e:
print(f"πŸ”΄ Error during initialization: {e}")
print(f"πŸ”΄ Traceback: {traceback.format_exc()}")
self.interface = self.create_fallback_interface()
def create_fallback_interface(self):
"""Create fallback interface"""
with gr.Blocks(title="NSE Analyzer - Fallback") as interface:
gr.Markdown("# ⚠️ NSE F&O Analyzer - Fallback Mode")
gr.Markdown("There was an error initializing the application. Please check the logs.")
return interface
def create_interface(self):
"""Create main Gradio interface"""
with gr.Blocks(
title="Divya Shah - AI Strategies for Option Sellers",
theme=gr.themes.Soft(),
css="""
.gradio-container {max-width: 1200px !important}
.brand-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 25px;
border-radius: 15px;
color: white;
text-align: center;
margin-bottom: 20px;
}
"""
) as interface:
# Your branded header
gr.Markdown("""
<div class="brand-header">
<h1 style="margin: 0 0 10px 0; font-size: 2.8em;">πŸ€– NSE F&O AI ANALYZER</h1>
<h2 style="margin: 0 0 8px 0; color: #ffd700;">Divya Shah</h2>
<h3 style="margin: 0; opacity: 0.9;">AI Strategies for Option Sellers</h3>
<p style="margin: 15px 0 0 0; font-size: 16px; opacity: 0.8;">
Professional Options Trading Analysis Platform
</p>
</div>
""")
gr.Markdown("### Download and analyze NSE Futures & Options data")
# NSE Single Day Download Tab
with gr.Tab("πŸ“₯ Single Day Download"):
self.single_day_download.create_interface()
# NSE Batch Download Tab
with gr.Tab("πŸ“ˆ Batch Download"):
self.batch_download.create_interface()
# NSE Data Summary Tab
with gr.Tab("πŸ“Š Data Summary"):
self.data_summary.create_interface()
# NSE AI Analysis Tab
with gr.Tab("πŸ€– AI Analysis"):
gr.Markdown("# πŸ€– Enhanced AI Analysis - NIFTY Strategies")
gr.Markdown("Advanced analysis with historical data and AI-powered recommendations")
with gr.Row():
analysis_type = gr.Dropdown(
label="Analysis Type",
choices=[
"comprehensive",
"option_selling",
"historical",
"basic"
],
value="comprehensive",
info="Comprehensive includes all analyses"
)
risk_level = gr.Dropdown(
label="Risk Level",
choices=["conservative", "moderate", "aggressive"],
value="moderate"
)
with gr.Row():
analyze_btn = gr.Button("πŸš€ Run Enhanced Analysis", variant="primary")
ai_analyze_btn = gr.Button("🧠 Get AI Recommendations", variant="secondary")
output = gr.Textbox(
label="Analysis Results",
lines=30,
max_lines=100,
show_copy_button=True
)
def analyze_enhanced_strategy(analysis_type, risk_level):
try:
return self.run_ai_analysis(risk_level, analysis_type)
except Exception as e:
return f"❌ Error during analysis: {str(e)}\n\n{traceback.format_exc()}"
def get_ai_recommendations():
try:
analyzer = self.AIAnalysis()
analyzer.load_data()
return analyzer.get_openai_strategy_recommendation(analyzer.nifty_data)
except Exception as e:
return f"❌ Error getting AI recommendations: {str(e)}"
analyze_btn.click(
fn=analyze_enhanced_strategy,
inputs=[analysis_type, risk_level],
outputs=output
)
ai_analyze_btn.click(
fn=get_ai_recommendations,
inputs=[],
outputs=output
)
return interface
def launch(self, **kwargs):
"""Launch the application"""
logger.info("πŸš€ Starting NSE F&O Analyzer...")
return self.interface.launch(**kwargs)
if __name__ == "__main__":
app = NSEAnalyzerApp()
app.launch()