<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kok Hua on Medium]]></title>
        <description><![CDATA[Stories by Kok Hua on Medium]]></description>
        <link>https://medium.com/@kokhua81?source=rss-e7322e3e8b09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CAwaUgK_qhxZWTXTKwO82Q.png</url>
            <title>Stories by Kok Hua on Medium</title>
            <link>https://medium.com/@kokhua81?source=rss-e7322e3e8b09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:22:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kokhua81/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tailored Insider Trading Alerts: Stay Updated for Informed Stock Decisions with Python, SEC API…]]></title>
            <link>https://wire.insiderfinance.io/tailored-insider-trading-alerts-stay-updated-for-informed-stock-decisions-with-python-sec-api-669d3205e730?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/669d3205e730</guid>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[insider-trading]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 12:01:17 GMT</pubDate>
            <atom:updated>2023-08-21T16:57:29.440Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tailored Insider Trading Alerts: Stay Updated for Informed Stock Decisions with Python, SEC API, and Telegram</h3><figure><img alt="Insider Trading Alerts: Stay Updated for Informed Stock Decisions with python" src="https://cdn-images-1.medium.com/max/1024/1*AHIUQNaYG0QJ-5W_zPQoJA.png" /></figure><p>Insider trading data from the SEC, especially transactions involving prominent figures like Warren Buffett, provides valuable insights into stock sentiment. By tracking their transactions, investors can gauge market confidence and anticipate potential trends. Those SEC filings serve as a strategic tool, helping investors make informed decisions and adjust their portfolios effectively.</p><p>This guide illustrates how we can utilize Python and the SEC API to retrieve and process SEC filings, specifically Insider Form 4 transactions. By integrating Python scripts with the SEC API, users can efficiently parse the filing document and retrieve real-time filing data, concentrating on specific stocks for monitoring. Through Telegram, these updates can be conveniently scheduled and dispatched to a dedicated channel, offering an organized platform to track and analyze activities related to the chosen stocks.</p><p>Below are the key steps to execute:</p><ol><li>Get free API key from sec_api.io</li><li>Import the required python libraries, including pandas, sec_api, and requests.</li><li>Fetch insider trading data using the InsiderTradingApi based on the trading symbol and date range.</li><li>Flatten the filing data to retrieve target data as a DataFrame.</li><li>Analyze insider transactions by calculating summary statistics like total shares and average share price for each recorded date.</li><li>Filter transactions by a specific reporting person (e.g., “BERKSHIRE HATHAWAY INC”).</li><li>(Optional) Use the Telegram API to send a summary report message to a target telegram group and schedule the script to run daily.</li></ol><h3>Sample Script</h3><p>Below is a sample script to monitor purchases/sales of OXY and BAC by BERKSHIRE HATHAWAY INC over the past 90 days.</p><pre>pip install sec-api</pre><pre>import pandas as pd<br>import math<br>from sec_api import InsiderTradingApi<br>import requests<br>from datetime import datetime, timedelta<br>from dateutil import tz<br><br>SEC_API_KEY = &quot;SEC API KEY&quot;<br>TOKEN = &quot;TELEGRAM TOKEN&quot; # Telegram token<br>chat_id = &quot;6240778619&quot; # Telegram chat group<br><br># List of trading symbols and corresponding big buyers<br>stocks_info = [<br>    {&quot;tradingSymbol&quot;: &quot;BAC&quot;, &quot;big_buyer&quot;: &quot;BERKSHIRE HATHAWAY INC&quot;},<br>    {&quot;tradingSymbol&quot;: &quot;OXY&quot;, &quot;big_buyer&quot;: &quot;BERKSHIRE HATHAWAY INC&quot;},<br>    # Add more symbols and buyers as needed<br>]<br><br>## Functions for processing the output<br>## Taken from Sec api example<br>def flatten_filing(filing):<br>    &quot;&quot;&quot;<br>    Condenses a filing record into a list of dictionaries, capturing essential details about non-derivative transactions.<br>    &quot;&quot;&quot;<br>    transactions = []<br><br>    # data points to be added to each transaction<br>    base_data = {&quot;periodOfReport&quot;: filing[&quot;periodOfReport&quot;],<br>                &quot;issuerCik&quot;: filing[&quot;issuer&quot;][&quot;cik&quot;],<br>                &quot;issuerTicker&quot;: filing[&quot;issuer&quot;][&quot;tradingSymbol&quot;],<br>                &quot;reportingPerson&quot;: filing[&quot;reportingOwner&quot;][&quot;name&quot;]<br>                }<br><br>    # ignore filing in case no non-derivative transactions was reported<br>    if &quot;transactions&quot; not in filing[&quot;nonDerivativeTable&quot;]:<br>        return []<br><br>    # extract the data points of interest from each transaction<br>    for transaction in filing[&quot;nonDerivativeTable&quot;][&quot;transactions&quot;]:<br>        try:<br>            entry = {&quot;securityTitle&quot;: transaction[&quot;securityTitle&quot;],<br>                    &quot;codingCode&quot;: transaction[&quot;coding&quot;][&quot;code&quot;],<br>                    &quot;acquiredDisposed&quot;: transaction[&quot;amounts&quot;][&quot;acquiredDisposedCode&quot;],<br>                    &quot;shares&quot;: transaction[&quot;amounts&quot;][&quot;shares&quot;],<br>                    &quot;sharePrice&quot;: transaction[&quot;amounts&quot;][&quot;pricePerShare&quot;],<br>                    &quot;total&quot;: math.ceil(transaction[&quot;amounts&quot;][&quot;shares&quot;] * transaction[&quot;amounts&quot;][&quot;pricePerShare&quot;]),<br>                    &quot;sharesOwnedFollowingTransaction&quot;: transaction[&quot;postTransactionAmounts&quot;][&quot;sharesOwnedFollowingTransaction&quot;]<br>                    }<br>        except:<br>            continue<br><br>        # merge base_data and entry into a new dict and append to transactions<br>        transactions.append({**base_data, **entry})<br><br>    return transactions<br><br><br># create a simplified list of all transactions per filing<br># with just a handful of data points, e.g. reporting person, shares sold, etc.<br>def flatten_filings(filings):<br>    unflattened_list = list(map(flatten_filing, filings))<br>    return [item for sublist in unflattened_list for item in sublist]<br><br><br>## Main script<br><br>for stock_info in stocks_info:<br>    # Set the trading symbol and calculate the date range<br>    tradingSymbol = stock_info[&quot;tradingSymbol&quot;]<br>    big_buyer = stock_info[&quot;big_buyer&quot;]<br>    today = datetime.now()<br>    time_ago = today - timedelta(days=90)  <br><br>    # Convert to the format required by the API<br>    date_format = &quot;%Y-%m-%d&quot;<br>    start_date = time_ago.strftime(date_format)<br>    end_date = today.strftime(date_format)<br><br>    insiderTradingApi = InsiderTradingApi(api_key=SEC_API_KEY)<br><br>    insider_trades = insiderTradingApi.get_data({<br>        &quot;query&quot;: {<br>            &quot;query_string&quot;: {<br>                &quot;query&quot;: f&quot;issuer.tradingSymbol:{tradingSymbol} AND filedAt:[{start_date} TO {end_date}]&quot;,<br>                &quot;time_zone&quot;: &quot;America/New_York&quot;<br>            }<br>        },<br>        &quot;from&quot;: &quot;0&quot;,<br>        &quot;size&quot;: &quot;10&quot;,<br>        &quot;sort&quot;: [{&quot;filedAt&quot;: {&quot;order&quot;: &quot;desc&quot;}}]<br>    })<br><br>    ## Get the SEC filings and do the necessary processing<br>    transactions = flatten_filings(insider_trades[&quot;transactions&quot;])<br><br>    df = pd.DataFrame(transactions)<br>    print(&quot;Length of transactions: &quot;.format(len(df)))<br><br>    if len(df)== 0:<br>        summary_report = pd.DataFrame()<br>    else:<br>        summary_df = df[[&#39;periodOfReport&#39;,&#39;reportingPerson&#39;,&#39;securityTitle&#39;,&#39;acquiredDisposed&#39;,&#39;sharePrice&#39;,&#39;shares&#39;]]\<br>        .groupby([&#39;periodOfReport&#39;,&#39;reportingPerson&#39;,&#39;securityTitle&#39;,&#39;acquiredDisposed&#39;]).agg({&#39;shares&#39;:&#39;sum&#39;,&#39;sharePrice&#39;:&#39;mean&#39;}).reset_index()<br><br>        #filtered by reportingPerson (or companies buying or selling in bulk)<br>        summary_report = summary_df[summary_df[&#39;reportingPerson&#39;]==big_buyer].sort_values(by=&#39;periodOfReport&#39;, ascending=False)<br><br>    #if len(summary_report)==0: print(&#39;No active Tranaction&#39;)<br><br>    ## Send to telegram<br>    url_pre =  f&quot;https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&amp;text={big_buyer}_insider_{tradingSymbol}&quot;<br><br>    if len(summary_report)==0:<br>        message = &#39;No active transactions&#39;<br>    else:<br>        message = summary_report[[&#39;periodOfReport&#39;,&#39;acquiredDisposed&#39;,&#39;shares&#39;]].to_string()<br><br>    url = f&quot;https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&amp;text={message}&quot;<br><br>    requests.get(url_pre) # this sends the message<br>    requests.get(url) # this sends the message<br><br>    print(f&#39;{big_buyer}_insider_{tradingSymbol}&#39;)<br>    print(message)<br>    print()</pre><h3><strong>Conclusion</strong></h3><p>Incorporating SEC insider trading data, especially involving notable figures like Warren Buffett, offers valuable insights into market sentiment. This guide demonstrates how to efficiently utilize Python and the SEC API to access and analyze SEC filings and publishing to Telegram streamlines updates, allowing investors to stay informed and make informed decisions.</p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669d3205e730" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/tailored-insider-trading-alerts-stay-updated-for-informed-stock-decisions-with-python-sec-api-669d3205e730">Tailored Insider Trading Alerts: Stay Updated for Informed Stock Decisions with Python, SEC API…</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Power of AI for Financial Analysis: Let ChatGPT Be Your Legendary Investor!]]></title>
            <link>https://wire.insiderfinance.io/unleashing-the-power-of-ai-for-financial-analysis-let-chatgpt-be-your-legendary-investor-aa072de7eeb9?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa072de7eeb9</guid>
            <category><![CDATA[fundamental-analysis]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[financial-statements]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 07:39:48 GMT</pubDate>
            <atom:updated>2023-08-11T12:29:08.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYvCbaAHx99rdtYqcD6Neg.png" /></figure><p>In the dynamic and complex world of finance, deciphering and comprehending financial data (Balance Sheet, Cash flow, Income Statements) can pose a significant challenge, particularly if you lack expertise in accounting or reading financial statements.</p><p>However, imagine if you could harness the capabilities of AI to play the role of a legendary investor like Warren Buffett or Charlie Munger helping you to make sense of these intricate details. Intrigued? Well, you’re in luck! In this article, we’ll explore how you can utilize Python and the prowess of generative AI such as ChatGPT to acquire insights and analysis.</p><h3>Extract Financial Data with Python</h3><p>We’re going to be using the yfinance library in Python to fetch the financial data we need. Assume you’re interested in analyzing the financial health of a company, let’s say Tesla (TSLA). You can easily retrieve the balance sheet, cash flow statement, and income statement data using the following code snippet:</p><pre>import yfinance as yf<br><br># Define the stock symbol<br>symbol = &#39;TSLA&#39;  <br><br># Fetch balance sheet data using yfinance<br>balance_sheet = yf.Ticker(symbol).balance_sheet<br>cash_flow = yf.Ticker(symbol).cash_flow<br>income_statement = yf.Ticker(symbol).financials<br><br># Fetch the latest yearly data.<br>latest_bal_sheet = balance_sheet.iloc[:, 0]<br>latest_cash_flow = cash_flow.iloc[:, 0]<br>latest_income_statement = income_statement.iloc[:, 0]</pre><h3>AI-Powered Financial Analysis</h3><p>Now comes the exciting part: What if we could enlist the capabilities of ChatGPT, our AI powerhouse, to analyze this data for us? To achieve this, we’ll craft a prompt that directs ChatGPT to embody the persona of a seasoned financial expert. By providing the prompts and financial data (as json format) as inputs, we can let the model generate insightful analysis for us.</p><p>The AI will highlight strengths, address concerns, assess the company’s financial health, and even provide recommendations. Considering the constraints on the length of the input prompt, we’ll begin by providing the balance sheet and income statement data.</p><pre>system_role  =\<br>&quot;&quot;&quot;Assume the role as a seasoned expert in the field of finance and investing, \<br>embodying the insights and acumen of legendary figures like Charlie Munger and Warren Buffett. \<br>Possessing a profound understanding of the stock market, companies, and financial statements, \<br>you have honed the skillset of a masterful accountant and financial analyst. \<br>Your ability to conduct thorough fundamental analysis sets you apart, allowing you to decipher intricate market trends, \<br>evaluate company performance, and make informed investment decisions.\<br>With a wealth of knowledge and years of experience, you provide invaluable guidance and insights into the world of finance and investing<br>&quot;&quot;&quot;<br><br>query_balshee_income_prompt = <br>&quot;&quot;&quot;\nGiven {} latest balance sheet and income statment, provide insights, comments, possible concerns on it.\<br>The output should have highlights of the balance sheet strengths, the potential concerns and\<br>a paragraph on the final assessment whether the company balance sheet is healthy. Do the same for the income statements.\<br>Lastly provide overall summmary of the company health<br>Balance sheet json data as below\n{}\nIncome json data as below\n{}&quot;&quot;&quot;<br><br>full_query_balshee_income_prompt =  system_role + query_balshee_income_prompt.format(symbol,latest_bal_sheet.to_json(),latest_income_statement.to_json())<br>print(full_query_balshee_income_prompt)<br></pre><p>You can copy and paste the aforementioned prompt into either ChatGPT or Google Bard. Alternatively, you have the option to utilize the OpenAI API through Python. Once the initial prompt has been processed, you can move forward with the second prompt, which will involve inputting the cash flow details.</p><pre>cashflow_prompt = <br>&quot;&quot;&quot;I also attached the cashflow statement as below.\ <br>Help me do the same analysis and lastly combined the information \<br>from previous output and this to give overall comment of company.\<br>and recommend whether to buy the company stock. \<br>The cashflow statement is as below\n{}&quot;&quot;&quot;.format(latest_cash_flow.to_json())<br><br>print(cashflow_prompt)</pre><h3>Sample Chatgpt output</h3><p>Below are the corresponding outputs from ChatGPT based on the two prompts. Feel free to ask ChatGPT additional questions about the specific data to obtain a more comprehensive understanding.</p><figure><img alt="Chatgpt output assessment of balance sheet and income statement" src="https://cdn-images-1.medium.com/max/1024/1*wf5MW4XqxsQ6MOdpR6XK3g.png" /></figure><figure><img alt="Chatgpt output assessment of balance sheet and income statement part 2" src="https://cdn-images-1.medium.com/max/1024/1*gJ_VIuHtcsMJK2L4WKbjQg.png" /><figcaption>Output from the first prompt on Balance Sheet &amp; Income Statement</figcaption></figure><figure><img alt="Chatgpt output assessment of cash flow and overall comment of the company financials" src="https://cdn-images-1.medium.com/max/1024/1*HCk6KEsAUhhIWN8V5cPEiw.png" /><figcaption>Output from the 2nd prompt on Cash Flow and Overall comment</figcaption></figure><h3>Conclusion</h3><p>In this tutorial, we’ve demonstrated how Python, data extraction, and AI can be seamlessly integrated to simplify the process of analyzing financial data. With the help of the generative AI, we can emulate the expertise of legendary investors and gain valuable insights into company performance, all while saving time and effort.</p><p>Feel free to share your thoughts below on how we can enhance the prompt to generate more detailed analyses and provide deeper insights!</p><p>You can refer to the following links for more articles on utilizing Python &amp; AI for stock market research and analysis.</p><ol><li><a href="https://medium.com/@kokhua81/stocks-technical-analysis-ta-with-python-chatgpt-a-comprehensive-guide-871a756ebc7c">Stocks Technical Analysis (TA) with Python &amp; ChatGPT: A Comprehensive Guide</a></li><li><a href="https://medium.com/@kokhua81/decoding-stock-sentiment-exploring-options-data-analysis-with-python-and-ai-e14f330069eb">Decoding Market Sentiment: Exploring Options Data Analysis with Python and AI</a></li></ol><p><em>Disclaimer: This blog is intended for informational purposes only and should not be considered as financial advice. Always conduct thorough research and consult with financial professionals before making investment decisions.</em></p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa072de7eeb9" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/unleashing-the-power-of-ai-for-financial-analysis-let-chatgpt-be-your-legendary-investor-aa072de7eeb9">Unleashing the Power of AI for Financial Analysis: Let ChatGPT Be Your Legendary Investor!</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stocks Technical Analysis (TA) with Python & ChatGPT: A Comprehensive Guide]]></title>
            <link>https://medium.com/@kokhua81/stocks-technical-analysis-ta-with-python-chatgpt-a-comprehensive-guide-871a756ebc7c?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/871a756ebc7c</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[market-sentiment]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 15:02:11 GMT</pubDate>
            <atom:updated>2023-08-06T15:05:59.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Technical analysis with Python and ChatGPT" src="https://cdn-images-1.medium.com/max/1024/1*dOehxQHrpHPsqbdXQWGihw.png" /></figure><p>One effective way to gain insights and sentiments into potential stock price movements is through Technical Analysis (TA). By delving into historical market data, particularly price and volume, TA seeks to anticipate future price shifts. This methodology operates on the premise that historical price patterns tend to recur, thus shedding light on potential future trends.</p><p>Python provides robust tools for collecting, analyzing, and deriving Technical Analysis (TA) indicators from stock data. By harnessing the power of ChatGPT in conjunction with these tools, you can enable ChatGPT to analyze the TA indicators you’ve generated. This blog will guide you through the step-by-step process of performing stock TA analysis using Python’s yfinance and pandas_ta libraries, as well as demonstrate how you can leverage ChatGPT’s capabilities to interpret the analysis outcomes and forecast future trends.</p><h3>Steps to Perform Stock TA Analysis Using Python and ChatGPT</h3><ol><li>Utilize yfinance to fetch historical stock price data and <a href="https://github.com/twopirllc/pandas-ta">pandas_ta</a> to compute technical indicators.</li><li>Gather indicators for the last trading day to input into the ChatGPT prompt.</li><li>Create a prompt for ChatGPT, incorporating the indicators for analysis.</li><li>Engage ChatGPT to interpret indicators and predict future trends.</li><li>Enhance insights by visualizing indicator trends using additional charts.</li></ol><h3>Python Script for Stock Price Data and TA Calculation</h3><p>Below is the Python script to perform the function using the yfinance and pandas-ta libraries. Pandas_ta can compute various technical indicators, such as Moving Averages, RSI, and Bollinger Bands, providing insights into momentum, volatility, and potential reversals. For more details, <a href="https://github.com/twopirllc/pandas-ta">consult the pandas-ta documentation</a>.</p><pre>!pip install yfinance<br>!pip install pandas_ta</pre><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import yfinance as yf<br>import pandas_ta as ta<br>import matplotlib.dates as mdates<br>from datetime import datetime, timedelta<br><br># Define the stock symbol and timeframe<br>symbol = &#39;DIS&#39;<br>end_date = datetime.today()<br>start_date = end_date - timedelta(days=120)  # 4 months before today<br><br># Fetch stock data using yfinance<br>stock_data = yf.download(symbol, start=start_date, end=end_date)<br><br># Calculate technical indicators using pandas-ta<br>stock_data.ta.macd(append=True)<br>stock_data.ta.rsi(append=True)<br>stock_data.ta.bbands(append=True)<br>stock_data.ta.obv(append=True)<br><br># Calculate additional technical indicators<br>stock_data.ta.sma(length=20, append=True)<br>stock_data.ta.ema(length=50, append=True)<br>stock_data.ta.stoch(append=True)<br>stock_data.ta.adx(append=True)<br><br># Calculate other indicators<br>stock_data.ta.willr(append=True)<br>stock_data.ta.cmf(append=True)<br>stock_data.ta.psar(append=True)<br><br>#convert OBV to million<br>stock_data[&#39;OBV_in_million&#39;] =  stock_data[&#39;OBV&#39;]/1e7<br>stock_data[&#39;MACD_histogram_12_26_9&#39;] =  stock_data[&#39;MACDh_12_26_9&#39;] # not to confuse chatGTP<br><br># Summarize technical indicators for the last day<br>last_day_summary = stock_data.iloc[-1][[&#39;Adj Close&#39;,<br>    &#39;MACD_12_26_9&#39;,&#39;MACD_histogram_12_26_9&#39;, &#39;RSI_14&#39;, &#39;BBL_5_2.0&#39;, &#39;BBM_5_2.0&#39;, &#39;BBU_5_2.0&#39;,&#39;SMA_20&#39;, &#39;EMA_50&#39;,&#39;OBV_in_million&#39;, &#39;STOCHk_14_3_3&#39;, <br>    &#39;STOCHd_14_3_3&#39;, &#39;ADX_14&#39;,  &#39;WILLR_14&#39;, &#39;CMF_20&#39;, <br>    &#39;PSARl_0.02_0.2&#39;, &#39;PSARs_0.02_0.2&#39;<br>]]<br><br>print(&quot;Summary of Technical Indicators for the Last Day:&quot;)<br>print(last_day_summary)</pre><h3>Setting Up the ChatGPT Prompt</h3><p>Construct the prompt in a manner that invokes the expertise of legendary TA figures like Charles Dow and John Bollinger to conduct the analysis on your behalf.</p><p>Below is the Python script that establishes the prompt, delineating ChatGPT’s role and integrating the most recent trading day’s indicators. Following ChatGPT’s analysis, you can further engage by posing additional questions, delving into specific indicators, and requesting ChatGPT to elaborate further. Do note instead of pasting the prompt to ChatGPT manually, you can also use the openai API to automate the process.</p><pre>## Work on the prompt<br>sys_prompt = &quot;&quot;&quot;<br>Assume the role as a leading Technical Analysis (TA) expert in the stock market, \<br>a modern counterpart to Charles Dow, John Bollinger, and Alan Andrews. \<br>Your mastery encompasses both stock fundamentals and intricate technical indicators. \<br>You possess the ability to decode complex market dynamics, \<br>providing clear insights and recommendations backed by a thorough understanding of interrelated factors. \<br>Your expertise extends to practical tools like the pandas_ta module, \<br>allowing you to navigate data intricacies with ease. \<br>As a TA authority, your role is to decipher market trends, make informed predictions, and offer valuable perspectives.<br><br>given {} TA data as below on the last trading day, what will be the next few days possible stock price movement? <br><br>Summary of Technical Indicators for the Last Day:<br>{}&quot;&quot;&quot;.format(symbol,last_day_summary)<br><br>print(sys_prompt)</pre><h3>Visualizing Insights</h3><p>Below is the Python code showcasing all the indicators by date, serving as a supplement to the analysis provided by ChatGPT.</p><pre># Plot the technical indicators<br>plt.figure(figsize=(14, 8))<br><br># Price Trend Chart<br>plt.subplot(3, 3, 1)<br>plt.plot(stock_data.index, stock_data[&#39;Adj Close&#39;], label=&#39;Adj Close&#39;, color=&#39;blue&#39;)<br>plt.plot(stock_data.index, stock_data[&#39;EMA_50&#39;], label=&#39;EMA 50&#39;, color=&#39;green&#39;)<br>plt.plot(stock_data.index, stock_data[&#39;SMA_20&#39;], label=&#39;SMA_20&#39;, color=&#39;orange&#39;)<br>plt.title(&quot;Price Trend&quot;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br>plt.legend()<br><br># On-Balance Volume Chart<br>plt.subplot(3, 3, 2)<br>plt.plot(stock_data[&#39;OBV&#39;], label=&#39;On-Balance Volume&#39;)<br>plt.title(&#39;On-Balance Volume (OBV) Indicator&#39;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br>plt.legend()<br><br># MACD Plot<br>plt.subplot(3, 3, 3)<br>plt.plot(stock_data[&#39;MACD_12_26_9&#39;], label=&#39;MACD&#39;)<br>plt.plot(stock_data[&#39;MACDh_12_26_9&#39;], label=&#39;MACD Histogram&#39;)<br>plt.title(&#39;MACD Indicator&#39;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br>plt.title(&quot;MACD&quot;)<br>plt.legend()<br><br># RSI Plot<br>plt.subplot(3, 3, 4)<br>plt.plot(stock_data[&#39;RSI_14&#39;], label=&#39;RSI&#39;)<br>plt.axhline(y=70, color=&#39;r&#39;, linestyle=&#39;--&#39;, label=&#39;Overbought (70)&#39;)<br>plt.axhline(y=30, color=&#39;g&#39;, linestyle=&#39;--&#39;, label=&#39;Oversold (30)&#39;)<br>plt.legend()<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br>plt.title(&#39;RSI Indicator&#39;)<br><br># Bollinger Bands Plot<br>plt.subplot(3, 3, 5)<br>plt.plot(stock_data.index, stock_data[&#39;BBU_5_2.0&#39;], label=&#39;Upper BB&#39;)<br>plt.plot(stock_data.index, stock_data[&#39;BBM_5_2.0&#39;], label=&#39;Middle BB&#39;)<br>plt.plot(stock_data.index, stock_data[&#39;BBL_5_2.0&#39;], label=&#39;Lower BB&#39;)<br>plt.plot(stock_data.index, stock_data[&#39;Adj Close&#39;], label=&#39;Adj Close&#39;, color=&#39;brown&#39;)<br>plt.title(&quot;Bollinger Bands&quot;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br>plt.legend()<br><br># Stochastic Oscillator Plot<br>plt.subplot(3, 3, 6)<br>plt.plot(stock_data.index, stock_data[&#39;STOCHk_14_3_3&#39;], label=&#39;Stoch %K&#39;)<br>plt.plot(stock_data.index, stock_data[&#39;STOCHd_14_3_3&#39;], label=&#39;Stoch %D&#39;)<br>plt.title(&quot;Stochastic Oscillator&quot;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br>plt.legend()<br><br># Williams %R Plot<br>plt.subplot(3, 3, 7)<br>plt.plot(stock_data.index, stock_data[&#39;WILLR_14&#39;])<br>plt.title(&quot;Williams %R&quot;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br><br># ADX Plot<br>plt.subplot(3, 3, 8)<br>plt.plot(stock_data.index, stock_data[&#39;ADX_14&#39;])<br>plt.title(&quot;Average Directional Index (ADX)&quot;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br><br># CMF Plot<br>plt.subplot(3, 3, 9)<br>plt.plot(stock_data.index, stock_data[&#39;CMF_20&#39;])<br>plt.title(&quot;Chaikin Money Flow (CMF)&quot;)<br>plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b%d&#39;))  # Format date as &quot;Jun14&quot;<br>plt.xticks(rotation=45, fontsize=8)  # Adjust font size<br><br># Show the plots<br>plt.tight_layout()<br>plt.show()</pre><h3>Sample output</h3><figure><img alt="Chatgpt prompt to analyze Technical analysis of stock" src="https://cdn-images-1.medium.com/max/1024/1*4LmISLy1TW0aIL6MUYUN0A.png" /></figure><figure><img alt="Interpreting technical analysis results with ChatGPT" src="https://cdn-images-1.medium.com/max/1024/1*-KqnM3F7muuPvDJbVpe9UQ.png" /></figure><figure><img alt="Python plot of various stock TA indicators" src="https://cdn-images-1.medium.com/max/1024/1*B6twMY1lsjUT4Twoj9tQNQ.png" /></figure><h3>Conclusion</h3><p>In conclusion, the combination of Python’s yfinance and pandas-ta modules, along with ChatGPT’s capabilities, provides a powerful method to analyze and interpret technical indicators, yielding valuable insights into stock sentiment.</p><p>The inclusion of additional charting enhances the depth of these insights. However, it’s important to recognize that a comprehensive analysis must also encompass macroeconomic and other relevant economic data to ensure well-informed decision-making.</p><p>If you are interesteed in stock market sentiment, analysis and price trends, do check out my other blog post on <a href="https://medium.com/@kokhua81/decoding-stock-sentiment-exploring-options-data-analysis-with-python-and-ai-e14f330069eb">Decoding Market Sentiment: Exploring Options Data Analysis with Python and AI</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=871a756ebc7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Stock Sentiment: Exploring Options Data Analysis with Python and AI]]></title>
            <link>https://wire.insiderfinance.io/decoding-stock-sentiment-exploring-options-data-analysis-with-python-and-ai-e14f330069eb?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/e14f330069eb</guid>
            <category><![CDATA[options]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[stock-market-analysis]]></category>
            <category><![CDATA[yahoo-finance]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 07:55:18 GMT</pubDate>
            <atom:updated>2023-08-14T16:05:14.887Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding Market Sentiment: Exploring Options Data Analysis with Python and AI</h3><figure><img alt="Using options data to determine market sentiment of stock using python and generative AI" src="https://cdn-images-1.medium.com/max/1024/1*8D-0CpfjjvlmXgYJyq41aw.png" /></figure><p>One intriguing avenue for gaining insights into market sentiment is through the analysis of options data. Options, which offer the right to buy or sell a stock at a specific price within a predetermined timeframe, can reveal valuable clues about investor expectations and market trends.</p><p>By examining key metrics derived from options data, such as implied volatility, open interest, and put-call ratios, investors can gauge market sentiment and anticipate potential price movements. Elevated levels of implied volatility, for instance, may indicate increased uncertainty and potential price swings, while shifts in put-call ratios can provide insights into prevailing bullish or bearish sentiments.</p><h4>Python to get options data, calculate metrics</h4><p>In this tutorial, we utilize Python and related libraries to retrieve options data and calculate essential metrics like implied volatility, open interest, and put-call ratios. These derived metrics provide insights into stock sentiment, both in the short term and over a longer horizon, considering option expiration dates.</p><p>Below are the key steps for the python script</p><ol><li>Import libraries (yahoo_fin) and fetch current stock price and option expiry dates.</li><li>Retrieve call and put option data for the nearest expiry date.</li><li>Analyze options data for implied volatility, option prices, strike prices, volume, and open interest.</li><li>Calculate put-call ratio, implied volatility percentiles, and skew.</li></ol><pre>from yahoo_fin import options, stock_info<br>import pandas as pd<br>from IPython.utils import io<br>import matplotlib.pyplot as plt<br>from datetime import datetime<br><br>ticker = &#39;NVDA&#39;<br>current_price = round(stock_info.get_live_price(ticker),3)<br>option_expiry_dates = options.get_expiration_dates(ticker)# get list of expiry date<br>nearest_expiry = option_expiry_dates[0] # can vary the list of expiry date<br><br>call_df = options.get_calls(ticker, nearest_expiry)<br>put_df = options.get_puts(ticker, nearest_expiry)<br><br># Capture the print statement in Google Colab<br>with io.capture_output() as captured:<br>    # Implied Volatility Analysis:<br>    avg_call_iv = call_df[&quot;Implied Volatility&quot;].str.rstrip(&quot;%&quot;).astype(float).mean()<br>    print(&quot;\nAverage Implied Volatility for Call Options:&quot;, avg_call_iv, &quot;%&quot;)<br><br>    avg_put_iv = put_df[&quot;Implied Volatility&quot;].str.rstrip(&quot;%&quot;).astype(float).mean()<br>    print(&quot;Average Implied Volatility for Put Options:&quot;, avg_put_iv, &quot;%&quot;)<br><br>    # Option Prices Analysis:<br>    avg_call_last_price = call_df[&quot;Last Price&quot;].mean()<br>    print(&quot;\nAverage Last Price for Call Options:&quot;, avg_call_last_price)<br><br>    avg_put_last_price = put_df[&quot;Last Price&quot;].mean()<br>    print(&quot;Average Last Price for Put Options:&quot;, avg_put_last_price)<br><br>    # Strike Price Analysis:<br>    min_call_strike = call_df[&quot;Strike&quot;].min()<br>    max_call_strike = call_df[&quot;Strike&quot;].max()<br>    print(&quot;\nMinimum Strike Price for Call Options:&quot;, min_call_strike)<br>    print(&quot;Maximum Strike Price for Call Options:&quot;, max_call_strike)<br><br>    min_put_strike = put_df[&quot;Strike&quot;].min()<br>    max_put_strike = put_df[&quot;Strike&quot;].max()<br>    print(&quot;Minimum Strike Price for Put Options:&quot;, min_put_strike)<br>    print(&quot;Maximum Strike Price for Put Options:&quot;, max_put_strike)<br><br>    # Volume Analysis:<br>    total_call_volume =  call_df[&quot;Volume&quot;].str.replace(&#39;-&#39;,&#39;0&#39;).astype(float).sum()<br>    print(&quot;\nTotal Volume for Call Options:&quot;, total_call_volume)<br><br>    try:<br>        total_put_volume =  put_df[&quot;Volume&quot;].str.replace(&#39;-&#39;,&#39;0&#39;).astype(float).sum()<br>    except:<br>        total_put_volume =  put_df[&quot;Volume&quot;].sum()<br><br>    print(&quot;Total Volume for Put Options:&quot;, total_put_volume)<br><br>    # Open Interest Analysis:<br>    try:<br>        call_df[&#39;Open Interest&#39;] = call_df[&#39;Open Interest&#39;].str.replace(&#39;-&#39;,&#39;0&#39;).astype(float)<br>    except:<br>        pass<br>    try:<br>        put_df[&#39;Open Interest&#39;] = put_df[&#39;Open Interest&#39;].str.replace(&#39;-&#39;,&#39;0&#39;).astype(float)<br>    except:<br>        pass<br>    total_call_open_interest = call_df[&quot;Open Interest&quot;].sum()<br>    print(&quot;\nTotal Open Interest for Call Options:&quot;, total_call_open_interest)<br><br>    total_put_open_interest = put_df[&quot;Open Interest&quot;].sum()<br>    print(&quot;Total Open Interest for Put Options:&quot;, total_put_open_interest)<br>    try:<br>        call_df[&#39;Implied Volatility&#39;] = call_df[&#39;Implied Volatility&#39;].str.replace(&#39;%&#39;,&#39;&#39;).astype(float)<br>    except:<br>        pass<br><br>    try:<br>        put_df[&#39;Implied Volatility&#39;] = put_df[&#39;Implied Volatility&#39;].str.replace(&#39;%&#39;,&#39;&#39;).astype(float)<br>    except:<br>        pass<br>    # Calculate Option Greeks (Delta, Gamma, Theta, Vega, and Rho) - You can use appropriate formulas to calculate these.<br><br>    # Calculate Put-Call Ratio<br>    put_call_ratio = total_put_volume / total_call_volume<br><br>    # Calculate Implied Volatility Percentile<br>    call_iv_percentile = (call_df[&#39;Implied Volatility&#39;] &gt; call_df[&#39;Implied Volatility&#39;].mean()).mean() * 100<br>    put_iv_percentile = (put_df[&#39;Implied Volatility&#39;] &gt; put_df[&#39;Implied Volatility&#39;].mean()).mean() * 100<br><br>    # Calculate Implied Volatility Skew<br>    implied_vol_skew = call_df[&#39;Implied Volatility&#39;].mean() - put_df[&#39;Implied Volatility&#39;].mean()<br><br>    # Check if call options have higher average implied volatility than put options<br>    is_bullish_sentiment = call_df[&#39;Implied Volatility&#39;].mean() &gt; put_df[&#39;Implied Volatility&#39;].mean()<br><br>    # Display the results<br>    print(&quot;Put-Call Ratio:&quot;, put_call_ratio)<br>    print(&quot;Call Option Implied Volatility Percentile:&quot;, call_iv_percentile)<br>    print(&quot;Put Option Implied Volatility Percentile:&quot;, put_iv_percentile)<br>    print(&quot;Implied Volatility Skew:&quot;, implied_vol_skew)<br><br>    # if is_bullish_sentiment:<br>    #     print(f&quot;The overall sentiment of {ticker} is bullish.&quot;)<br>    # else:<br>    #     print(f&quot;The overall sentiment of {ticker}  is bearish.&quot;)<br><br># Get the captured output as a string<br>captured_output = captured.stdout<br><br># Print the captured output or save it to a variable or file as needed<br>print(captured_output)</pre><h3>Use ChatGPT to analyse the data for you</h3><p>Instead of analyzing the derived metrics yourself, you can set up a prompt and ask ChatGPT to perform the analysis for you! You can use OpenAI’s platform or simply paste the content into the web version. Below is the Python script that creates the prompt and captures all the information you need.</p><pre>role_prompt = &quot;&quot;&quot;Assume the role as a seasoned stock option analyst with a strong track record\<br> in dissecting intricate option data to discern valuable insights into stock sentiment.\<br>  Proficient in utilizing advanced statistical models and data visualization techniques to \<br>  forecast market trends and make informed trading decisions. Adept at interpreting option Greeks, \<br>  implied volatility, and analyzing trading volumes to gauge investor sentiment accurately.\<br>   Known for an exceptional ability to transform complex data into actionable trading strategies, \<br>   consistently achieving optimal results for portfolio growth.&quot;&quot;&quot;<br><br>today_date = datetime.now().strftime(&quot;%b %d, %Y&quot;)<br><br>advice_prompt = f&quot;Given {ticker} current {today_date} price is {current_price} and \<br>call and put option at expiry date {nearest_expiry} is as below: \n{captured_output}\n\<br>What is the overall sentiment of {ticker} based on above information?&quot;<br>print(role_prompt + &#39;\n&#39; + advice_prompt)</pre><h3>Sample query and output from ChatGPT</h3><figure><img alt="Prompt setup for ChatGPT to analyze options metrics and derive market sentiment" src="https://cdn-images-1.medium.com/max/1024/1*bSfPCcQ-VEifyxCy8tDjnQ.png" /></figure><figure><img alt="ChatGPT output on analyzing options data to determine stock sentiment" src="https://cdn-images-1.medium.com/max/1024/1*yhEnqqu2NwD8Zmrh6Puf7g.png" /></figure><h3>Conclusion</h3><p>We have demonstrated above how we can utilize Python and its related libraries to retrieve options data and derive key metrics. Furthermore, we can harness generative AI to analyze and potentially draw conclusions regarding the sentiment of the stock based on the options data. However, it’s important to note that this approach provides a potential indicator of stock sentiment and is by no means the sole determinant of stock movements. Trading decisions should also consider other factors such as broader market trends and external news.</p><p>In addition to utilizing options data, we can leverage technical analysis to gauge stock sentiment. Feel free to explore my post “<a href="https://medium.com/@kokhua81/stocks-technical-analysis-ta-with-python-chatgpt-a-comprehensive-guide-871a756ebc7c">Stocks Technical Analysis (TA) with Python &amp; ChatGPT: A Comprehensive Guide</a>” that demonstrates the use of Python and AI to compute and interpret technical analysis</p><p>We can enhance the above approach by scheduling and automating the process, allowing it to feed into your Telegram bot or channel. You can find more details under this post on <a href="https://medium.com/@kokhua81/how-to-send-messages-and-files-to-telegram-with-python-66c1abeea7a6">How to Send Messages and Files to Telegram with Python</a> . This way, you can receive daily updates on the data.</p><p>Feel free to provide your input if you believe additional metrics or parameters could be integrated to utilize options data more effectively and accurately reflect the sentiment of the stock.</p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e14f330069eb" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/decoding-stock-sentiment-exploring-options-data-analysis-with-python-and-ai-e14f330069eb">Decoding Stock Sentiment: Exploring Options Data Analysis with Python and AI</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Messages and Files to Telegram with Python]]></title>
            <link>https://medium.com/@kokhua81/how-to-send-messages-and-files-to-telegram-with-python-66c1abeea7a6?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c1abeea7a6</guid>
            <category><![CDATA[python-telegram-bot]]></category>
            <category><![CDATA[python-guide]]></category>
            <category><![CDATA[telegram]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 08:13:49 GMT</pubDate>
            <atom:updated>2023-07-19T08:13:49.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Telegram API: Send and receive text, message" src="https://cdn-images-1.medium.com/max/1024/1*xtANLcWUo05AXgU_GXiwHw.png" /></figure><p>In this step-by-step guide, I will show how to send messages and images to Telegram and to download images from Telegram using Python. By utilizing the python Telethon library and TelegramClient, you can effortlessly send messages and images with just a few lines of python code.</p><h3><strong>Steps</strong></h3><ul><li>Obtain your Telegram API ID and API hash values by visiting <a href="http://my.telegram.org/">my.telegram.org</a> and setting up the API. More details in the <a href="https://core.telegram.org/api/obtaining_api_id">documentation</a>.</li><li>pip install telethon</li><li>Run the python code</li></ul><h3>Sending messages and files</h3><pre>from telethon import TelegramClient<br>import asyncio<br><br>## Run the following 2 lines if using Google Colab<br>import nest_asyncio<br>nest_asyncio.apply()<br><br>api_id=&#39;API_ID&#39;<br>api_hash=&#39;API_HASH&#39;<br>session_name= &#39;session1&#39;<br>## must be your channel or have authorization to post<br>channel_invite_link = &#39;t.me/AICats_Prompt&#39; <br><br><br>async def func():<br>    entity = await client.get_entity(channel_invite_link)<br>    # Send an image follow by a text.<br>    await client.send_file(entity, &#39;/file/to/media.jpeg&#39;) <br>    await client.send_message(entity=entity, message=&quot;Your text&quot;) <br><br># connection<br>async with TelegramClient(session_name, api_id, api_hash) as client:<br>    client.loop.run_until_complete(func())</pre><p>Notes</p><ol><li>The session name can be any arbitrary name. If an error occurs with the session name being locked, use a new random session name.</li><li>The channel should either be your own, or you must have authorization to post.</li></ol><h3>Dowloading Images</h3><p>The same method can be used to download media or other content from any Telegram channel.</p><pre>import uuid<br>from telethon import TelegramClient<br>import asyncio<br><br>## Run the following 2 lines if using Google Colab<br>import nest_asyncio<br>nest_asyncio.apply()<br><br>api_id=&#39;API_ID&#39;<br>api_hash=&#39;API_HASH&#39;<br>session_name= &#39;session1&#39;<br>channel_invite_link = &#39;t.me/AICats_Prompt&#39;<br><br>async def func():<br>    entity = await client.get_entity(channel_invite_link)<br>    messages = []<br>    #download images from last 10 messages<br>    async for m in client.iter_messages(entity, reverse=False, limit = 10): <br>        messages.append(m)<br><br>    for m in reversed(messages):<br>        print(await m.download_media(f&quot;image/{uuid.uuid1()}&quot;))<br><br>async with TelegramClient(username, api_id, api_hash) as client:<br>    client.loop.run_until_complete(func())</pre><p>Notes</p><ol><li>The messages are displayed from most recent to oldest by default, ensuring you always receive the latest message first. To access the oldest message first, you can use reverse=True.</li><li>You can include a filter in client.iter_messages to specify and filter out specific message types, such as photos, etc. <a href="https://docs.telethon.dev/en/stable/modules/client.html">You can refer to official telethon documentation</a> for more filters selection.</li></ol><h3><strong>Conclusion</strong></h3><p>Above is a simple method for sending messages and files to a Telegram channel using Python. Additionally, we can use the same API to download images. The Telethon library offers many other functions that you can explore for your specific needs. Have fun getting started with your first Telegram project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c1abeea7a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Google Bard for Latest Stock Analysis and Information? Think Again]]></title>
            <link>https://medium.com/@kokhua81/using-google-bard-for-latest-stock-analysis-and-information-think-again-21ab85f78221?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ab85f78221</guid>
            <category><![CDATA[stock-analysis]]></category>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[google-bard]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 08:12:19 GMT</pubDate>
            <atom:updated>2023-06-22T08:13:41.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Using google bard for stock analysis and information getter. Can it really be used?" src="https://cdn-images-1.medium.com/max/1024/1*XNCJ5iMCl02CWyEBsJpjtA.png" /></figure><p>Google Bard is a conversational generative AI chatbot developed by Google that, much like OpenAI, utilizes an LLM (Language Model) to enable interactive and dynamic conversations. In the previous post <a href="https://medium.com/@kokhua81/integrating-google-bard-with-python-via-bard-api-5f242b88e1f0">on using python with Google Bard</a>, we discussed how we can utilize Python to connect with Google Bard. We highlighted two advantages of Google Bard over OpenAI, namely its ability to provide up-to-date information and its availability as a free tool.</p><p>In this post, I will explore the application of Google Bard in stock analysis and screening, leveraging its access to the latest and most current information.</p><p>To start off, we will use Google Bard to retrieve key financial metrics of NVIDIA and its competitors. These metrics will include the most recent Price, Price-to-Earnings (P/E) Ratio, Earnings Per Share (EPS), Price-to-Book (P/B) Ratio, Dividend Yield, Debt-to-Equity Ratio, and more.</p><p>The following Python script will send the prompt to BARD and request BARD to return the data in a format that can be easily parsed into a Pandas dataframe for further processing.</p><pre>import requests<br>import os, re, json<br>from bardapi import Bard<br>import pandas as pd<br>os.environ[&#39;_BARD_API_KEY&#39;]=&quot;__Secure-1PSID Key&quot;<br><br># Create a session object using the requests library<br>session = requests.Session()<br><br># Set the headers for the session<br>session.headers = {<br>            &quot;Host&quot;: &quot;bard.google.com&quot;,<br>            &quot;X-Same-Domain&quot;: &quot;1&quot;,<br>            &quot;User-Agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36&quot;,<br>            &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded;charset=UTF-8&quot;,<br>            &quot;Origin&quot;: &quot;https://bard.google.com&quot;,<br>            &quot;Referer&quot;: &quot;https://bard.google.com/&quot;,<br>        }<br><br># Set the &quot;__Secure-1PSID&quot; cookie with the Bard API key<br>session.cookies.set(&quot;__Secure-1PSID&quot;, os.getenv(&quot;_BARD_API_KEY&quot;))<br><br># Create a Bard object with the session and a timeout of 30 seconds<br>bard = Bard(session=session, timeout=30)<br><br># Send an API request and get a response<br>query  = &#39;I am looking for AMD, INTC, NVDA, MU, XLNX stocks. \<br>        Please provide to your best of your knowledge their most recent Price, Price-to-Earnings (P/E) Ratio, Earnings Per Share (EPS), \<br>        Price-to-Book (P/B) Ratio, Dividend Yield, Return on Equity (ROE), Debt-to-Equity Ratio, \<br>         in tabular format. return as json so i can pass to python pandas. Do not include other text. start with &quot;The json is :&quot;&#39;<br><br>query = re.sub(&#39;\s\s+&#39;, &#39;&#39;, query)<br>output = bard.get_answer(query)[&#39;content&#39;]<br><br>## Parse as pandas dataframe<br>json_str = re.search(r&#39;json({.*\})&#39;, output.replace(&#39;\n&#39;,&#39;&#39;), re.MULTILINE | re.DOTALL).group(1)<br>data = json.loads(json_str)<br>df = pd.DataFrame(data[&#39;data&#39;])<br>print(df)</pre><p>Below is the output generated on Jun 22 2023 from Google Bard. Something caught my eye — the NVIDIA current price is not correct, and I also checked the EPS and debt-to-equity ratio, which are also incorrect. We will prompt Google Bard further to understand more.</p><pre>  Symbol   Price    P/E   EPS    P/B  Dividend Yield    ROE  Debt/Equity<br>0    AMD  102.25  33.45  3.07   2.89            0.07  29.56         0.32<br>1   INTC   47.26  10.21  4.63   1.72            3.02  33.06         0.37<br>2   NVDA  219.47  37.85  5.83  12.42            0.00  47.15         0.09<br>3     MU   60.43   9.75  6.21   2.01            2.88  33.67         0.33<br>4   XLNX  172.85  19.38  8.93   3.10            0.00  34.11         0.34</pre><figure><img alt="Incorrect Stock data generated by Google Bard when trying to use Bard to provide updated stock information" src="https://cdn-images-1.medium.com/max/772/1*gxFB7_eN2r4kvMelYQaWHA.png" /><figcaption>Incorrect Stock data generated by Google Bard</figcaption></figure><p>I believe the other stock data is also flawed. Even if Google Bard claims to have updated data, it appears to be unreliable for stock analysis in this aspect. Unfortunately, it doesn’t seem suitable for my needs in terms of analyzing stocks.</p><p><strong>Getting Stocks News</strong></p><p>I attempted another simpler experiment, this time focusing on obtaining the most recent news about Nvidia for sentiment analysis. Below is prompt and respective output from Bard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*l7vhLrIR-fLv9P45vhdykg.png" /><figcaption>The date of the NVIDIA news generated by Bard is incorrect.</figcaption></figure><p>I believe some of the dates are incorrect, particularly the news about acquiring ARM for $40 Billion, which is from 2022. It seems that Google Bard does not provide the latest news.</p><p><strong>Conclusion</strong></p><p>Based on the two studies above, I am not convinced that Google Bard is a suitable tool for retrieving the latest stock information and news. Even if Bard does provide some output, I am hesitant to trust the data’s accuracy, as it may cloud my insights when making actual stock purchases. However, I believe it can still be used to retrieve information about a company, especially when the information is less recent. Nevertheless, I would exercise caution and double-check any information provided by Google Bard before making any decisions at this stage.</p><p><strong>A side experiment..</strong></p><p>I am not surprised that Bard is able to gather information about my chrome browser or even my PC. However, I am surprised that it displayed the output and even offered to close the tabs for me. By the way, the list of tabs displayed is not correct…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*gy-OKRsZLTNiw9I0k99NcQ.png" /><figcaption>Bard getting information from my browser</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ab85f78221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Google Bard with Python via Bard-API]]></title>
            <link>https://medium.com/@kokhua81/integrating-google-bard-with-python-via-bard-api-5f242b88e1f0?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f242b88e1f0</guid>
            <category><![CDATA[google-bard]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[google-bard-api]]></category>
            <category><![CDATA[chatgpt-alternative]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 08:53:44 GMT</pubDate>
            <atom:updated>2023-06-19T08:53:44.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Using Google Bard in Python via bardapi" src="https://cdn-images-1.medium.com/max/1024/1*iwahf_GLA-oh2o-927Bo2w.png" /></figure><p>Google Bard is a large language model (LLM) similar to OpenAI’s ChatGPT, capable of answering questions, generating creative text, translating languages, and producing various forms of creative content. Currently, Google Bard is available to the public, but in a limited beta release. Users can join a waitlist to apply for <a href="https://bard.google.com/">access to Bard</a>.</p><p>For those eager to integrate Google Bard with Python, it is important to note that there is currently no official API available. However, we can utilize <a href="https://github.com/dsdanielpark/Bard-API">Daniel Park’s bardapi</a> to use in python environment.</p><p>There are several advantages of using Google Bard (bardapi version) over OpenAI (API version).</p><ol><li>Bard is more up-to-date compared to OpenAI, whose knowledge cutoff was in September 2021.</li><li>Bard is currently available for free usage unlike the OpenAI API version.</li><li>Bardapi has the ability to understand chat history, which is not readily available with the OpenAI API. However, it is worth noting that by leveraging tools like LangChain, it is possible to integrate memory state functionality with the OpenAI API, enabling similar capabilities.</li></ol><p>Below is a sample guide on how to integrate Bard with python using the Bardapi.</p><pre># Script reference: https://github.com/dsdanielpark/Bard-API<br><br>from bardapi import Bard<br>import os<br>import requests<br>os.environ[&#39;_BARD_API_KEY&#39;] = &#39;xxxxxxx&#39;<br><br># This will allow us to continue conversation with Bard in separate query<br>session = requests.Session()<br><br>session.headers = {<br>            &quot;Host&quot;: &quot;bard.google.com&quot;,<br>            &quot;X-Same-Domain&quot;: &quot;1&quot;,<br>            &quot;User-Agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36&quot;,<br>            &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded;charset=UTF-8&quot;,<br>            &quot;Origin&quot;: &quot;https://bard.google.com&quot;,<br>            &quot;Referer&quot;: &quot;https://bard.google.com/&quot;,<br>        }<br><br>session.cookies.set(&quot;__Secure-1PSID&quot;, os.getenv(&quot;_BARD_API_KEY&quot;)) <br><br>bard = Bard(token=token, session=session, timeout=30)<br>bard.get_answer(&quot;We will talk about latest presidents in Germany and Italy. Who are they&quot;)[&#39;content&#39;]<br><br># Continued conversation without set new session<br>bard.get_answer(&quot;What we talk about just now??&quot;)[&#39;content&#39;]</pre><figure><img alt="Python Bard API continuing conversation within a session" src="https://cdn-images-1.medium.com/max/1024/1*CEZSkVS0_aadCwzwx56q0w.png" /><figcaption>Bardapi: understanding chat history</figcaption></figure><p>Google Bard also has the ability to return images, which has been enabled in the development version of Bard-API. We can expect this feature to be available in the production version soon.</p><p><strong>Conclusion</strong></p><p>In conclusion, the Bard-API package provides a practical and effective means to interact with Google Bard’s response API within your Python environment, bridging the gap until the official release of the Bard API.</p><p>By utilizing Bard-API, you can fully explore and leverage the capabilities of Bard, allowing you to experiment with various queries and unlock the valuable insights it has to offer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f242b88e1f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PandasAI — Exploratory Data Analysis with Pandas and AI prompts]]></title>
            <link>https://medium.com/@kokhua81/pandasai-exploratory-data-analysis-with-pandas-and-ai-prompts-111212cda304?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/111212cda304</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[pandas-ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 09:20:36 GMT</pubDate>
            <atom:updated>2023-08-05T08:56:07.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>PandasAI — Exploratory Data Analysis with Pandas and AI prompts</h3><figure><img alt="PandasAI — Exploring DataFrame with Pandas and AI prompts" src="https://cdn-images-1.medium.com/max/1024/1*7CJoNrsN7hJOH4e06dqSqQ.png" /></figure><p>I came across <a href="https://github.com/gventuri/pandas-ai">PandasAI</a> while searching for AI integration with Pandas dataframes. My primary objective is to conduct fast exploratory data analysis on new datasets, which would guide my future analysis approach. PandasAI appeared to meet my needs in this regard. In summary, PandasAI is a Python library that seamlessly integrates generative artificial intelligence capabilities (eg Openai) into Pandas, enabling users to perform basic Pandas operations using simple text prompts. It’s worth noting that PandasAI is designed to complement rather than replace Pandas.</p><p>What I like about pandasAI</p><ol><li>Alternatives LLM integration: Besides openai, PandasAI support integration with Hugging Face’s Starcoder, which is free to use and works pretty well with PandasAI</li><li>Return Dataframe Object: PandasAI returns dataframe objects that can be further processed by Pandas or PandasAI itself.</li><li>Simplified Plotting process: PandasAI simplifies common plotting tasks for easy data visualization.</li></ol><p>In the following sections, we explore a range of common tasks that can be performed by prompting the dataframe instead of the usual pandas operations. We will use a sample dataset “Penguins” loaded from seaborn as our study. We will also be using the <a href="https://www.google.com/search?q=hugging+face+star+coder&amp;rlz=1C1GCEA_enSG927SG927&amp;sxsrf=APwXEdc-CI4kGQasRjFc9btEitWXCln-qw%3A1686906488590&amp;ei=eCaMZKilI_jx4-EP6vaGoA8&amp;ved=0ahUKEwiowZWwuMf_AhX4-DgGHWq7AfQQ4dUDCBA&amp;uact=5&amp;oq=hugging+face+star+coder&amp;gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIFCAAQgAQ6CggAEEcQ1gQQsAM6BwgjELECECc6DggAEIoFELEDEIMBEJECOhMILhCKBRCxAxCDARDHARDRAxBDOggIABCKBRCRAjoHCAAQgAQQCjoHCCMQsAIQJzoZCC4QDRCABBCxAxCDARCxAxCDARDHARDRAzoNCAAQDRCABBCxAxCDAToHCAAQDRCABDoECCMQJzoHCCMQigUQJzoKCAAQgAQQFBCHAjoNCAAQigUQsQMQgwEQQzoLCAAQgAQQsQMQgwE6BggAEBYQHjoICAAQigUQhgNKBAhBGABQ7wFYmBhg5hloAnABeACAAWGIAdwGkgECMTSYAQCgAQHAAQHIAQg&amp;sclient=gws-wiz-serp">Hugging Face starcoder</a> LLM which is free. However, I find that openai is able to deliver the right output with longer and more complex prompt.</p><pre>pip install pandasai</pre><pre># Setting up for prompt<br>import pandas as pd<br>from pandasai import PandasAI<br>from pandasai.llm.starcoder import Starcoder<br>from pandasai.llm.openai import OpenAI<br>import seaborn as sns<br><br># Instantiate a LLM<br># Openai<br># llm = OpenAI(api_token=&quot;openai_key&quot;)<br><br># Starcoder<br>llm = Starcoder(api_token=&quot;hugging face api key&quot;)<br>pandas_ai = PandasAI(llm)<br><br># Load dataset<br>penguins = sns.load_dataset(&quot;penguins&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*Vu8vh-4cdaD7CvtetJ2enQ.png" /><figcaption>Basic Operations prompt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*zx0m9eGCFmnYwhrsaoaiBw.png" /><figcaption>NA operations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*1woPWsj7cRdfgZTrqGfUjA.png" /><figcaption>Fillna and row operations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*uPjKpiJSDZAmCckXIBDwTg.png" /></figure><p>There are some cases where I did not managed to get an output (openai llm might do a better job) such as below.</p><pre># it set to the penguins dataframe instead.<br>penguins_update = pandas_ai(penguins, prompt= &#39;return a copy. penguin[ bill_length_mm] = 0 if island = Torgersen&#39;, show_code=True) <br># Does not return any output <br>penguins_newcol = pandas_ai(penguins, prompt= &#39;Add new column &quot;bill_length_cm&quot; by taking &quot;bill_length_mm&quot; /100.&#39;)</pre><p>In conclusion, PandasAI excels at enabling simple and clean exploratory analysis, particularly with its seamless integration of Starcoder, which eliminates cost concerns. However, it may not perform as effectively with longer and more complex prompts, especially when used with Starcoder. It’s important to note that while PandasAI offers valuable functionalities, you will still rely on Pandas for more extensive data manipulation and analysis tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=111212cda304" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Web Analytics Data using Python & Adobe Analytics 2.0 APIs]]></title>
            <link>https://medium.com/@kokhua81/extracting-web-analytics-data-using-python-adobe-analytics-2-0-apis-d6192fd0803e?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6192fd0803e</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[web-analytics]]></category>
            <category><![CDATA[adobe-analytics]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[adobe-analytics-api]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 05:40:20 GMT</pubDate>
            <atom:updated>2023-08-04T08:41:19.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Sailing through the Threads of Web Analytics with python and Adobe Analytics API" src="https://cdn-images-1.medium.com/max/1024/1*7OCIH2r0rK27mEcAxNhMwQ.png" /></figure><p>The Adobe Analytics 2.0 APIs provide a powerful way to directly interact with Adobe’s servers, enabling you to perform various actions programmatically that were previously only available through the user interface. In this blog post, we will explore how to leverage Python and the 2.0 API to extract web analytics data from Adobe Analytics.</p><p><strong>Getting Started: OAuth Server-to-Server Credentials</strong></p><p>The Service Account (JWT) credentials have been deprecated in favor of the OAuth Server-to-Server credentials. This guide will focus on using the latter. To obtain the API, Client and Secret key, you can refer to the official <a href="https://developer.adobe.com/developer-console/docs/guides/authentication/ServerToServerAuthentication/implementation/">Adobe Developer documentation</a> on the setup.</p><p><strong>Authenticating and Accessing Adobe Analytics 2.0 API with Python</strong></p><p>The following Python script demonstrates the authentication process and making consecutive API requests using Authlib.</p><pre>import requests<br>from authlib.integrations.requests_client import OAuth2Session<br><br># Configure the Adobe Analytics API credentials<br>client_id = &#39;YOUR CLIENT ID&#39;<br>client_secret = &#39;YOUR CLIENT SECRET&#39;<br>token_endpoint = &#39;https://ims-na1.adobelogin.com/ims/token&#39;<br>company_name = &#39;TGT_COMPANY&#39;<br><br># Create an OAuth2Session object with the client credentials<br>oauth = OAuth2Session(client_id, client_secret, scope=&#39;openid AdobeID additional_info.projectedProductContext&#39;)<br><br># Fetch the access token from Adobe IMS<br>token = oauth.fetch_token(token_endpoint)<br><br>## Test a simple GET query<br>api_url = r&#39;https://analytics.adobe.io/api/{}/annotations?locale=en_US&amp;limit=10&amp;page=0&amp;sortProperty=id&#39;.format(company_name)<br><br>headers = {<br>    &#39;Authorization&#39;: &#39;Bearer &#39; + token[&#39;access_token&#39;],<br>    &#39;x-api-key&#39;: client_id<br>}<br>response = requests.get(api_url, headers=headers)<br><br>if response.status_code == 200:<br>    data = response.json()<br>    print(data)<br>else:<br>    print(&#39;Error:&#39;, response.status_code, response.text)</pre><p><strong>Using the Reporting API</strong></p><p>The /reports endpoint serves as the primary endpoint for reporting requests to retrieve web analytics metrics. Since the /reports endpoint utilizes the same API as the Analytics Workspace UI, it offers extensive configuration options. To initiate a report request, we must provide a Date Range, Metrics, and at least one Dimension. The /reports endpoint requires a specific JSON data structure to define the requested report. You can refer to the sample code below for the structure. For more informationon creating the JSON Structure, you can visit the<a href="https://github.com/AdobeDocs/analytics-2.0-apis/blob/master/reporting-guide.md"> Adobe Analytics Docs.</a></p><pre># Setting up for the JSON Structure<br># Getting the Visits and Page views from Jun 1st to Jun 5th group<br># by each day results.<br><br>RSID = &#39;Report Suite ID&#39;<br>START_DATE = &#39;2023-06-01&#39;<br>END_DATE = &#39;2023-06-05&#39;<br>MIDNIGHT = &#39;T00:00:00.000&#39;<br>DATE_RANGE = START_DATE + MIDNIGHT + &#39;/&#39; + END_DATE + MIDNIGHT<br><br>DIM = &#39;variables/daterangeday&#39;<br>METS = [&#39;metrics/visits&#39;,&#39;metrics/pageviews&#39;]<br>METS_OBJ = [{&#39;id&#39;:x} for x in METS]<br><br>query_json = {<br>               &quot;rsid&quot;:RSID,<br>               &quot;globalFilters&quot;:[<br>                  {<br>                        &quot;type&quot;:&quot;dateRange&quot;,<br>                        &quot;dateRange&quot;:DATE_RANGE<br>                  }<br>               ],<br>               &quot;metricContainer&quot;:{<br>                  &quot;metrics&quot;:METS_OBJ,<br>                   <br>              },<br>               &quot;dimension&quot;:DIM,<br>               &quot;settings&quot;:{<br>                  &quot;dimensionSort&quot;:&quot;asc&quot;<br>               }<br>}<br><br>api_url = r&#39;https://analytics.adobe.io/api/{}/reports&#39;.format(company_name)<br><br>response =requests.post(url=api_url, headers=headers, json=query_json)<br><br># Process the response<br>if response.status_code == 200:<br>    data = response.json()<br>else:<br>    print(&#39;Error:&#39;, response.status_code, response.text)</pre><p><strong>Formatting the Response Output</strong></p><p>Upon receiving the response from the /reports endpoint, you can format the output in a tabular structure for better readability and analysis.</p><pre>df  =pd.DataFrame(response.json()[&#39;rows&#39;])<br>df.columns = [DIM+&#39;_key&#39;,DIM,&#39;data&#39;] #rename columns<br><br>dfa = pd.DataFrame(df[&#39;data&#39;].to_list())<br>dfa.columns = METS<br><br>output = pd.concat([df.iloc[:,:-1],dfa],axis=&#39;columns&#39;)<br>output</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*XtdIjf3GDFn_286zOZLDbw.png" /><figcaption>Sample output with Visits and page views by date</figcaption></figure><p><strong>Conclusion</strong></p><p>We can leverage Python and the Adobe Analytics 2.0 APIs to provides a automated solution for extracting web analytics data. By utilizing OAuth Server-to-Server credentials and making API requests, we can automate data retrieval, generate custom reports, storing to databaes and gain valuable insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6192fd0803e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless Prompt Generation: Auto-generating AI System Prompt Phrases with ChatGPT]]></title>
            <link>https://medium.com/@kokhua81/effortless-prompt-generation-auto-generating-ai-system-prompt-phrases-with-chatgpt-dce861d96d8c?source=rss-e7322e3e8b09------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce861d96d8c</guid>
            <category><![CDATA[ai-prompt-engineering]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-custom-knowledge]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[openai-chatgpt]]></category>
            <dc:creator><![CDATA[Kok Hua]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 06:24:00 GMT</pubDate>
            <atom:updated>2023-06-07T06:27:55.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMyYzffXss98dc53LO1PvQ.jpeg" /></figure><p>Prompt engineering is essential for optimizing behavior and output of AI systems like ChatGPT. Creating effective prompts is challenging and time-consuming, especially when tailoring them for different roles/persona. However, we can utilize ChatGPT’s capabilities to generate prompts for us.</p><p>By empowering ChatGPT with custom knowledge on crafting effective prompts, we enable it to learn the skill of generating prompts tailored to various roles. To impart this custom knowledge, we leverage a collection of websites that provide good instances of well-crafted system prompts.</p><p>In this blog post, we will explore using Python, ChatGPT, and the LangChain module to generate role-specific prompt phrases. LangChain is a versatile tool that enables the conversion of external sources into document objects. Converted document objects can then be indexed in databases like Chroma, enabling fast and efficient information retrieval. This integration allows AI systems such as ChatGPT to access a broad spectrum of knowledge sources.</p><h4>Setting up the Environment</h4><p>Below code snippet demonstrates the necessary steps to extract additional data from websites, create embeddings, utilize Chroma vector store, load documents from the web, and persist the processed instance. These steps lay the foundation for generating system prompt phrases using the extracted data.</p><pre># intalling the necessary libraries in Jupyter<br>!pip install tiktoken<br>!pip install openai<br>!pip install chromadb<br>!pip install langchain<br>!pip install nest_asyncio</pre><pre>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.llms import OpenAI<br>from langchain.chains import RetrievalQA<br>from langchain.chat_models import ChatOpenAI<br>from langchain.document_loaders import WebBaseLoader<br>from langchain.prompts import PromptTemplate<br>import nest_asyncio<br><br>nest_asyncio.apply()<br><br># sample website with good system prompts<br>tgt_sites = [&#39;https://github.com/f/awesome-chatgpt-prompts&#39;,<br>               &#39;https://www.greataiprompts.com/prompts/best-system-prompts-for-chatgpt/&#39;,<br>               &#39;https://stackdiary.com/chatgpt/role-based-prompts/&#39;]<br><br>def add_documents(loader, instance):<br>    documents = loader.load()<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100, separators= [&quot;\n\n&quot;, &quot;\n&quot;, &quot;.&quot;, &quot;;&quot;, &quot;,&quot;, &quot; &quot;, &quot;&quot;])<br>    texts = text_splitter.split_documents(documents)<br>    instance.add_documents(texts)<br><br>embeddings = OpenAIEmbeddings(openai_api_key=&#39;YOUR_OPENAI_API_KEY&#39;)<br>instance = Chroma(embedding_function=embeddings, persist_directory=&#39;PATH_TO_PERSIST_DIRECTORY&#39;)<br><br>loader = WebBaseLoader(tgt_sites)<br>if loader:<br>    add_documents(loader, instance)<br><br>instance.persist()<br>instance = None<br><br>instance = Chroma(persist_directory=&#39;PATH_TO_PERSIST_DIRECTORY&#39;, embedding_function=embeddings)</pre><h4>Generating System Prompt Phrases</h4><p>Now that we have set up our environment and loaded the necessary data, we can proceed to generate system prompt phrases using ChatGPT. We will utilize the RetrievalQA class from Langchain, which incorporates the ChatOpenAI model to interact with the language model. Here is the code snippet to generate system prompt phrases:</p><pre>qa = RetrievalQA.from_chain_type(<br>    llm=ChatOpenAI(<br>        model_name=&quot;gpt-3.5-turbo&quot;,<br>        temperature=0,<br>        openai_api_key=&#39;YOUR_OPENAI_API_KEY&#39;<br>    ),<br>    chain_type=&quot;stuff&quot;,<br>    retriever=instance.as_retriever()<br>)<br><br>query_str = &quot;&quot;&quot;<br>              Craft a paragraph of how chatgpt (address as you) supposed to act based on the role stated. <br>              Provide expectation of the required scope, skillset and knowledge. <br>              If there is no specific role found, use relative reference if necessary. <br>              The role is &quot;python blog professional writer&quot;. Maximium 5 sentences. <br>              Start the paragraph with &quot;I want you to act as a &quot;<br><br>            &quot;&quot;&quot;<br>output_string = qa.run(query_str)<br>print(output_string)</pre><pre>[Sample output]<br>I want you to act as a Python blog professional writer. As a ChatGPT, you are expected to have a good understanding of Python programming language and its various libraries and frameworks. You should be able to write informative and engaging blog posts that cater to both beginners and advanced users. Your writing should be clear, concise, and well-structured, with a focus on providing practical examples and use cases.Additionally, you should be able to keep up with the latest trends and developments in the Python community and incorporate them into your writing. </pre><p>In this script, our focus is on generating system role prompts. You can append your specific requests or target tasks to these prompts for ChatGPT to understand and respond accordingly. To enhance ChatGPT’s capabilities, you can include additional relevant websites, expanding its knowledge base for prompt generation in various roles and scenarios.</p><h3><strong>Conclusion</strong></h3><p>In this blog post, we explored the process of using ChatGPT and additional data extracted from a webpage to generate system prompt phrases. By leveraging the power of language models and retrieval techniques, we can create informative and context-aware prompts to guide AI systems more efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce861d96d8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>