Introduction

Artificial Intelligence (AI) has increasingly influenced modern financial markets by improving data analysis, investment research, and portfolio management. AI-assisted methods allow investors to identify market trends, evaluate company performance, and optimize investment decisions more efficiently.

The objective of this project is to construct and evaluate an AI-assisted investment portfolio using quantitative finance techniques and historical market data. AI was utilized to support stock selection, industry trend analysis, and portfolio optimization.

This project applies a Quality Momentum Strategy, focusing on companies with strong fundamentals and positive market momentum. The selected portfolio mainly consists of technology and AI-related companies expected to benefit from long-term growth in artificial intelligence, cloud computing, semiconductor innovation, and digital transformation.

To evaluate the effectiveness of the strategy, a three-year backtesting analysis is conducted using the SPY ETF as the benchmark. Portfolio performance is evaluated using several financial metrics, including cumulative return, Sharpe ratio, maximum drawdown, alpha, and beta.

Investment Thesis

Strategy Overview

This project applies a Quality Momentum Strategy by combining quality investing and momentum investing principles.

The quality factor focuses on companies with:

  • Strong profitability
  • Stable earnings growth
  • Competitive advantages
  • Healthy financial conditions

Meanwhile, the momentum factor focuses on stocks that demonstrate positive price trends and strong investor sentiment.

The rationale behind this strategy is that high-quality companies with strong momentum characteristics tend to outperform the broader market over time. In addition, the portfolio emphasizes companies operating in industries related to artificial intelligence, semiconductors, cloud computing, and digital technology, which are expected to experience long-term structural growth.

Source of Alpha

The expected source of alpha in this portfolio comes from exposure to high-growth technology sectors, strong earnings performance, and momentum persistence.

The strategy attempts to capture abnormal returns by investing in companies that benefit from increasing AI adoption and digital transformation trends. In addition, diversification across multiple leading firms helps reduce concentration risk while maintaining exposure to sectors with strong growth potential.

AI Collaboration Process

Artificial Intelligence tools such as ChatGPT were used throughout the portfolio construction process.

Example Prompts Used

Prompt 1

“Act as a quantitative analyst. Identify US-listed companies with strong momentum, strong earnings growth, and exposure to AI-related industries.”

Prompt 2

“Suggest a portfolio of high-quality technology stocks with strong long-term growth potential and relatively low financial risk.”

Prompt 3

“Explain why momentum and quality factors may generate abnormal returns in financial markets.”

AI assisted in: - Narrowing the stock universe - Identifying sector trends - Improving investment reasoning - Supporting portfolio optimization ideas

Portfolio Construction

Load Required Libraries

The following libraries are used to support portfolio analysis, optimization, data collection, and performance evaluation.

The tidyquant package is used to retrieve stock market data from Yahoo Finance. The PortfolioAnalytics and PerformanceAnalytics packages are used for portfolio optimization and financial performance analysis. Meanwhile, tidyverse is used for data manipulation and transformation.

library(tidyquant)
library(PortfolioAnalytics)
library(PerformanceAnalytics)
library(quantmod)
library(tidyverse)
library(ROI)
library(ROI.plugin.quadprog)
library(ROI.plugin.glpk)
library(xts)
library(lubridate)

Define Portfolio Assets

This section defines the stocks included in the portfolio and the benchmark used for performance comparison.

The selected assets mainly consist of large-cap technology and AI-related companies that demonstrate strong growth potential and market momentum. The SPY ETF is used as the benchmark because it represents the overall performance of the United States stock market.

tickers <- c(
  "NVDA",
  "MSFT",
  "META",
  "AMZN",
  "GOOGL",
  "AAPL",
  "AVGO",
  "AMD",
  "JPM",
  "V"
)

benchmark <- "SPY"

Portfolio Asset Description

The following table presents the selected assets included in the portfolio construction process.

portfolio_table <- data.frame(
  Ticker = c(
    "NVDA", "MSFT", "META", "AMZN", "GOOGL",
    "AAPL", "AVGO", "AMD", "JPM", "V"
  ),
  Company = c(
    "Nvidia",
    "Microsoft",
    "Meta Platforms",
    "Amazon",
    "Alphabet",
    "Apple",
    "Broadcom",
    "Advanced Micro Devices",
    "JPMorgan Chase",
    "Visa"
  )
)

