A Clojure-based Portfolio Analysis Tool based on LLM Integration
1. Abstract
This blog post presents the design and implementation of a Portfolio Analysis Program built almost entirely in Clojure for The University of Hong Kong’s Center for Investment Management.
The program enables users to construct custom portfolios from individual stocks or asset classes, evaluate performance using key financial metrics, and visualize results interactively.
What sets this tool apart is its integration of financial market narratives through a Large Language Model (LLM), which contextualizes portfolio performances using real-time financial news.
2. Data and Methodology
2.1. Yahoo Finance (libpython-clj and yfinance)
The program leverages the “yfinance” API on Python to retrieve critical financial data, enabling robust portfolio construction and performance evaluation. By utilizing libpython-clj, a Clojure library that facilitates seamless integration with Python, we created an efficient wrapper around the yfinance library that allows us to access open and close price data for individual stocks (see our other blog for code examples).
2.2. Portfolio Construction, Performance and Visualization
The program allows users to define their stock trades by inputting a csv file that contains the stocks’ ticker, volume and action(buy/sell). These actions would then be reflected within the program and be collated into a financial investment portfolio.
Using the program, we can track the portfolio’s various financial metrics (notebook-style visualization with Clay), which include:
● Portfolio Return: Total percentage change in portfolio value.
● Annualized Return: Compounded annual growth rate (CAGR).
● Volatility: Standard deviation of daily returns, measuring risk.
● Rolling Annualized Volatility: Annualized risk trends over a moving window.
Metrics are computed from open and close prices of portfolio assets, processed efficiently in Clojure. For visualization, the program integrates Plotly to render interactive charts, including line plots for the aforementioned metrics.
2.3. AI Financial Advisor
The Portfolio Analysis Program enhances user insights by calling Large Language Models (Deepseek V3.1) via API endpoints, providing market condition narratives that may explain the performance of the portfolio. In this case, we utilize Clojure’s clj-http library to build an HTTP client to retrieve LLM responses from these API’s.
The following is a short code preview to obtain LLM responses.
Here, we create a function to load our API keys through our secret .edn file.
defn load-config []
(with-open [r (io/reader "./src/finance/portfolio_analysis/key_config.edn")]
( (edn/read (java.io.PushbackReader. r))))
We then create a function to retrieve LLM responses based on a query (the client-message
variable).
defn ask-chatbot [client-message]
(let [deepseek-api-key (:deepseek-api-key (load-config)) ;; Load our API key
(:model "deepseek-chat" ;; Non-reasoning model
payload {:max-tokens 200 ;; ~150 words
:messages [{:role "system" :content "You are a helpful assistant."}
:role "user" :content client-message}]
{:stream false}]
; Send request to API Endpoint and deserialize response
let [response-body (json/read-str ((client/post "https://api.deepseek.com/chat/completions"
(:content-type :json
{:headers {"Authorization" (format "Bearer %s" deepseek-api-key)}
:body (json/write-str payload)}) :body) :key-fn keyword)]
; Deserialize the response and obtain LLM response
:message (((first (response-body :choices)) :message) :content)
{:token-usage (response-body :usage)})))
Now, we test the chatbot’s response through the following prompt.
def basic-chatbot-response (ask-chatbot "Can you tell me the current market conditions that may affect one's portfolio?")) (
:message basic-chatbot-response) (
"Of course. The current market environment is being shaped by a complex interplay of several major factors. Here are the key conditions that could affect an investment portfolio, broken down into categories for clarity.\n\n**Disclaimer:** This information is for educational purposes only and is based on market conditions as of late 2023 / early 2024. It is not financial advice. Always consult with a qualified financial advisor for guidance tailored to your specific situation.\n\n---\n\n### 1. Macroeconomic Conditions & Central Bank Policy\n\nThis is the dominant theme driving markets right now.\n\n* **Interest Rates & Inflation:** The primary story for the past two years has been the global fight against high inflation.\n * **High Interest Rates:** Central banks, notably the U.S. Federal Reserve (Fed), have raised interest rates aggressively to cool inflation. This increases borrowing costs for companies and consumers, which can slow economic growth and corporate profits.\n * **Impact:** Higher rates make bonds and savings accounts more attractive, drawing money away from riskier assets like stocks. They also pressure growth stocks (especially tech) because their future earnings are worth less when discounted at a higher rate.\n * **The \"Higher for Longer\" Narrative:** The current debate is whether the Fed is done hiking rates and how long they will keep rates elevated before cutting them. Markets are highly sensitive to any data that hints at the future path of rates.\n\n* **Economic Growth & Recession Risks:** There is a constant tug-of-war between signals.\n * **Resilience:** The U.S. economy has remained surprisingly resilient with a strong labor market, leading to talk of a \"soft landing\" (where inflation is tamed without a major recession).\n * **Risks:** However, leading indicators in other parts of the world (like Europe and China) show significant slowdowns. Persistent high rates could still tip the U.S. into a mild recession.\n\n### 2. Geopolitical Risks\n\nThese events create uncertainty and can cause sudden volatility.\n\n* **Ongoing Conflicts:** The wars in Ukraine and the Middle East disrupt energy markets, supply chains, and global trade, creating uncertainty.\n* **U.S.-China Tensions:** The strategic competition between the world's two largest economies continues, affecting trade, technology sectors (e.g., semiconductors), and investment flows.\n* **Global Fragmentation:** The trend toward \"friend-shoring\" (moving supply chains to allied countries) and deglobalization can increase costs and create inefficiencies.\n\n### 3. Sector-Specific Trends\n\n* **Technology & Artificial Intelligence (AI):** Enthusiasm around AI has been a massive driver for mega-cap tech stocks (the \"Magnificent 7\"). This has created a concentration risk, where the market's performance is heavily dependent on a few names.\n* **Commercial Real Estate:** High interest rates and the shift to remote work have created significant stress, particularly for office real estate. This could pose risks for regional banks that are heavily exposed to these loans.\n* **Energy:** Prices remain volatile due to geopolitical tensions and OPEC+ production decisions, affecting both energy company stocks and broader inflation.\n\n### 4. Market Technicals & Sentiment\n\n* **Market Concentration:** As mentioned, a small number of giant tech stocks account for a very large portion of major indices like the S&P 500. If their momentum reverses, it could drag the entire index down.\n* **High Volatility:** The VIX (Volatility Index), often called the \"fear gauge,\" can spike on any unexpected economic data or geopolitical news, leading to sharp market swings.\n* **Consumer Sentiment:** While the economy has been strong, consumer confidence surveys have been mixed. If consumers pull back on spending, it would negatively impact many companies' earnings.\n\n---\n\n### How This Might Affect Your Portfolio:\n\n* **Equities (Stocks):** Volatility is likely to continue. Growth stocks may remain under pressure if rates stay high, while value stocks and sectors like energy might perform better. International stocks face headwinds from a strong U.S. dollar and slower global growth.\n* **Fixed Income (Bonds):** After a terrible 2022, higher yields now offer attractive income for the first time in years. However, bond prices can still fall if interest rates rise further. If the economy slows and rates are cut, bonds could see significant price appreciation.\n* **Cash and Cash Equivalents:** With high-interest savings accounts and money market funds yielding over 5%, cash is no longer a \"drag\" on returns and provides flexibility and safety.\n* **Alternative Assets:** Real estate and commodities can provide diversification but come with their own sets of risks in the current environment.\n\n### What to Consider:\n\n1. **Diversification:** This is more important than ever. Ensure your portfolio is spread across different asset classes (stocks, bonds, cash), sectors, and geographic regions.\n2. **Review Your Risk Tolerance:** Are you comfortable with the current level of market volatility? Your asset allocation should match your long-term goals and ability to stomach short-term swings.\n3. **Focus on Quality:** In an uncertain economic environment, focus on companies with strong balance sheets, consistent earnings, and low debt.\n4. **Avoid Timing the Market:** It's incredibly difficult. Instead, focus on time *in* the market through consistent, long-term investing strategies like dollar-cost averaging.\n\nTo get the most current snapshot, I recommend checking recent headlines from financial news sources like **Bloomberg, Reuters, or The Financial Times** for the latest data on inflation, jobs reports, and central bank commentary."
Using another API service from NewsAPI.org, we provide financial news articles from which the LLM would retrieve context to base its response from. The retrieved news data is appended into the LLM prompt alongside portfolio metrics (e.g., returns, volatility) to generate concise explanatory narratives. As a demonstration let’s use this article from the Wall Street Journal. With this, we can provide a better prompt for the LLM. Instead of “Can you tell me the current market conditions that may affect one’s portfolio?”, we can have:
def enhanced-chatbot-response (ask-chatbot
("According to the WSJ on 19 September 2025, Stocks closed the week at record highs, propelled by investor optimism that the Federal Reserve
will keep cutting interest rates—and keep the market rally going. All three major indexes posted weekly gains of more than 1%.
The Fed cut the benchmark borrowing rate by 0.25% on Wednesday, and traders are now anticipating additional rate reductions in October and December.
The median projection of the Fed’s interest-rate setting committee also penciled in two additional cuts in 2025.
The S&P 500 rose 0.5% on Friday, while the tech-heavy Nasdaq gained 0.7%. The Dow Jones Industrial Average added 0.4%, or 173 points.
Based on this information, can you tell me the current market conditions that may affect one's portfolio?"))
:message enhanced-chatbot-response) (
"Of course. Based on the information provided from the hypothetical WSJ article, here are the current market conditions and how they may affect an investment portfolio:\n\n### Summary of Market Conditions:\n\nThe overarching theme is a **strong bullish (rising) market** driven primarily by monetary policy expectations.\n\n**1. Record-High Equity Prices & Strong Performance:**\n* **Condition:** All three major U.S. stock indexes (S&P 500, Nasdaq, Dow Jones) are at record highs and posted significant weekly gains (>1%).\n* **Portfolio Impact:**\n * **Positive for Equity Holdings:** Portfolios with exposure to U.S. stocks, particularly large-cap and technology stocks (as indicated by the Nasdaq's outperformance), have likely experienced substantial appreciation in value.\n * **Potential for Overvaluation:** This run-up increases the risk that assets may be becoming overvalued, which could lead to increased volatility or a sharper correction if the positive sentiment reverses.\n\n**2. Aggressive Federal Reserve Easing Cycle:**\n* **Condition:** The Fed has begun cutting interest rates (a 0.25% cut already implemented) and is signaling more cuts are on the horizon, with expectations for additional reductions in October, December, and into 2025.\n* **Portfolio Impact:**\n * **Lower Borrowing Costs:** Beneficial for companies, especially those with high debt, as it reduces their interest expenses, potentially boosting profits.\n * **Boost to Growth Stocks:** Technology and other growth-oriented stocks typically benefit more from lower interest rates, as their future earnings become more valuable in today's dollars. This explains the Nasdaq's strong performance.\n * **Pressure on Interest-Sensitive Holdings:** This environment is typically **negative for cash holdings and fixed-income assets** like bonds and CDs, as the interest they pay becomes less attractive. Existing bonds with higher fixed rates may see their market value increase, but new bonds will be issued at these lower rates.\n * **Weakness in the U.S. Dollar:** Anticipated rate cuts can put downward pressure on the U.S. dollar, which can be a tailwind for U.S. multinational companies (as overseas earnings are worth more when converted back to dollars) and for international investments.\n\n**3. High Investor Optimism and \"Goldilocks\" Sentiment:**\n* **Condition:** The rally is explicitly \"propelled by investor optimism.\" The market is interpreting the Fed's actions as a move to sustain economic growth without triggering inflation—a so-called \"soft landing\" or \"Goldilocks\" scenario (not too hot, not too cold).\n* **Portfolio Impact:**\n * **Momentum-Driven Gains:** This sentiment can become self-fulfilling in the short term, pushing prices higher.\n * **Increased Risk of a Sentiment Shift:** Portfolios are highly exposed to any change in this narrative. If economic data weakens significantly (suggesting recession) or strengthens too much (suggesting the Fed may halt cuts), it could quickly reverse the current optimism and lead to a market pullback.\n\n### Key Considerations for Portfolio Management:\n\n* **Asset Allocation Review:** It may be a good time to ensure your portfolio's mix of stocks, bonds, and cash aligns with your risk tolerance, especially since equities have surged.\n* **Sector Exposure:** The conditions favor growth-oriented sectors (like technology) and are less favorable to interest-rate-sensitive sectors like utilities or financials (which benefit from higher rates).\n* **Rebalancing:** Taking some profits from top-performing equity holdings to reinvest into underweighted asset classes (like bonds, which are now offering higher yields if purchased after a rate cut, or international stocks) could be a prudent strategy to manage risk.\n* **Stay Diversified:** While the current conditions are positive for stocks, maintaining a diversified portfolio across different asset classes and geographies remains the best defense against an unexpected shift in the market narrative.\n\nIn conclusion, the current conditions are **highly favorable for equity-heavy portfolios** but are built on expectations of continued Fed support. The largest risk is a change in those expectations or in the underlying economic data that drives Fed policy."
These narratives highlight potential reasons for performance, such as earnings reports or market events, guiding users on factors to investigate further.
3. Pedagogical Bridge: A Contextual Analysis
To ground the tool in intuitive understanding, we draw a parallel between financial performance and student learning assessment. Just as a grade alone doesn’t explain why a student succeeded or struggled, a return figure doesn’t explain why a portfolio moved.
We ask: Can we help investors understand not just what happened, but why?
4. Results and Discussion
4.1. On the Value of Contextual Analytics
While many tools report what happened, few explain why. Our Portfolio Analysis Program closes this gap by combining quantitative analysis with natural language reasoning. This hybrid approach supports both novice learners and experienced investors in diagnosing performance.
An important factor that will be extensively covered will be the idea of prompt engineering. Since the aim is to reduce hallucinations from AI, while bringing most relevant information to the forefront and potentially even make the tool diagnostic in nature, there will be clear attention to making the in-built prompt clear, structured and actionable. The AI’s role will be defined and the prompt will be potentially dynamic and change according to unique dates and portfolio requirements.
4.2. On Clojure’s Role in Modern Financial Systems
Clojure proves exceptionally well-suited for this kind of multi-system integration:
● Its JVM foundation enables seamless interaction with Java and Python ecosystems
● Functional design prevents side effects in complex pipelines
● REPL-driven development allows rapid iteration and debugging
The Portfolio Analysis Program demonstrates that Clojure is not just a language for backend services, but a first-class platform for intelligent financial applications.
4.3. Educational Implications
By linking portfolio metrics to real-world events, the Portfolio Analysis Program fosters critical thinking in investment education. Students learn to:
● Distinguish noise from signal
● Connect macro events to portfolio outcomes
● Evaluate whether returns were due to skill or circumstance
This creates a richer, more reflective learning experience, moving beyond spreadsheet-based grading to narrative-driven feedback.
By generating narrative explanations, e.g. “Apple’s 5% drop on June 3rd followed a weaker-than-expected iPhone sales forecast”, the tool transforms abstract volatility into contextual insight. This mirrors how educators use feedback to guide improvement, making PAT not just an analytics engine, but a coaching system.
This narrative-first approach is especially valuable in teaching environments, where students benefit from connecting market movements to real-world events.
5. Conclusion
This project demonstrates that:
● Functional programming in Clojure enables elegant, maintainable financial tooling.
● Integrating AI with traditional analytics adds interpretability and depth.
● Performance metrics become more meaningful when paired with contextual narratives.
We conclude that the future of portfolio analysis lies not in bigger dashboards, but in smarter, self-explaining systems. By building a Portfolio Analysis Program in Clojure, we show how a principled, functional approach can power tools that are not only technically sound, but also educationally transformative.
6. Future Work
● Add support for multi-asset portfolios (ETFs, bonds, crypto)
● Implement automated anomaly detection (e.g., unexpected drawdowns)
● Build a web interface using ClojureScript and Reagent for broader access
● Integrate with student trading logs for real-time feedback in portfolio management courses
● Develop custom benchmark comparisons (e.g., vs. S&P 500, sector indices)