File size: 7,254 Bytes
50be1ff
9162cf1
 
 
 
 
 
 
 
 
515f567
 
 
377f9ae
 
2235014
e5c766a
8d310cf
 
 
 
 
e5c766a
9162cf1
515f567
 
e04c223
6e86c39
 
69b8b9c
e5c766a
 
60bcd70
69b8b9c
5f1836d
3792828
eec10f6
8d310cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60bcd70
5f1836d
 
5f9f0ea
 
60bcd70
5f9f0ea
5f1836d
cf4ecc3
5f1836d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a9cfaf
 
 
5f1836d
 
3792828
e5c766a
8d310cf
 
 
 
 
 
 
 
 
 
 
62264e0
8d310cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf4ecc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8d0d55
cf4ecc3
e5c766a
 
 
 
 
 
 
 
 
 
3792828
 
 
 
 
 
 
 
 
 
e5c766a
3792828
e5c766a
 
cf4ecc3
 
e5c766a
 
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
164
165
166
167
168
169
170
171
172
173
import streamlit as st
import os
import getpass
from langchain import PromptTemplate
from langchain import hub
from langchain.docstore.document import Document
from langchain.document_loaders import WebBaseLoader
from langchain.schema import StrOutputParser
from langchain.schema.prompt_template import format_document
from langchain.schema.runnable import RunnablePassthrough
import google.generativeai as genai
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.chains.llm import LLMChain
from langchain.chains import StuffDocumentsChain
from langchain_core.messages import HumanMessage
import requests
from tradingview_ta import TA_Handler, Interval
import yfinance as yf
from datetime import datetime, timedelta
from newsapi import NewsApiClient

st.set_page_config(layout="wide")

GOOGLE_API_KEY=os.environ['GOOGLE_API_KEY']

st.title('Stock Market Insights')
st.sidebar.image("https://myndroot.com/wp-content/uploads/2023/12/Gemini-Dext.jpg",width =100)
st.sidebar.markdown("The App uses **Google Gemini API** for Text and Vision along with 🦜️🔗 LangChain")
st.sidebar.info("Know more about [NSE Tickers](https://www.google.com/search?q=nse+tickers+list&sca_esv=a6c39f4d03c5324c&sca_upv=1&rlz=1C1GCEB_enIN1011IN1011&sxsrf=ADLYWILQPbew-0SrvUUWpI8Y29_uOOgbvA%3A1716470016765&ei=AEFPZp-zLvzHp84P_ZWtuA0&oq=NSE+Tickers+&gs_lp=Egxnd3Mtd2l6LXNlcnAiDE5TRSBUaWNrZXJzICoCCAAyBRAAGIAEMggQABgWGAoYHjIGEAAYFhgeMgYQABgWGB4yBhAAGBYYHjIGEAAYFhgeMgYQABgWGB4yBhAAGBYYHjILEAAYgAQYhgMYigUyCxAAGIAEGIYDGIoFSIIbUL0PWL0PcAF4AZABAJgB8QKgAfECqgEDMy0xuAEByAEA-AEBmAICoAKKA8ICChAAGLADGNYEGEeYAwCIBgGQBgiSBwUxLjMtMaAHtQU&sclient=gws-wiz-serp)")

st.sidebar.info("Know more about [Charts](https://chart-img.com/)")
ticker_user = st.text_input("Enter Ticker for NSE Stocks","")
gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")

llm = ChatGoogleGenerativeAI(model="gemini-1.5-pro",google_api_key = GOOGLE_API_KEY)
llm_vis = ChatGoogleGenerativeAI(model="gemini-pro-vision",google_api_key = GOOGLE_API_KEY)

def get_tradingview_analysis(symbol, exchange, screener, interval):
    try:
        stock = TA_Handler(
            symbol=symbol,
            screener=screener,
            exchange=exchange,
            interval=interval,
        )
        analysis_summary = stock.get_analysis()
        return analysis_summary
    except Exception as e:
        return {"error": str(e)}

        