knitr::kable(
  portfolio_table,
  caption = "Portfolio Asset List"
)
Portfolio Asset List
Ticker Company
NVDA Nvidia
MSFT Microsoft
META Meta Platforms
AMZN Amazon
GOOGL Alphabet
AAPL Apple
AVGO Broadcom
AMD Advanced Micro Devices
JPM JPMorgan Chase
V Visa

The benchmark used in this project is SPY, which tracks the S&P 500 Index. SPY is considered an appropriate benchmark because it represents the overall US equity market.

Data Collection

Download Historical Price Data

This step collects historical daily stock price data for all portfolio assets and the benchmark over the past three years.

The tq_get() function from the tidyquant package is used to download stock market data directly from Yahoo Finance. The adjusted closing price data will later be used to calculate daily returns and perform portfolio analysis.

start_date <- Sys.Date() - years(3)

prices <- tq_get(
  tickers,
  from = start_date,
  get = "stock.prices"
)

benchmark_prices <- tq_get(
  benchmark,
  from = start_date,
  get = "stock.prices"
)

Exploratory Data Analysis

Preview Historical Price Data

Before conducting portfolio optimization and backtesting, it is important to examine the historical market data collected for the selected assets.

The following table displays a preview of the daily stock price dataset retrieved from Yahoo Finance. The dataset includes important market information such as opening price, closing price, highest price, lowest price, trading volume, and adjusted closing price.

head(prices)

Historical Price Visualization

The next step is visualizing the historical stock price movements of the selected assets over the past three years.

This visualization helps identify general market trends, growth patterns, and price volatility among portfolio assets. Several companies, particularly technology and semiconductor firms, experienced substantial price appreciation during periods of strong AI-related market sentiment.

prices %>%
  ggplot(aes(x = date, y = adjusted, color = symbol)) +
  geom_line(show.legend = TRUE) +
  labs(
    title = "Historical Stock Price Trends",
    x = "Date",
    y = "Adjusted Closing Price",
    color = "Ticker"
  ) +
  theme_minimal()

Summary Statistics

Descriptive statistics are useful for understanding the overall characteristics of the selected assets before conducting portfolio optimization.

The following summary statistics provide information regarding the average price, volatility, minimum price, and maximum price of each stock included in the portfolio.

prices %>%
  group_by(symbol) %>%
  summarise(
    Mean_Price = mean(adjusted),
    Std_Dev = sd(adjusted),
    Min_Price = min(adjusted),
    Max_Price = max(adjusted)
  )

Return Calculation

Calculate Daily Returns

After collecting the historical price data, the next step is calculating daily stock returns.

The periodReturn() function is used to calculate daily percentage returns based on adjusted closing prices. Then, the data is transformed into xts time-series format because portfolio optimization and backtesting functions in R commonly require time-series data structures.

returns <- prices %>%
  group_by(symbol) %>%
  tq_transmute(
    select = adjusted,
    mutate_fun = periodReturn,
    period = "daily",
    col_rename = "returns"
  ) %>%
  pivot_wider(
    names_from = symbol,
    values_from = returns
  ) %>%
  drop_na()

returns_xts <- xts(
  returns[,-1],
  order.by = returns$date
)

The daily return series generated in this step will be used for portfolio optimization and backtesting analysis in the next stage.

Return Distribution Analysis

Understanding return distribution is important because it helps evaluate the volatility and risk characteristics of the portfolio assets.

The following visualization shows the distribution of daily returns across all selected assets. Stocks with wider distributions generally indicate higher volatility and investment risk.

returns %>%
  pivot_longer(
    cols = -date,
    names_to = "Ticker",
    values_to = "Daily_Return"
  ) %>%
  ggplot(aes(x = Daily_Return, fill = Ticker)) +
  geom_histogram(
    bins = 50,
    alpha = 0.6
  ) +
  facet_wrap(~Ticker, scales = "free") +
  theme_minimal() +
  labs(
    title = "Distribution of Daily Returns",
    x = "Daily Return",
    y = "Frequency"
  )

Portfolio Optimization

Construct Portfolio Specification

After calculating daily returns, the next step is constructing the portfolio optimization model.

Portfolio optimization is performed to determine the optimal asset allocation that maximizes return while controlling portfolio risk. This project applies a long-only portfolio strategy, meaning that short selling is not allowed and all portfolio weights must remain positive.

