<?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 Arjun tewari on Medium]]></title>
        <description><![CDATA[Stories by Arjun tewari on Medium]]></description>
        <link>https://medium.com/@arjuntewari0505?source=rss-c02f1de4b1b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HBmnc5LlwRwdQZ8L52JTKQ.jpeg</url>
            <title>Stories by Arjun tewari on Medium</title>
            <link>https://medium.com/@arjuntewari0505?source=rss-c02f1de4b1b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:40:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arjuntewari0505/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[Your AI Is Lying to You — Here’s the RAG Hack That Fixes It]]></title>
            <link>https://medium.com/@arjuntewari0505/your-ai-is-lying-to-you-heres-the-rag-hack-that-fixes-it-c79ed95ec9e4?source=rss-c02f1de4b1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79ed95ec9e4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[document-management]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Arjun tewari]]></dc:creator>
            <pubDate>Mon, 19 May 2025 14:12:01 GMT</pubDate>
            <atom:updated>2025-05-19T14:12:01.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*knJ1d7QAE0WybdytNkD-NQ.png" /></figure><h3>Your AI Is Lying to You — Here’s the RAG Hack That Fixes It</h3><p><strong>Retrieval-Augmented Generation (RAG)</strong> has revolutionized the way AI systems answer questions. Instead of relying solely on model memory, RAG enhances responses with relevant knowledge pulled from external sources, like vector databases.</p><p>But what if <strong>one query isn’t enough</strong> to capture all the nuances of a user’s intent?</p><p>Enter <strong>Multi-Query Retrieval</strong> — a powerful RAG enhancement that expands a user’s question into multiple semantically rich variants, improving the relevance and coverage of retrieved documents.</p><p>In this blog post, we’ll dissect a working RAG pipeline using multi-query retrieval, explain each node’s role, and walk through <strong>where and why this technique shines</strong>.</p><h3>🤖 What is Multi-Query Retrieval?</h3><p>When a user asks a question like <em>“What are the benefits of green tea?”</em>, a single search query might not capture all relevant information. By rephrasing or expanding it into multiple queries like:</p><ul><li>“Health benefits of drinking green tea”</li><li>“How does green tea affect the body?”</li><li>“Green tea and metabolism improvement”</li></ul><p>…we drastically <strong>increase the chances of retrieving diverse and comprehensive documents</strong>.</p><p>This strategy is especially effective in:</p><ul><li>Question Answering Systems</li><li>Chatbots and Virtual Assistants</li><li>Legal/medical document search</li><li>Academic research helpers</li><li>Enterprise knowledge bases</li></ul><h3>🔍 Breakdown of the Architecture</h3><p>Let’s walk through each component of the visual pipeline.</p><h3>⚡ 1. Trigger: When Chat Message Received</h3><p>This is the event trigger. It begins the process once a user sends a message.</p><h3>🔗 2. Question and Answer Chain</h3><p>This is the <strong>central RAG orchestration</strong> block. It handles:</p><ul><li>Accepting the user’s question</li><li>Performing retrieval via the retriever chain</li><li>Generating the final answer using the documents fetched</li></ul><h3>🧠 3. OpenAI Chat Model 1</h3><p>This model generates <strong>multiple query variants</strong> from the user’s original question.<br> It acts as the <strong>query expander</strong>, leveraging the semantic understanding of LLMs to produce alternate phrasings.</p><h3>📦 4. MultiQuery Retriever</h3><p>Receives multiple queries from the first Chat Model and forwards them to a downstream retriever.</p><p>Think of this as a <strong>dispatcher</strong>: it uses every query to search the knowledge base and collect results.</p><h3>🔍 5. Vector Store Retriever</h3><p>This retriever connects to the actual database (in this case, a <strong>vector store</strong> like Pinecone). It finds relevant chunks of documents based on <strong>semantic similarity</strong> to the queries.</p><p>It uses <strong>embeddings</strong> to match meanings, not just keywords.</p><h3>🧠 6. OpenAI Chat Model 2</h3><p>This is the <strong>response generator</strong>.</p><p>Using the original user question and the set of retrieved documents, it formulates a final, grounded, and contextually rich answer.</p><h3>🧠 7. Embeddings: OpenAI2</h3><p>This node generates <strong>embeddings</strong> for documents being stored in the vector database (Pinecone).<br> Embeddings are dense numeric representations of text that capture meaning — and they’re <strong>key to semantic search</strong>.</p><h3>🗃️ 8. Pinecone Vector Store</h3><p>A high-performance <strong>vector database</strong> that stores the embeddings of your knowledge base documents. It enables <strong>fast and accurate similarity search</strong> during the retrieval step.</p><h3>💡 Why This Setup Works So Well</h3><p>Here’s why this RAG setup with multi-query retrieval excels:</p><h3>✅ 1. Increased Recall</h3><p>Different phrasing fetches different sets of results, making sure you don’t miss relevant documents.</p><h3>✅ 2. Context Rich Answers</h3><p>Combining diverse document snippets gives the LLM more to work with, reducing hallucination.</p><h3>✅ 3. Scalable Architecture</h3><p>Using vector stores like Pinecone ensures the system can handle large volumes of documents efficiently.</p><h3>📈 Real-World Use Cases</h3><ul><li><strong>Legal AI Assistants:</strong> Expand legal queries to ensure rare case laws aren’t missed.</li><li><strong>Medical Chatbots:</strong> Retrieve comprehensive literature for symptoms or drug effects.</li><li><strong>Enterprise Knowledge Retrieval:</strong> Surface FAQs, policies, and internal docs from scattered sources.</li></ul><h3>🔚 Conclusion</h3><p>Multi-query retrieval brings a <strong>precision-enhancing superpower</strong> to your RAG pipeline.</p><p>By leveraging the semantic intelligence of LLMs to reframe the question multiple ways, you open the door to <strong>richer, more accurate, and more human-like answers.</strong></p><p>If you’re building AI apps that require <strong>trustworthy and knowledge-grounded responses</strong>, this architecture is your best friend.</p><h3>🧠 TL;DR</h3><ul><li>Multi-query retrieval = One question → Multiple semantically different queries</li><li>Increases document coverage and answer quality</li><li>Ideal for knowledge-intensive applications like chatbots, legal assistants, and internal tools</li><li>OpenAI + Pinecone + Embedding = 🔥 Semantic Powerhouse</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79ed95ec9e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This AI Bot Reads Finds Trends, and Posts on LinkedIn and X — So I Don’t Have To]]></title>
            <link>https://medium.com/@arjuntewari0505/this-ai-bot-reads-finds-trends-and-posts-on-linkedin-and-x-so-i-dont-have-to-d560b651383e?source=rss-c02f1de4b1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d560b651383e</guid>
            <category><![CDATA[n8n-workflow]]></category>
            <category><![CDATA[ai-automation]]></category>
            <category><![CDATA[ai-content-generator]]></category>
            <category><![CDATA[content-creation]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Arjun tewari]]></dc:creator>
            <pubDate>Tue, 06 May 2025 11:52:12 GMT</pubDate>
            <atom:updated>2025-05-06T11:52:12.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>This AI Bot Reads Finds Trends, and Posts on LinkedIn and X — So I Don’t Have To</h3><p>One line of code didn’t change my life. One workflow did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WHiXZiVnyDiaTij8Lrzvw.png" /></figure><h3><strong>The Dream: Post Like a Thought Leader, Live Like an Engineer</strong></h3><p>If you’re anything like me, you’ve probably tried to stay consistent on LinkedIn and X (formerly Twitter) only to burn out a week later. Between trend research, writing, editing, formatting, and scheduling — it’s a full-time job. So, I did what any curious AI enthusiast would: I automated it.</p><p>This isn’t just another RSS-to-post script. It’s a full-blown, AI-powered, trend-aware, multi-agent content pipeline. Here’s how I built an autopilot for my personal brand — and how you can, too.</p><p><strong>The Stack</strong></p><ul><li><strong>n8n</strong> — Low-code automation backbone</li><li><strong>OpenAI GPT-4</strong> — LLM for writing content</li><li><strong>SerpAPI</strong> — Finds current news and trends</li><li><strong>NewsAPI</strong> — Supplements with headlines and summaries(Optional)</li><li><strong>LinkedIn API</strong> — Posts professional updates</li><li><strong>X API</strong> — Tweets trending thoughts</li><li><strong>RSS Feeds</strong> — Langchain, OpenAI, Latent Space (rotated daily)</li></ul><h3><strong>🔁 The Workflow</strong></h3><p>Here’s how the magic happens:</p><h3>1. RSS Feeds Trigger Daily</h3><p>Every day, one of three carefully chosen RSS feeds (Langchain, OpenAI, LatentSpace) is triggered in rotation, making sure the content doesn’t repeat and stays balanced between tech, AI, and startup news.</p><h3>2. AI Agent Writes Contextual Content</h3><p>The feed is passed to an OpenAI-powered content agent. This agent is also equipped with:</p><ul><li><strong>Memory</strong> for past styles</li><li><strong>Structured output parser</strong> to maintain tone and formatting</li><li><strong>SerpAPI + NewsAPI</strong> to enrich with current trends and insights</li></ul><h3>3. Content is Refined and Transformed into Posts</h3><p>A simple code module formats it into a short-form post (for LinkedIn) and a tweet (for X).</p><h3>4. LinkedIn + X Auto Publishing</h3><ul><li>The LinkedIn post is published using LinkedIn’s /ugcPosts endpoint.</li><li>The tweet is sent via the X (Twitter) API, with fallback checks for rate limits and errors.</li></ul><p>No copy-paste. No buffer. No scheduling apps. Pure automation.</p><h3>🧪 What I Learned</h3><ul><li><strong>OAuth is painful</strong> — Setting up LinkedIn’s and X’s access tokens was the hardest part. Getting scopes and redirect URIs right took hours.</li><li><strong>Trends = Engagement</strong> — Combining RSS with real-time trend APIs like SerpAPI dramatically improved the relevance of the content.</li><li><strong>Structured AI &gt; Raw AI</strong> — Using structured output parsers helped maintain tone, limit hallucinations, and avoid broken formatting.</li></ul><h3>🚀 What’s Next?</h3><p>I plan to add:</p><ul><li><strong>Analytics feedback loop</strong> — to tune content based on what performs</li><li><strong>Sentiment-aware posting</strong> — so the tone matches trending emotions</li><li><strong>Custom brand voice</strong> — trained on my previous posts</li></ul><p>And yes, maybe a “pause if I’m sleeping” toggle 😉</p><h3>🫡 Final Thoughts</h3><p>This project isn’t just automation — it’s augmentation. A way to scale your digital presence while focusing on what matters: building, learning, and sharing.</p><p>If you’re tired of writing posts manually, or just want to experiment with AI automation, feel free to fork the idea and make it yours.</p><p><strong>The best content creators of tomorrow won’t write more. They’ll automate smarter.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d560b651383e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Smart Web Scraper in Python Using Selenium & BeautifulSoup]]></title>
            <link>https://medium.com/@arjuntewari0505/build-a-smart-web-scraper-in-python-using-selenium-beautifulsoup-c9d4ef656b2e?source=rss-c02f1de4b1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9d4ef656b2e</guid>
            <category><![CDATA[web-scraping-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[news]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Arjun tewari]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 12:53:17 GMT</pubDate>
            <atom:updated>2025-03-25T12:53:17.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*l-PW-eLo88FeYnZ_cH0ZEg.png" /></figure><p>In the world of modern development, <strong>data is gold</strong> — but it’s not always available in ready-made APIs.</p><p>Today, we’re diving into a <strong>robust Python-based web scraper</strong> built with undetected_chromedriver, Selenium, and BeautifulSoup—a tool every developer can plug into their workflow to mine real-time information from the internet. We’ll debug it, explain how it works, and show you how to use it effectively.</p><h3><strong>Why Use a Web Scraper?</strong></h3><p>Many websites don’t offer APIs. Even if they do, APIs can be limited, slow, or costly. Web scraping allows you to:<br>1. <strong>Automate data collection</strong> from news, blogs, and marketplaces.<br>2. <strong>Power machine learning models</strong> with fresh, real-world data.<br>3. <strong>Monitor public sentiment</strong> and political developments in real time.<br>4. <strong>Stay ahead of competitors</strong> by keeping an eye on what’s trending.</p><h3><strong>What This Scraper Does</strong></h3><p>This script scrapes <strong>political news articles from Indian Express</strong>. It launches a browser invisibly, waits for the page to fully load (even the JavaScript content), extracts the article titles and content, and returns them in a neat list.</p><h3><strong>Key Libraries Used</strong></h3><ul><li><strong>undetected_chromedriver</strong>: Launches a Chrome browser that avoids bot detection (unlike traditional Selenium setups).</li><li><strong>Selenium</strong>: Automates browser actions and waits for JavaScript-rendered elements.</li><li><strong>BeautifulSoup</strong>: Parses and cleans the final HTML to extract meaningful content.</li></ul><p><strong>Importing Libraries</strong></p><pre>import undetected_chromedriver as uc<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from bs4 import BeautifulSoup</pre><p><strong>Main Scraper Function</strong></p><pre>def scrapper():<br>    options = uc.ChromeOptions()<br>    options.add_argument(&quot;--headless=new&quot;)<br>    options.add_argument(&quot;--disable-gpu&quot;)<br>    options.add_argument(&quot;--no-sandbox&quot;)<br>    options.add_argument(&quot;--disable-dev-shm-usage&quot;)<br>    options.add_argument(&quot;--disable-blink-features=AutomationControlled&quot;)</pre><p>These options:</p><ul><li>Run Chrome <strong>invisible to the user</strong>.</li><li>Avoid detection by websites using <strong>anti-bot measures</strong>.</li></ul><p><strong>Load the Website and Wait for JS to Render</strong></p><pre>    driver = uc.Chrome(options=options)<br>    url = &quot;https://indianexpress.com/section/political-pulse/?ref=l1_home&quot;<br>    driver.get(url)<br><br>    WebDriverWait(driver, 10).until(<br>        EC.presence_of_element_located((By.TAG_NAME, &quot;body&quot;))<br>    )</pre><p>Many websites load content dynamically using JavaScript. If you don’t wait, you’ll scrape <strong>empty pages</strong>. This line ensures that content is fully rendered.</p><p><strong>Extract HTML and Parse with BeautifulSoup</strong></p><pre>    html = driver.page_source<br>    soup = BeautifulSoup(html, &quot;html.parser&quot;)<br>    articles = soup.find_all(&quot;div&quot;, class_=&quot;img-context&quot;)</pre><p>This is where we convert the loaded page into something readable by Python. We target specific HTML elements (div.img-context) that hold the news articles.</p><p><strong>Extract Titles and Content</strong></p><pre>    articles_list = []<br>    for article in articles:<br>        title_tag = article.find(&quot;h2&quot;, class_=&quot;title&quot;)<br>        title = title_tag.get_text(strip=True) if title_tag else &quot;Title not found&quot;<br><br>        paragraph_tags = article.find_all(&quot;p&quot;)<br>        paragraphs = &quot; &quot;.join([p.get_text(strip=True) for p in paragraph_tags]) if paragraph_tags else &quot;Content not found&quot;<br><br>        articles_list.append({&quot;title&quot;: title, &quot;content&quot;: paragraphs})</pre><p>This loop:</p><ul><li>Gets the <strong>title</strong> of each article.</li><li>Joins all <strong>paragraphs</strong> into a single content block.</li><li>Adds it to a structured list.</li></ul><p><strong>Clean Exit</strong></p><pre>    import time<br>    time.sleep(5)<br>    driver.quit()<br>    return articles_list</pre><p>After scraping, we:</p><ul><li>Wait briefly (sometimes prevents crash).</li><li><strong>Quit the browser</strong> to free memory.</li><li>Return all collected data for further use.</li></ul><p><strong>Output :</strong></p><pre>[<br>  {<br>    &quot;title&quot;: &quot;Opposition gears up for Lok Sabha showdown&quot;,<br>    &quot;content&quot;: &quot;The Opposition parties are rallying to present a united front...&quot;<br>  },<br>  {<br>    &quot;title&quot;: &quot;Cabinet reshuffle expected next week&quot;,<br>    &quot;content&quot;: &quot;According to sources, key ministries are likely to see changes...&quot;<br>  }<br>]</pre><h3>Use Cases for Developers</h3><ul><li><strong>News Aggregators</strong>: Feed the latest stories into your app.</li><li><strong>Trend Trackers</strong>: Analyze keyword frequencies or sentiment over time.</li><li><strong>Research Tools</strong>: Summarize and categorize political narratives.</li><li><strong>Competitor Monitoring</strong>: Track mentions of rival companies, products, or politicians.</li></ul><h3><strong>Final Thoughts</strong></h3><p>This script is your <strong>starter kit for web scraping dynamic content</strong>. It avoids detection, handles modern JS-heavy pages, and delivers clean, structured data. With a few tweaks, you can use it on any news portal, e-commerce site, or blog. If you find it useful do drop a clap and support!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9d4ef656b2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Insurance Charge Predictor Using XGBoost and Taipy]]></title>
            <link>https://medium.com/@arjuntewari0505/building-an-ai-powered-insurance-charge-predictor-using-xgboost-and-taipy-2dfb7d13303a?source=rss-c02f1de4b1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dfb7d13303a</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[regression-data-analysis]]></category>
            <dc:creator><![CDATA[Arjun tewari]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 08:10:52 GMT</pubDate>
            <atom:updated>2025-03-15T08:10:52.356Z</atom:updated>
            <content:encoded><![CDATA[<p>Link to <a href="https://github.com/ArjunTewari/Predicting_Insurance">github</a></p><h3>Introduction</h3><p>Medical insurance costs vary based on multiple factors such as <strong>age, BMI, smoking habits, gender, and region</strong>. Predicting these charges accurately is a complex challenge, but <strong>Machine Learning (ML)</strong> provides an optimal solution.</p><p>This project <strong>leverages advanced ML techniques</strong> to predict insurance charges based on user inputs. Our model integrates:</p><ul><li><strong>Ensemble Learning</strong> (XGBoost + Huber Regressor + HistGradientBoosting)</li><li><strong>Polynomial Features for capturing non-linear interactions</strong></li><li><strong>MinMax Scaling for feature normalization</strong></li><li><strong>Taipy GUI for an interactive web interface</strong></li></ul><p>With a strong <strong>R² score of 0.86</strong>, this model provides highly accurate predictions, making it valuable for <strong>insurance companies, financial planners, and individuals</strong>.</p><h3>Real-World Problem &amp; Solution</h3><p>Medical insurance pricing is affected by:</p><p>✅ <strong>Health risks (BMI, smoking, age)</strong><br> ✅ <strong>Demographic factors (Region, Gender, Children)</strong><br> ✅ <strong>Behavioral &amp; lifestyle choices (Smoking, BMI)</strong></p><p><strong>Challenges in Insurance Cost Estimation:</strong> 🔸 Insurance companies need precise predictions for fair pricing.<br> 🔸 Individuals want to estimate potential healthcare costs.<br> 🔸 Underestimating risks can lead to <strong>financial instability</strong> for insurers.<br> 🔸 Overestimating premiums can make insurance <strong>unaffordable</strong>.</p><p><strong>Our AI-powered solution</strong> bridges this gap by analyzing <strong>historical data</strong> and providing precise charge estimates.</p><h3>1. Data Preprocessing &amp; Feature Engineering</h3><p>We begin by <strong>loading and cleaning</strong> the dataset, ensuring it is properly formatted.</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import MinMaxScaler, PolynomialFeatures<br><br># Load Data<br>data = pd.read_csv(&quot;insurance.csv&quot;, index_col=&quot;index&quot;)<br>df = pd.DataFrame(data)<br><br># Handle missing values using Interpolation<br>df = df.interpolate()<br><br># Feature Engineering - Creating interaction features<br>df[&quot;age_smoker_interaction&quot;] = df[&quot;age&quot;] * (df[&quot;smoker&quot;] == &quot;yes&quot;).astype(int)<br>df[&quot;age_bmi_interaction&quot;] = df[&quot;age&quot;] * df[&quot;bmi&quot;]<br><br># Encoding categorical variables (One-Hot Encoding)<br>df_encoded = pd.get_dummies(data=df, columns=[&#39;sex&#39;, &#39;region&#39;, &#39;smoker&#39;], drop_first=True)<br><br># Log transformation to normalize highly skewed &#39;charges&#39; column<br>df[&quot;log_charges&quot;] = np.log(df[&quot;charges&quot;])</pre><h3>Why These Transformations?</h3><ol><li><strong>Handling Missing Data</strong>: Uses interpolation to fill gaps in data.</li><li><strong>Feature Engineering</strong>: Adds interaction features (Age × Smoker, Age × BMI) for <strong>higher predictive power</strong>.</li><li><strong>Categorical Encoding</strong>: Converts text labels into numerical format for ML models.</li><li><strong>Log Transformation</strong>: Reduces the impact of <strong>high-cost outliers</strong>.</li></ol><h3>2. Splitting Data &amp; Scaling Features</h3><p>After preparing the dataset, we <strong>split it into training and testing sets</strong>. And use MinMaxScaler to scale the dataset for better predictions.</p><pre># Splitting into train and test sets (80-20 split)<br>train, test = train_test_split(df_encoded, test_size=0.2, random_state=42)<br><br># Separating features and target variable<br>x_train = train.drop(columns=[&quot;charges&quot;])<br>y_train = train[&quot;charges&quot;]<br>x_test = test.drop(columns=[&quot;charges&quot;])<br>y_test = test[&quot;charges&quot;]<br><br># Normalizing the feature set using MinMaxScaler<br>scaler_x = MinMaxScaler()<br>x_train_scaled = scaler_x.fit_transform(x_train)<br>x_test_scaled = scaler_x.transform(x_test)<br><br># Scaling the target variable separately<br>scaler_y = MinMaxScaler()<br>y_train_scaled = scaler_y.fit_transform(y_train.values.reshape(-1, 1))</pre><h3>Why Scaling?</h3><p>✔ <strong>MinMax Scaling</strong> ensures that all features are within a <strong>0–1 range</strong>, which helps algorithms like XGBoost converge faster.<br> ✔ <strong>Prevents dominance</strong> of large-scale variables over smaller ones (e.g., age vs. BMI).</p><h3>3. Feature Expansion Using Polynomial Features</h3><p>Since relationships in <strong>insurance pricing are non-linear</strong>, we <strong>expand features</strong> using <strong>PolynomialFeatures</strong>.</p><pre>from sklearn.preprocessing import PolynomialFeatures<br><br># Expanding features with polynomial interactions (degree = 2)<br>poly = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)<br>x_train_poly = poly.fit_transform(x_train_scaled)<br>x_test_poly = poly.transform(x_test_scaled)</pre><h3>Why Polynomial Features?</h3><ol><li>Captures complex interactions between features (e.g., <strong>BMI × Age</strong>)</li><li>Boosts model accuracy for <strong>non-linear relationships</strong></li><li>Essential for <strong>improving regression models</strong> on structured datasets.</li></ol><h3>4. Training the Model Using Ensemble Learning</h3><p>We use <strong>Voting Regressor</strong> with <strong>XGBoost, Huber Regressor, and HistGradientBoosting</strong>. I tried following models in the order of increasing accuracy :<br>1. Used decision trees <br>2. Used Random Forest regressor<br>3. Used Hist Gradient Boosting Regressor<br>4. Huber Regessor<br>5. XGBoost Regressor (Giving the maximum efficiency and accuracy)<br>After this I used voting regressor to ensemble all the best ones but did not achieve any significant achievement.</p><p>But I fine tuned the parameters of XGBoost model by brute trial and error method which brought significant impact in the errors.</p><pre>from xgboost import XGBRegressor<br>from sklearn.ensemble import VotingRegressor, HistGradientBoostingRegressor<br>from sklearn.linear_model import HuberRegressor<br><br># Define Models<br>model_1 = HistGradientBoostingRegressor()<br>model_2 = HuberRegressor()<br><br># XGBoost Model with Tweedie Loss Function<br>xgb_model = XGBRegressor(n_estimators=850, learning_rate=0.008, max_depth=16, <br>                         colsample_bytree=0.9, objective=&#39;reg:tweedie&#39;)<br><br># Ensemble Learning - Voting Regressor<br>ensemble_model = VotingRegressor(estimators=[<br>    (&#39;xgb&#39;, xgb_model)<br>])<br><br># Train the ensemble model<br>ensemble_model.fit(x_train_poly, y_train_scaled.ravel())</pre><h3>5. Model Evaluation</h3><p>After training, we evaluate <strong>Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and R² score</strong>.</p><pre>from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score<br><br>def evaluate_model_performance(y_true, y_pred):<br>    mae = mean_absolute_error(y_true, y_pred)<br>    mse = mean_squared_error(y_true, y_pred)<br>    rmse = np.sqrt(mse)<br>    r2 = r2_score(y_true, y_pred)<br>    return rmse, r2, mae<br><br># Predictions<br>ensemble_predictions = ensemble_model.predict(x_test_poly)<br>ensemble_predictions = scaler_y.inverse_transform(ensemble_predictions.reshape(-1, 1))<br><br># Evaluate performance<br>rmse, r2, mae = evaluate_model_performance(ensemble_predictions, y_test.to_numpy().reshape(-1, 1))<br><br>print(f&quot;MAE: {mae}&quot;)<br>print(f&quot;MSE: {mse}&quot;)<br>print(f&quot;RMSE: {rmse}&quot;)<br>print(f&quot;R²: {r2:.2f}&quot;)</pre><h3>Results</h3><p>💡 <strong>MAE</strong> = <strong>2108.83</strong> (Avg. absolute difference from actual charges)<br> 💡 <strong>RMSE</strong> = <strong>4393.04</strong> (Accounts for larger deviations)<br> 💡 <strong>R²</strong> = <strong>0.86</strong> (Explains <strong>86% variance</strong>, a strong result!)</p><h3>6. Deploying an Interactive GUI Using Taipy</h3><p>Finally, we <strong>deploy a user-friendly GUI</strong> using <strong>Taipy</strong>. This includes using preparing the data and using the saved model to predict the insurance.</p><pre>#User Variables:<br>user_age = 0<br>user_bmi = 0<br>user_sex = &quot;&quot;<br>user_region = &quot;&quot;<br>user_smoker = &quot;&quot;<br>user_children = 0<br><br><br>def preprocess_input(age, bmi, sex, region, smoker,children):<br>    # Convert categorical variables into one-hot encoding<br>    user_data = {<br>        &quot;age&quot;: age,<br>        &quot;bmi&quot;: bmi,<br>        &quot;children&quot;: children,<br>        &quot;age_smoker_interaction&quot;: age * (smoker == &quot;yes&quot;),<br>        &quot;age_bmi_interaction&quot;: age * bmi,<br>        &quot;sex_male&quot;: 1 if sex == &quot;male&quot; else 0,<br>        &quot;region_northwest&quot;: 1 if region == &quot;northwest&quot; else 0,<br>        &quot;region_southeast&quot;: 1 if region == &quot;southeast&quot; else 0,<br>        &quot;region_southwest&quot;: 1 if region == &quot;southwest&quot; else 0,<br>        &quot;smoker_yes&quot;: 1 if smoker == &quot;yes&quot; else 0,<br>    }<br><br>    # Convert to DataFrame<br>    user_df = pd.DataFrame([user_data])<br><br>    # Scale the inputs<br>    user_scaled = scaler_y.transform(user_df)<br>    return user_scaled<br><br>predicted_charge = 0<br><br>def reset(state):<br>    state.user_age = 0<br>    state.user_bmi = 0<br>    state.user_sex = &quot;&quot;<br>    state.user_region = &quot;&quot;<br>    state.user_smoker = &quot;&quot;<br>    state.user_children = 0<br>    state.predicted_charge = 0<br>def predict_insurance(state):<br>    user_scaled = preprocess_input(state.user_age, state.user_bmi, state.user_sex, state.user_region, state.user_smoker, state.user_children)<br>    state.predicted_charge = (model_2.predict(user_scaled)[0]).round(2)<br>image = &quot;logo.jpg&quot;<br><br>page = &quot;&quot;&quot;<br>&lt;|text-center|<br>&lt;|{image}|image|width=800px|height=200px|&gt;<br>&lt;h1&gt;INSURANCE CHARGE PREDICTOR&lt;/h1&gt;<br><br>&lt;h6&gt;This predictor uses XGBoost regressor to predict the insurance charge using various factors like user&#39;s age and BMI etc.&lt;/h6&gt;<br>&lt;|layout|columns = 1 1 1 1|<br># MAE : &lt;|metric|value={mae:.2f}|&gt;<br># RMSE : &lt;|metric|value={rmse:.2f}|&gt;<br># R² : &lt;|metric|value={r2:.2f}|&gt;<br>|&gt;<br>## &lt;|Enter your details|&gt;<br><br>## &lt;|Enter your age : |&gt;&lt;|{user_age}|number|&gt;<br><br>## &lt;|Enter your BMI : |&gt; &lt;|{user_bmi}|number|&gt;<br><br>## &lt;|Enter your Gender : |&gt; &lt;|{user_sex}|selector|lov=male;female|&gt;<br><br>## &lt;|Enter your Region : |&gt;&lt;|{user_region}|selector|lov=northeast; northwest; southeast; southwest|&gt;<br><br>## &lt;|Do you smoke? :|&gt; &lt;|{user_smoker}|selector|lov=yes;no|&gt;<br><br>Number of children : &lt;|{user_children}|number|width = 600px|&gt;<br><br>&lt;|Submit|button|on_action=predict_insurance|width = 500px|&gt;<br>&lt;|Reset|button|on_action=reset|width = 500px|&gt;<br><br>## Predicted Insurance Charge:<br>&lt;|${predicted_charge}|text|width=100px|height=200px|&gt;<br>&gt;<br>&quot;&quot;&quot;<br><br>if __name__== &quot;__main__&quot;:<br>    app = Gui(page)<br>    port = int(os.environ.get(&quot;PORT&quot;, 5000))<br>    app.run(host=&quot;0.0.0.0&quot;, port=port)</pre><h3><strong>Quantifiable Achievements and Model Improvement</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*HIah-yyCud4yUD8ChwgQhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*Xjw-f0M1uDPz1tlb_Gy7DA.png" /><figcaption><strong>Metrics of Hist and Hubber (Left) and Fine tuned XGBoost (Right)</strong></figcaption></figure><p>The clear trend across all three models is that <strong>as we moved towards more advanced techniques</strong>, our predictions became <strong>more accurate, errors reduced significantly, and generalization improved</strong>.</p><ol><li><strong>XGBoost reduced MAE by 37% compared to Huber and 23% compared to HistGradientBoosting.</strong></li><li><strong>RMSE dropped by 33% compared to Huber and 5% compared to HistGradientBoosting.</strong></li><li><strong>The R² score increased from 0.76 (Huber) to 0.87 (XGBoost), meaning our model explains 11% more variance than Huber.</strong></li></ol><p>For a <strong>real-world insurance prediction application</strong>, these improvements mean <strong>better pricing strategies for insurers, more accurate cost estimates for customers, and greater financial stability in the industry</strong>. XGBoost <strong>not only improves performance but also ensures a scalable and efficient solution</strong> — making it the ideal choice for production-level deployments.</p><h3><strong>Why did XGBoost Outperformed?</strong></h3><p>XGBoost <strong>uses Tweedie regression</strong>, specifically designed to handle skewed insurance cost data, leading to <strong>better generalization</strong>.<br>It applies <strong>L1 &amp; L2 regularization</strong>, preventing overfitting while <strong>learning complex patterns</strong> in the dataset.<br>It is optimized for parallel computing, provides the <strong>best performance-to-time ratio</strong>, making it ideal for <strong>real-world deployment</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dfb7d13303a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Price Prediction using LSTM and Bidirectional LSTM]]></title>
            <link>https://medium.com/@arjuntewari0505/stock-price-prediction-using-lstm-and-bidirectional-lstm-b2f72283b433?source=rss-c02f1de4b1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f72283b433</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Arjun tewari]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 09:18:52 GMT</pubDate>
            <atom:updated>2025-03-14T09:18:52.155Z</atom:updated>
            <content:encoded><![CDATA[<p>Link to <a href="https://github.com/ArjunTewari/Stock_closing_price">Github</a></p><h3>Introduction</h3><p>Stock price prediction is a challenging task due to the highly volatile and nonlinear nature of stock market movements. In this project, we build a deep learning model using <strong>Long Short-Term Memory (LSTM)</strong> and then enhance the performance using <strong>Bidirectional LSTM</strong>. The project showcases how sequential models improve predictive accuracy and provides insights into deep learning for financial applications</p><h3>Problem Statement</h3><p>Predicting stock prices based on historical data is crucial for traders and investors. The challenge lies in capturing temporal dependencies and trends efficiently. Traditional machine learning models often fail to grasp long-term dependencies in sequential data. LSTM, a variant of Recurrent Neural Networks (RNNs), is well-suited for handling such dependencies. This project demonstrates how an <strong>LSTM model</strong> can be improved using <strong>Bidirectional LSTM</strong>, leading to better predictions.</p><h3>Objectives</h3><ol><li>Preprocess historical stock price data.</li><li>Train an LSTM model to predict stock prices.</li><li>Enhance performance using Bidirectional LSTM.</li><li>Compare performance metrics (RMSE, R², MAE) for both models.</li><li>Implement data augmentation for improved generalization.</li><li>Visualize actual vs. predicted prices.</li></ol><h3>Libraries Used</h3><ul><li>pandas: For data manipulation.</li><li>numpy: For numerical operations.</li><li>scikit-learn: For data preprocessing and evaluation metrics.</li><li>Keras &amp; TensorFlow: For deep learning models.</li><li>Taipy: For data visualization and UI.</li><li>optuna: For hyperparameter tuning.</li></ul><h3>Data Preprocessing</h3><p>We begin by loading historical stock data (AAPL.csv) and splitting it into training, validation, and test sets. I have checked the dataset, it has not categorical dataset, no missing values and no outliers.</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import MinMaxScaler<br><br>data_set = pd.DataFrame(pd.read_csv(&quot;AAPL.csv&quot;, parse_dates=True)).set_index(&quot;Date&quot;)<br><br>def train_test_val(data):<br>    train_size, val_size = int(len(data) * 0.7), int(len(data) * 0.15)<br>    train, test, val = data.iloc[:train_size], data.iloc[train_size:train_size + val_size], data.iloc[train_size + val_size:]<br>    x_train, y_train = train.drop(columns=[&quot;Close&quot;]), train[&quot;Close&quot;]<br>    x_test, y_test = test.drop(columns=[&quot;Close&quot;]), test[&quot;Close&quot;]<br>    x_val, y_val = val.drop(columns=[&quot;Close&quot;]), val[&quot;Close&quot;]<br>    return x_train, x_test, x_val, y_train, y_test, y_val<br><br>x_train, x_test, x_val, y_train, y_test, y_val = train_test_val(data_set)</pre><h3>Feature Scaling</h3><p>Scaling improves model convergence and performance. <strong>Do make note to always check the shape of the output after every preprocessing step</strong>, as these techniques alter the shape of the dataset.</p><pre>scaler_x = MinMaxScaler()<br>x_train_scaled, x_test_scaled, x_val_scaled = scaler_x.fit_transform(x_train), scaler_x.transform(x_test), scaler_x.transform(x_val)<br>scaler_y = MinMaxScaler()<br>y_train_scaled, y_test_scaled, y_val_scaled = scaler_y.fit_transform(y_train.values.reshape(-1, 1)), scaler_y.transform(y_test.values.reshape(-1, 1)), scaler_y.transform(y_val.values.reshape(-1, 1))</pre><h3>Data Augmentation with Noise Injection</h3><p>Adding noise improves model generalization. As LSTM models work on large dataset, so we will increase the dataset size by adding synthetic data.</p><pre>def add_noise(data, noise_factor=0.01):<br>    noise = np.random.normal(loc=0, scale=noise_factor, size=data.shape)<br>    return data + noise<br><br>x_train_augmented = add_noise(x_train_scaled)<br>y_train_augmented = y_train<br>x_train_combined, y_train_combined = np.vstack([x_train_scaled, x_train_augmented]), np.vstack([y_train, y_train_augmented])</pre><h3>Model Implementation</h3><h3>Time Series Data Preparation</h3><p>Before feeding the dataset to the LSTM model, It has to be given as a sequential data, for that we will use — TimeseriesGenerator :</p><pre>from keras.preprocessing.sequence import TimeseriesGenerator<br><br>n_input, n_features = 50, x_train_combined.shape[1]<br>train_generator = TimeseriesGenerator(x_train_combined, y_train_combined, length=n_input, batch_size=10)<br>test_generator = TimeseriesGenerator(x_test_scaled, y_test_scaled, length=n_input, batch_size=10)<br>val_generator = TimeseriesGenerator(x_val_scaled, y_val_scaled, length=n_input, batch_size=10)</pre><h3>LSTM Model</h3><p>The model given below is the final model, I tried various ways like : <br>1. Increasing the layers -&gt; Increasing the time of training -&gt; Computationally expensive but the performance dropped.</p><p>2. Using recurrent droput layer which did not help as well</p><p>3. At the end, I used bidrectional LSTM which yeilded the best result :</p><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import LSTM, Dense<br><br>model = Sequential()<br>model.add(LSTM(50, activation=&quot;tanh&quot;, return_sequences=False, input_shape=(n_input, n_features)))<br>model.add(Dense(1))<br>model.compile(optimizer=&#39;adam&#39;, loss=&quot;mean_squared_error&quot;)<br>model.fit(train_generator, epochs=10, batch_size=10)</pre><h3><strong>LSTM model —</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jqE1n-Mbjv3IBui57dviA.png" /><figcaption>True values(blue) vs Predicted values (Orange) for LSTM model</figcaption></figure><figure><img alt="R2 error is 0.6 which can be improved and brought close to 1." src="https://cdn-images-1.medium.com/max/1024/1*vCIo0cYe9OiMIPz0CIL_Eg.png" /><figcaption>R2 error is 0.6 which can be improved and brought close to 1.</figcaption></figure><h3><strong>Bi-directional LSTM -</strong></h3><p>Bidirectional LSTM improves performance by processing input sequences from both forward and backward directions.</p><pre>from tensorflow.keras.layers import Bidirectional<br><br>model_bi = Sequential()<br>model_bi.add(Bidirectional(LSTM(50, activation=&quot;tanh&quot;, return_sequences=False, input_shape=(n_input, n_features))))<br>model_bi.add(Dense(1))<br>model_bi.compile(optimizer=&#39;adam&#39;, loss=&quot;mean_squared_error&quot;)<br>model_bi.fit(train_generator, epochs=10, batch_size=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFfwT2eUK8mds5ikbFoSwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFkng6dF-iFL0ALViANoiA.png" /></figure><p>As we can see it has a better performance than a normal LSTM model, Bidirectional LSTM improves performance by processing input sequences from both forward and backward directions. <strong>Two-way (Past to Future &amp; Future to Past)</strong>, Improved accuracy &amp; generalization</p><h3>Model Evaluation</h3><p>Evaluation of regression models is done by MAE (Mean absolute error), RSME (Root Mean Square error) and R2.</p><pre>from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score<br><br>def evaluate_model(y_true, y_pred):<br>    mae = mean_absolute_error(y_true, y_pred)<br>    mse = mean_squared_error(y_true, y_pred)<br>    rmse = np.sqrt(mse)<br>    r2 = r2_score(y_true, y_pred)<br>    return rmse, r2, mae<br><br>predictions = model_bi.predict(test_generator)<br>predicted_prices = scaler_y.inverse_transform(predictions)<br>rmse, r2, mae = evaluate_model(y_test[50:], predicted_prices)</pre><h3>Taipy UI Implementation</h3><p>To make the project interactive and user-friendly, we use <strong>Taipy</strong> for visualization. This enables a dynamic web UI to display <strong>actual vs. predicted</strong> stock prices along with performance metrics.</p><pre>from taipy import Gui<br><br>page = &quot;&quot;&quot;<br>&lt;|text-center|<br>&lt;h1&gt;Stock Closing Price Prediction&lt;/h1&gt;<br>&gt;<br>&lt;h5&gt;Using LSTM and Bidirectional LSTM for stock price prediction.&lt;/h5&gt;<br><br>&lt;|{combined_chart_data}|chart|type=line|x=Index|y[1]=Actual|y[2]=Predicted|title=Actual vs Predicted Closing Prices|&gt;<br><br>&lt;|layout|columns=1 1 1|<br># MAE: &lt;|metric|value={mae:.2f}|&gt;<br># RMSE: &lt;|metric|value={rmse:.2f}|&gt;<br># R²: &lt;|metric|value={r2:.2f}|&gt;<br>|&gt;<br>&quot;&quot;&quot;<br><br>app = Gui(page)<br>if __name__ == &quot;__main__&quot;:<br>    app.run(title=&quot;Stock Prediction Dashboard&quot;, host=&quot;0.0.0.0&quot;, port=5005)</pre><p>This UI implementation allows users to interactively view the model’s performance, explore predictions, and understand stock trends visually.</p><h3>Result :</h3><h4>Drastic Reduction in Prediction Errors</h4><p>The <strong>Mean Absolute Error (MAE)</strong> dropped from <strong>10.9</strong> in the standard LSTM model to <strong>4.3</strong> in the Bi-LSTM model. This represents a <strong>60.5% reduction in error</strong>, meaning the model’s predicted stock closing prices are now much closer to actual values.</p><p>Similarly, the <strong>Root Mean Squared Error (RMSE)</strong> saw a substantial decrease from <strong>15.5</strong> to <strong>5.9</strong>, marking a <strong>61.9% improvement</strong>. Since RMSE penalizes larger deviations more than MAE, this indicates that the Bidirectional LSTM is not only more precise but also <strong>more robust to extreme variations</strong> in stock prices.</p><h4>Higher Predictive Power with Bi-LSTM</h4><p>The <strong>R² score</strong>, which measures how well the model explains variance in stock prices, increased <strong>from 0.6 to 0.9</strong>. This suggests that the Bi-LSTM captures a much stronger relationship between input features and stock price movements, making it a more reliable predictor. A score close to 1 indicates near-perfect predictions, proving that <strong>capturing information in both forward and backward directions</strong> allows the model to make significantly better-informed predictions.</p><h3>Efficiency Gains: Optimizing Computational Resources</h3><p>While deep learning models often trade accuracy for increased computational costs, the code used in this project ensures a <strong>balanced approach</strong>, saving both time and resources.</p><ol><li><strong>Efficient Data Augmentation:</strong> Instead of gathering more data, <strong>noise injection</strong> was used to expand the dataset, improving generalization without additional data collection costs. This ensures that the model can learn more patterns while maintaining training efficiency.</li><li><strong>Smart Feature Scaling:</strong> The use of MinMaxScaler ensured that the model converged faster, reducing training time and preventing exploding gradients that could otherwise lead to instability.</li><li><strong>Optimized Batch Processing:</strong> The TimeseriesGenerator efficiently created input sequences, eliminating the need for manual reshaping of data. This approach <strong>reduces memory overhead and speeds up model training</strong> by utilizing efficient internal batch management.</li><li><strong>Early Stopping for Computational Savings:</strong> Implementing <strong>EarlyStopping</strong> ensured that the model <strong>did not overtrain</strong>, saving unnecessary epochs and preventing resource wastage. By stopping training when no further improvement was observed, the code <strong>avoided redundant computations, reducing training time without sacrificing accuracy</strong>.</li><li><strong>Pre-trained Model Loading:</strong> Instead of training from scratch every time, the model was saved and reloaded, allowing <strong>reuse of trained parameters</strong>. This significantly reduces the need for repetitive training, making the solution <strong>scalable and deployable in real-world applications</strong></li></ol><h3><strong>Conclusion</strong></h3><p>The results showcase how <strong>Bidirectional LSTM offers substantial improvements over standard LSTM models</strong>, reducing errors by over <strong>60%</strong> while capturing richer contextual dependencies. Moreover, the code is structured to maximize computational efficiency, preventing unnecessary overhead in training and inference.</p><p>This project not only demonstrates <strong>state-of-the-art deep learning techniques</strong> for stock prediction but also highlights the importance of <strong>efficient coding practices</strong> that ensure models are both <strong>powerful and cost-effective</strong> in real-world deployments</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f72283b433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Multi-Agent Crew for News Analysis Using CrewAI and Deepseek]]></title>
            <link>https://medium.com/@arjuntewari0505/building-a-multi-agent-crew-for-news-analysis-using-crewai-and-deepseek-2f4f78d1a310?source=rss-c02f1de4b1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f4f78d1a310</guid>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[crew-ai]]></category>
            <dc:creator><![CDATA[Arjun tewari]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 13:37:21 GMT</pubDate>
            <atom:updated>2025-03-24T15:46:52.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Multi-Agent Crew for Stock market impact analysis</h3><p>Link to git Repo — <a href="https://github.com/ArjunTewari/News-Stock">https://github.com/ArjunTewari/News-Stock</a></p><h3>Introduction</h3><p>In this blog, we will build a <strong>multi-agent system</strong> using <strong>CrewAI</strong> to analyze news articles and extract <strong>insights for stock market trading</strong>. The system will:</p><ol><li><strong>Scrape news articles</strong> (News Aggregation)</li><li><strong>Analyze the impact on the Indian stock market</strong> (Impact Analysis)</li><li><strong>Provide trading strategies</strong> based on the impact (Market Insights)</li></ol><p>We will be using:</p><ul><li><strong>CrewAI</strong> (to create multi-agent workflows)</li><li><strong>OpenAI API</strong> (for processing text-based tasks)</li><li><strong>Deepseek-LLM (locally hosted)</strong> (as an alternative LLM)</li><li><strong>NewsAPI</strong> (for fetching news)</li><li><strong>LangChain</strong> (to integrate models)</li></ul><p>Let’s go through the code <strong>step by step</strong>, explaining each section.</p><h3>1. Setting Up the Environment</h3><p>The first step is to <strong>import the required libraries</strong>:</p><pre>from newsapi import NewsApiClient<br>from crewai import Task, Crew, Agent<br>from langchain_openai import ChatOpenAI<br>from dotenv import find_dotenv, load_dotenv<br>_ = load_dotenv(find_dotenv())</pre><h4>Explanation:</h4><ul><li>newsapi: Used to fetch news articles.</li><li>crewai: Helps define agents and tasks in a structured manner.</li><li>langchain_openai: Allows us to use OpenAI’s models in LangChain.</li><li>dotenv: Loads environment variables (like API keys) from a .env file.</li></ul><h3>2. Loading the Deepseek Model (Locally Hosted)</h3><p>Instead of relying entirely on OpenAI’s API, we attempt to load a <strong>locally hosted Deepseek-LLM</strong> for text generation.</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline<br>from langchain_community.llms import HuggingFacePipeline<br><br># Load the tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;./deepseek-llm-7b-chat&quot;)<br><br># Load model with quantization for efficiency<br>from transformers import BitsAndBytesConfig<br>quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=&quot;float16&quot;)<br><br>model = AutoModelForCausalLM.from_pretrained(<br>    &quot;./deepseek-llm-7b-chat&quot;,<br>    quantization_config=quantization_config,<br>    device_map=&quot;cpu&quot;<br>)<br><br># Create a text-generation pipeline<br>text_gen_pipeline = pipeline(<br>    &quot;text-generation&quot;,<br>    model=model,<br>    tokenizer=tokenizer,<br>    max_new_tokens=15<br>)<br><br># Convert it to a LangChain-compatible LLM<br>llm = HuggingFacePipeline(pipeline=text_gen_pipeline)</pre><h4>Explanation:</h4><ul><li>We load the deepseek-llm-7b-chat model from a local directory.</li><li><strong>Quantization</strong> is applied (load_in_4bit=True) to reduce memory usage. Since I am using it on my local server.</li><li>The <strong>pipeline</strong> is set up for <strong>text generation</strong>.</li><li>The model is then <strong>converted</strong> into a format that CrewAI can use.</li></ul><p><strong>Defining token limit to keep the cost minimum :</strong></p><pre>TOKEN_LIMIT = 150  # Adjust as needed</pre><h3>3. Setting Up OpenAI API</h3><p>To provide flexibility, we also set up OpenAI’s <strong>o3-mini</strong> model:</p><pre>import os<br>openai_api_key = os.environ[&quot;OPENAI_API_KEY&quot;]<br><br>llm = ChatOpenAI(model=&quot;o3-mini&quot;, max_tokens=TOKEN_LIMIT)</pre><h4>Explanation:</h4><ul><li>Retrieves the OpenAI API key from <strong>environment variables</strong>.</li><li>Loads <strong>ChatOpenAI</strong> with the <strong>o3-mini model</strong> (a lightweight OpenAI chat model).</li></ul><h3>5. Defining Agents</h3><p>Each <strong>Agent</strong> has a <strong>specific role</strong> in the system.</p><h4>Agent 1: News Scraper</h4><p>This agent <strong>collects</strong> the latest political news articles. The scapper is defined in another script, it will be shared afterwards. You can also use NewsAPI as given below:</p><pre>scrapper_Agent = Agent(<br>    role=&quot;Scrape the news using tool&quot;,<br>    goal=f&quot;Provide information in a structured format in minimum possible words within the {TOKEN_LIMIT}&quot;,<br>    backstory=f&quot;This agent scrapes the latest news articles and returns responses within the {TOKEN_LIMIT}.&quot;,<br>    tools=[ScrapperTool()],<br>    allow_delegation=False,<br>    verbose=True,<br>    async_execution=True,<br>)</pre><pre> newsapi = NewsApiClient(api_key=&#39;00b977b511e8492ba9c69f7bbc319fc2&#39;)<br> sources = newsapi.get_sources()<br> top_headlines = newsapi.get_everything(q=&#39;Bitcoin&#39;,<br>                                        from_param=&#39;2025-03-05&#39;,<br>                                        to=&#39;2025-01-01&#39;,<br>                                        language=&#39;en&#39;,<br>                                        sort_by=&#39;relevancy&#39;,<br>                                        page=1)</pre><h4>Agent 2: Impact Analysis</h4><p>This agent <strong>analyzes the impact of news</strong> on the Indian stock market.</p><pre>Impact_Agent = Agent(<br>    role=&quot;Analyze the impact of the news on the Indian stock market&quot;,<br>    goal=f&quot;Make a list of your analysis in a structured manner and create a report in minimal words and within the {TOKEN_LIMIT}.&quot;,<br>    backstory=&quot;Designed to analyze news impact and return structured data.&quot;,<br>    allow_delegation=False,<br>    verbose=False,<br>    llm=llm,<br>    async_execution=True,<br>)</pre><h4>Agent 3: Trading Insights</h4><p>This agent <strong>creates trading strategies</strong> based on news and impact reports.</p><pre>Insight_Agent = Agent(<br>    role=&quot;From the report provided by Impact_Agent and Scrapper_Agent, provide strategies to trade.&quot;,<br>    goal=f&quot;Create a strategy report in within the {TOKEN_LIMIT}.&quot;,<br>    backstory=&quot;Formulates strategies to maximize trading profit for traders.&quot;,<br>    allow_delegation=False,<br>    verbose=True,<br>    llm=llm,<br>    async_execution=True,<br>)</pre><h4>Explanation:</h4><ul><li>Each <strong>agent</strong> has a <strong>role</strong>, <strong>goal</strong>, and <strong>backstory</strong>.</li><li>allow_delegation=False: Prevents them from <strong>delegating</strong> work to others.</li><li>llm=llm: Specifies which model they will use. Here it is using a single model, we can specify other models for every agent.</li></ul><h3>6. Defining Tasks</h3><p>Each <strong>task</strong> is assigned to a <strong>specific agent</strong>.</p><pre>News_Aggregation_Task = Task(<br>    description=&quot;Scrape the news articles of politics.&quot;,<br>    expected_output=&quot;A structured list of news titles and descriptions in minimal text.&quot;,<br>    agent=scrapper_Agent<br>)<br><br>Impact_Analysis_Task = Task(<br>    description=&quot;Analyze how news can affect the Indian stock market in minimal tokens.&quot;,<br>    expected_output=&quot;A structured impact report of each news item.&quot;,<br>    agent=Impact_Agent<br>)<br><br>Insight_Task = Task(<br>    description=&quot;Create trading strategies based on news impact.&quot;,<br>    expected_output=&quot;A structured list of strategies for traders.&quot;,<br>    agent=Insight_Agent<br>)</pre><h4>Explanation:</h4><ul><li>Each <strong>task</strong> has:</li><li>A <strong>description</strong> (what needs to be done).</li><li>An <strong>expected output</strong> (what the agent should return).</li><li>An <strong>assigned agent</strong> (who will perform it).</li></ul><h3>7. Creating the Crew</h3><p>Now, we bring everything together into a <strong>Crew</strong>.</p><pre>my_crew = Crew(<br>    agents=[scrapper_Agent, Impact_Agent, Insight_Agent],<br>    tasks=[News_Aggregation_Task, Impact_Analysis_Task, Insight_Task],<br>    verbose=2,<br>    memory=False,<br>    timeout=120<br>)</pre><h4>Explanation:</h4><ul><li>Defines a <strong>Crew</strong> consisting of all <strong>agents</strong> and <strong>tasks</strong>.</li><li>verbose=2: Enables detailed logs.</li><li>memory=False: Disables memory storage.</li><li>timeout=120: Limits execution time to 120 seconds.</li></ul><h3>8. Running the Crew</h3><p>Finally, we execute everything using:</p><pre>result = my_crew.kickoff()<br>print(result)</pre><h4>Explanation:</h4><ul><li>.kickoff() starts the <strong>task execution</strong>.</li><li>The <strong>final output</strong> is printed.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f4f78d1a310" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>