if ticker_user!="":
    url1 = f"https://www.google.com/finance/quote/{ticker_user}:NSE?hl=en"
    url2 = f"https://in.tradingview.com/symbols/NSE-{ticker_user}/"
    url3 = f"https://in.tradingview.com/symbols/NSE-{ticker_user}/news/"
    url4 = f"https://in.tradingview.com/symbols/NSE-{ticker_user}/minds/"

    loader = WebBaseLoader([url1,url2,url3,url4])
    docs = loader.load()
    
    
    st.divider()
    # llm_prompt_template = """You are an expert Stock Market Trader for stock market insights based on fundamental, analytical, profit based and company financials.
    # Based on the context below
    # {context}, Summarize the stock based on Historical data based on fundamental, price, news, sentiment , any red flags and suggest rating of the Stock in a 1 to 10 Scale"""
    
    llm_prompt_template = """You are an expert Stock Market Trader specializing in stock market insights derived from fundamental analysis, analytical trends, profit-based evaluations, and detailed company financials. Using your expertise, please analyze the stock based on the provided context below.
    
    Context:
    {context}
    
    Task:
    Summarize the stock based on its historical and current data.
    Evaluate the stock on the following parameters:
    1. Company Fundamentals: Assess the stock's intrinsic value, growth potential, and financial health.
    2. Current & Future Price Trends: Analyze historical price movements and current price trends.
    3. News and Sentiment: Review recent news articles, press releases, and social media sentiment.
    4. Red Flags: Identify any potential risks or warning signs.
    5. Provide a rating for the stock on a scale of 1 to 10.
    6. Advise if the stock is a good buy for the next 2 weeks.
    7. Suggest at what price we need to buy and hold or sell

    PROVIDE THE DETAILS based on just the FACTS present in the document
    PROVIDE THE DETAILS IN an JSON Object
    """
    
    # st.sidebar.subheader('Prompt')
    # user_prompt = st.sidebar.text_area("Enter Prompt",llm_prompt_template)
    #https://huggingface.co/spaces/pradeepodela/Stock-Analyser/blob/main/app.py
    interval = Interval.INTERVAL_1_DAY
    analysis_summary = get_tradingview_analysis(
            symbol=ticker_user,
            exchange="NSE",
            screener="india",
            interval=interval,
        )

    st.title("Analysis Summary")
    st.dataframe(analysis_summary.summary)
    query = f"{ticker_user} stock"

    details = {
        "symbol": ticker_user,
        "exchange": "NSE",
        "screener": "india",
        "interval": interval,
    }
    st.title("Details")
    st.dataframe(details)

    st.title("Oscillator Analysis")
    st.dataframe(analysis_summary.oscillators)

    st.title("Moving Averages")
    st.dataframe(analysis_summary.moving_averages)

    st.title("Summary")
    st.dataframe(analysis_summary.summary)

    st.title("Indicators")
    st.dataframe(analysis_summary.indicators)

    url = "https://api.chart-img.com/v2/tradingview/advanced-chart"
    api_key = "l0iUFRSeqC9z7nDPTd1hnafPh2RrdcEy6rl6tNqV"
    headers = {
        "x-api-key": api_key,
        "content-type": "application/json"
    }
    data = {
        "height": 400,
        "theme": "light",
        "interval": "1D",
        "session": "extended",
        "symbol": f"NSE:{ticker_user}"
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        with open("chart_t1.jpg", "wb") as f:
            f.write(response.content)
            
        st.image("chart_t1.jpg", caption='')

        llm_prompt = PromptTemplate.from_template(llm_prompt_template)
    
        llm_chain = LLMChain(llm=llm,prompt=llm_prompt)
        stuff_chain = StuffDocumentsChain(llm_chain=llm_chain,document_variable_name="context")
        
        
        res = stuff_chain.invoke(docs)

        #create the humanmassage propmt templete with the image file 
        # hmessage = HumanMessage(
        #     content=[
        #         {
        #             "type": "text",
        #             "text": "Based on the Image, suggest a BUY and SELL Strategy along with Risk based approach using Stop loss/Target price. PROVIDE THE DETAILS based on just the FACTS present and PROVIDE THE DETAILS IN an JSON Object",
        #         },
        #         {"type": "image_url", "image_url": "chart_t1.jpg"},
        #     ]
        # )
        # message = llm_vis.invoke([hmessage])
        
        # st.write(message.content)
        st.write(res["output_text"])
    
        # print("Image saved as chart-img-02.png")
    else:
        st.warning(f"Failed to retrieve image. Status code: {response.status_code}")
        st.warning("Response:", response.text)