The optimization process uses the mean-variance optimization framework introduced by Harry Markowitz, where portfolio return and portfolio volatility are simultaneously considered.

portfolio_spec <- portfolio.spec(assets = tickers) %>%
  add.constraint(type = "full_investment") %>%
  add.constraint(type = "long_only") %>%
  add.objective(type = "return", name = "mean") %>%
  add.objective(type = "risk", name = "StdDev")

Optimize Portfolio Weights

The next step is generating the optimal portfolio weights based on the Sharpe Ratio optimization approach.

The Sharpe Ratio optimization attempts to maximize portfolio return relative to portfolio volatility. Higher Sharpe Ratios indicate more efficient risk-adjusted portfolio performance.

optimized_portfolio <- optimize.portfolio(
  R = returns_xts,
  portfolio = portfolio_spec,
  optimize_method = "ROI",
  max_sharpe = TRUE
)

weights <- extractWeights(optimized_portfolio)

weights
##          NVDA          MSFT          META          AMZN         GOOGL 
##  5.627562e-01 -3.981249e-17  9.479327e-33  3.045861e-17  7.838999e-04 
##          AAPL          AVGO           AMD           JPM             V 
## -5.396120e-17  4.337957e-01  2.664187e-03  0.000000e+00 -2.863256e-16

Portfolio Weights

Optimized Portfolio Allocation

The following table presents the optimized allocation weights for each portfolio asset.

weight_table <- data.frame(
  Ticker = names(weights),
  Weight = round(weights, 4)
)

knitr::kable(
  weight_table,
  caption = "Optimized Portfolio Weights"
)
Optimized Portfolio Weights
Ticker Weight
NVDA NVDA 0.5628
MSFT MSFT 0.0000
META META 0.0000
AMZN AMZN 0.0000
GOOGL GOOGL 0.0008
AAPL AAPL 0.0000
AVGO AVGO 0.4338
AMD AMD 0.0027
JPM JPM 0.0000
V V 0.0000

Portfolio Weight Visualization

The following visualization illustrates the percentage allocation of each asset within the optimized portfolio.

weight_table %>%
  ggplot(aes(x = reorder(Ticker, Weight), y = Weight, fill = Ticker)) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  theme_minimal() +
  labs(
    title = "Optimized Portfolio Weights",
    x = "Ticker",
    y = "Portfolio Weight"
  )

Backtesting

Calculate Portfolio Returns

After determining the optimal asset allocation, the next step is calculating portfolio returns using the optimized weights.

The portfolio return series represents the overall daily performance of the AI-assisted investment portfolio throughout the backtesting period.

portfolio_returns <- Return.portfolio(
  returns_xts,
  weights = weights
)

colnames(portfolio_returns) <- "AI_Portfolio"

Calculate Benchmark Returns

To evaluate portfolio performance, benchmark returns are also calculated using the SPY ETF.

The benchmark serves as a market reference for determining whether the portfolio strategy successfully outperformed the broader market.

benchmark_returns <- benchmark_prices %>%
  tq_transmute(
    select = adjusted,
    mutate_fun = periodReturn,
    period = "daily",
    col_rename = "Benchmark"
  )

benchmark_returns_xts <- xts(
  benchmark_returns$Benchmark,
  order.by = benchmark_returns$date
)

colnames(benchmark_returns_xts) <- "Benchmark"

Combine Portfolio and Benchmark Returns

The portfolio and benchmark return series are combined into a single dataset to simplify comparative performance analysis.

combined_returns <- merge.xts(
  portfolio_returns,
  benchmark_returns_xts
)

Performance Visualization

Portfolio vs Benchmark Performance

The following chart compares the cumulative performance of the AI-assisted portfolio against the SPY benchmark over the backtesting period.

charts.PerformanceSummary(
  combined_returns,
  main = "Portfolio vs Benchmark Performance"
)

Performance Metrics

Annualized Returns

Annualized return measures the average yearly return generated by the portfolio and benchmark during the backtesting period.

table.AnnualizedReturns(combined_returns)

Sharpe Ratio

The Sharpe Ratio evaluates portfolio return relative to portfolio risk. A higher Sharpe Ratio indicates more efficient risk-adjusted performance.

SharpeRatio.annualized(combined_returns)
##                                         AI_Portfolio Benchmark
## Annualized Sharpe Ratio (Rf=0%, p=95%):     1.539441   1.43543

