Navigating the Nepali stock market, particularly for identifying undervalued stocks with genuine growth potential, often feels like searching for a needle in a haystack. Traditional fundamental analysis is time-consuming, and the sheer volume of information can overwhelm even seasoned investors. I've found that leveraging generative AI, specifically an approach inspired by Claude's capabilities, within a Python framework can dramatically streamline this process. This post is for data scientists and investors with a basic understanding of Python, data science, and machine learning who want to build a more reliable, AI-powered value investment framework, moving beyond manual data crunching to intelligent, automated insights. You'll learn how to integrate external data sources, simulate AI-driven analysis, and apply a structured approach to pinpoint promising investment opportunities in the NEPSE market.
Key Takeaways
- Integrating diverse data sources like historical stock prices and news feeds is crucial for a comprehensive AI-driven investment strategy.
- Simulating generative AI capabilities (like sentiment analysis or fundamental scoring) within a Python script allows for rapid prototyping and validation of AI-powered investment hypotheses.
- A robust value investment framework considers both quantitative metrics (e.g., P/E, dividend yield) and qualitative factors (e.g., market sentiment, company news).
- Effective risk assessment and portfolio optimization are vital, even in an AI-driven approach, to mitigate market volatility and maximize returns.
- The power of generative AI lies in its ability to synthesize complex information, but human oversight and judgment remain indispensable for real-world investment decisions.
The Problem: Uncovering Hidden Value in NEPSE
The Nepali stock market presents unique challenges: data availability can be fragmented, and while historical price data is accessible, synthesizing it with qualitative factors like market sentiment or company-specific news is often a manual, subjective exercise. Investors typically rely on published financial statements and historical trends, but without a systematic way to process vast amounts of unstructured text or dynamically assess market mood, they miss crucial signals. My goal was to build a system that could automatically ingest relevant data, apply a set of value investment principles augmented by AI-like analysis, and recommend stocks with a clearer rationale.
Data and Sources
For this framework, we're pulling two distinct types of data:
- Historical Stock Prices: We'll use the Yahoo Finance API to fetch daily historical data for selected Nepali companies listed on the Nepal Stock Exchange (NEPSE). While NEPSE has its own data portals, Yahoo Finance provides a convenient programmatic interface for historical data.
Yahoo Finance API for Historical Data
- Market Sentiment/News Proxy: To simulate the impact of broader market sentiment or industry-specific news that an AI might process, we'll use the Discord Engineering Blog RSS feed. While not directly finance-related, it serves as an excellent proxy for demonstrating how an AI could ingest and analyze unstructured text from a dynamic source to infer sentiment or key themes, which could then be applied to finance-specific news in a real-world scenario.
Data accessed on 2026-07-28.
Step 1 — Data Ingestion: Fueling the AI Engine
The first hurdle in any data-driven project is getting the data in. For our value investing framework, this means fetching historical stock prices and a stream of textual data for sentiment analysis. I encountered situations where API endpoints for NEPSE data were inconsistent, making Yahoo Finance a more robust choice for historical prices, despite potential delays for less liquid stocks.
To fetch historical stock data, I built a function that takes a ticker symbol and a date range. It handles common API errors and ensures we get clean data. For sentiment, we're parsing an RSS feed, which often requires robust error handling for malformed XML or network issues.
import yfinance as yf
import feedparser
import pandas as pd
import datetime
def fetch_stock_data(ticker, start_date, end_date):
"""Fetches historical stock data from Yahoo Finance."""
try:
data = yf.download(ticker, start=start_date, end=end_date)
if data.empty:
print(f"Warning: No data found for {ticker} from {start_date} to {end_date}.")
return pd.DataFrame()
return data
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return pd.DataFrame()
def fetch_rss_feed(url):
"""Fetches and parses an RSS feed."""
try:
feed = feedparser.parse(url)
if feed.bozo:
print(f"Warning: RSS feed parsing issues for {url}: {feed.bozo_exception}")
# Still return entries, as some might be valid
return [{'title': entry.title, 'link': entry.link, 'published': entry.published}
for entry in feed.entries]
except Exception as e:
print(f"Error fetching RSS feed from {url}: {e}")
return []
This code snippet shows how `yf.download` is used for stock data, and `feedparser.parse` for RSS. Both include `try-except` blocks to catch network or parsing errors, which are common when dealing with external APIs. I've found that robust ingestion is the bedrock; without reliable data, any subsequent AI analysis is moot.
Step 2 — Data Preprocessing: Preparing for AI Consumption
Raw data, especially from diverse sources, is rarely ready for direct analysis. Historical stock prices might have missing days, and text from RSS feeds needs cleaning before sentiment analysis. My preprocessing step focuses on standardizing the data. For stock data, this involves calculating basic metrics like daily returns and handling any `NaN` values. For text, it's about extracting relevant fields and ensuring it's in a format suitable for our simulated AI.
def preprocess_stock_data(df):
"""Calculates daily returns and cleans stock data."""
if df.empty:
return df
df['Daily_Return'] = df['Adj Close'].pct_change()
df.dropna(inplace=True)
return df
def preprocess_rss_entries(entries):
"""Preprocesses RSS entries for sentiment analysis."""
processed_texts = []
for entry in entries:
title = entry.get('title', '')
# In a real scenario, you might concatenate title and summary/description
if title:
processed_texts.append(title)
return processed_texts
Here, `preprocess_stock_data` computes daily returns, a fundamental metric for volatility and performance. `preprocess_rss_entries` simply extracts titles, which will be our input for the simulated sentiment analysis. This step is crucial because the quality of your AI's output is directly proportional to the quality of its input.
Step 3 — AI-Powered Value Investment Framework: Simulating Claude's Insights
This is where the "AI-driven" aspect comes into play. Since direct integration with Claude's API involves credentials and costs, I've simulated its core capabilities: sentiment analysis from text and a "fundamental score" for stocks. In a production environment, you would replace these simulation functions with actual API calls to Claude (or a similar LLM) with carefully crafted prompts.
Simulating AI Sentiment Analysis
For the Discord blog posts, our simulated AI will assess the sentiment of the titles. A real Claude integration would involve sending the text to the LLM with a prompt like "Analyze the sentiment of this text about technology and return a score from -1 (very negative) to 1 (very positive)." For this tutorial, I'm using a simple keyword-based approach to demonstrate the concept.
def simulate_claude_sentiment(text):
"""
Simulates Claude's sentiment analysis.
In a real scenario, this would be an API call to Claude.
"""
text_lower = text.lower()
if any(keyword in text_lower for keyword in ['error', 'bug', 'issue', 'challenge', 'fix', 'problem']):
return -0.5 # Slightly negative
if any(keyword in text_lower for keyword in ['guide', 'new', 'update', 'improve', 'optimize', 'revolutionize']):
return 0.7 # Positive
return 0.1 # Neutral to slightly positive by default for tech blogs
This `simulate_claude_sentiment` function provides a basic sentiment score. It's a placeholder, of course, but it illustrates how an AI's output (a numerical score, a category, etc.) would be integrated into our pipeline.
Simulating AI Fundamental Scoring for Value Stocks
For stock valuation, our simulated AI will take historical data and infer a "value score" or "growth potential." A real Claude prompt might be: "Given this company's historical stock prices, daily returns, and recent market sentiment, assess its value potential on a scale of