Maximum Drawdown

Maximum Drawdown measures the largest decline from a portfolio peak to its lowest point during the investment period.

maxDrawdown(combined_returns)
##                AI_Portfolio Benchmark
## Worst Drawdown    0.3726916 0.1875524

CAPM Statistics (Alpha & Beta)

The following analysis calculates portfolio alpha and beta relative to the benchmark.

table.CAPM(
  portfolio_returns,
  benchmark_returns_xts
)
  • Alpha measures excess portfolio return beyond expected market return.
  • Beta measures portfolio sensitivity to overall market movements.

Positive alpha indicates that the portfolio generated abnormal returns relative to the benchmark after adjusting for market risk.

Analysis and Discussion

The backtesting results demonstrate the effectiveness of the Quality Momentum strategy during the selected investment period.

Several important observations can be identified from the analysis. First, technology and semiconductor companies contributed significantly to overall portfolio performance due to strong market demand for artificial intelligence infrastructure and cloud computing services. Companies such as Nvidia, Microsoft, and Broadcom benefited substantially from increasing AI adoption and investor optimism toward technological innovation.

Second, the momentum component of the strategy helped capture strong upward market trends during periods of positive investor sentiment. Stocks with sustained positive price momentum generally continued outperforming due to institutional investment flows and favorable earnings expectations.

Third, diversification across multiple technology and financial firms helped reduce concentration risk while maintaining exposure to high-growth sectors. Although technology stocks tend to exhibit relatively high volatility, diversification improved the overall portfolio risk profile.

The comparison against the SPY benchmark indicates whether the AI-assisted portfolio successfully generated abnormal returns relative to the broader market. If the portfolio demonstrates higher cumulative return and Sharpe Ratio than the benchmark, the proposed strategy can be considered effective in achieving superior risk-adjusted performance.

However, the portfolio may still experience periods of elevated volatility due to its substantial exposure to growth-oriented technology companies. As a result, market corrections affecting the technology sector could significantly influence short-term portfolio performance.

Critical Reflection

AI Insights

Artificial Intelligence provided several valuable insights throughout the portfolio construction process. AI-assisted analysis helped identify sectors expected to benefit from long-term structural growth, particularly artificial intelligence infrastructure, semiconductors, cloud computing, and digital services.

In addition, AI improved analytical efficiency by assisting in stock screening, narrowing the investment universe, and supporting investment reasoning based on financial and industry-related information.

Traditional investment analysis may overlook how rapidly AI adoption and technological innovation can influence future corporate earnings growth and investor sentiment. Therefore, AI-assisted reasoning contributed additional perspectives that strengthened the overall portfolio construction process.

Strategy Evaluation

Overall, the backtesting results generally support the initial hypothesis that combining quality and momentum factors can potentially generate abnormal returns relative to the market benchmark.

Nevertheless, several limitations should still be considered. Historical market performance does not guarantee future investment returns, particularly in rapidly evolving industries such as technology and artificial intelligence. In addition, growth-oriented technology stocks often experience higher volatility and may be highly sensitive to macroeconomic conditions, interest rate changes, and shifts in investor sentiment.

Another limitation is that this project does not incorporate transaction costs, taxes, or periodic portfolio rebalancing, which could influence real-world investment performance.

Future improvements for this strategy may include: - Dynamic portfolio rebalancing - Sentiment analysis integration - Risk parity optimization - Macroeconomic factor modeling - Machine learning-based forecasting models

These improvements may further enhance portfolio performance and strengthen the robustness of the investment strategy.

Conclusion

This project demonstrates how Artificial Intelligence can support modern portfolio construction and investment analysis through a combination of data-driven reasoning and quantitative finance methodologies.

By integrating AI-assisted stock selection, portfolio optimization, and quantitative backtesting, the proposed Quality Momentum strategy attempted to identify high-quality companies with strong growth potential and favorable market momentum.

The backtesting analysis provided important insights regarding portfolio return, risk-adjusted performance, downside risk, and market sensitivity relative to the SPY benchmark. The results suggest that AI-assisted investment strategies may potentially improve portfolio decision-making and generate competitive performance under favorable market conditions.

Overall, this project highlights the growing importance of Artificial Intelligence in modern financial markets and demonstrates how AI can serve as a valuable analytical tool in quantitative portfolio management.