Building and Testing Stock Portfolios in R (2024)

Building and Testing Stock Portfolios in R (3)

In this article, we’ll examine how to get stock data, analyze it to make investment decisions, and visualize the results.

With the recent surge in retail investors entering the market, it’s more important than ever that new traders are armed with the tools they need to compare stocks by analyzing their performance over time. In this post, we’ll use the stock data of three familiar companies — Starbucks, Carnival, and Apple — to construct a portfolio, examine its historical performance, and compare it to the S&P 500.

Three very useful packages for financial analysis in R are quantmod , to pull stock data from Yahoo Finance; PerformanceAnalytics , to construct and test portfolios; and dygraphs , to produce interactive and informative visualizations of our data. If you don’t have these packages installed, you can install and load them into your R environment using the code below.

Once we have the packages installed and loaded, we can write a function to get monthly return data for our individual stocks. Our function takes two arguments: ticker , the stock’s symbol, and base_year , the year that we want to start analyzing the data.

This function can appear a bit complicated if you are unfamiliar with R and its packages. Here’s an explanation of each line:

  • Line 4: Passes our ticker symbol to the getSymbols() function to get our stock data from Yahoo Finance
  • Lines 5–8: Removes any missing values from the data and isolates the “Adjusted Price” column (the sixth column), which accounts for stock splits, dividends, and other corporate actions (more on that here)
  • Lines 10–12: Uses R’s built-in paste0() and Sys.Date()functions to create a string we can pass between brackets so that only observations between our base year and today’s date are selected
  • Line 15: Calculates monthly arithmetic returns for our adjusted closing stock price data
  • Line 18: Assigns our monthly return data to R’s global environment to ensure that we can access it by its ticker symbol later

After writing our function, it’s now available for us to calculate monthly returns for our three stocks. We need to call our function four times — once for each stock we want to analyze and once for the S&P 500 — so that we have a benchmark against which to judge each stock’s monthly performance. We can then merge all our monthly returns into one time series object and look at the last several years’ performance for each using the dygraphs package (check out the interactive version here). The last line prints the last five months of return data and its output is reproduced below.

Building and Testing Stock Portfolios in R (4)
Building and Testing Stock Portfolios in R (5)

From our returns data set, we can get a sense of how well each stock has performed relative to the S&P 500 over the last several years. For example, when news of the spread of COVID-19 was roiling financial markets in March 2020, the S&P 500 recorded a loss of about 12.5% while Carnival lost more than 60% of its value for that month. Apple, by contrast, experienced a loss of only about 7%. Using corrplot::corrplot(cor(returns), method = number) generates a correlation matrix to indicate how these stocks’ returns are related to each other.

Building and Testing Stock Portfolios in R (6)

A fundamental principle of portfolio management is that you should select stocks with low correlations to each other. You wouldn’t want all the stocks in your portfolio to always rise and fall together — that could expose you to excess volatility that you may want to avoid, especially if this is a retirement account where preservation of principle is your main concern. A portfolio made up of highly correlated stocks is subject to unsystematic risk stemming from the firm-specific risks inherent to each stock.

From our correlation matrix, we observe that all of our stocks are positively correlated, albeit in varying degrees. Apple is only weakly correlated with Starbucks (0.27), but Carnival and the S&P 500 have a high correlation (0.71) with each other. Importantly, all of our stocks have a fairly high positive correlation with the market, meaning they tend to move with the market most months.

We can use the PerformanceAnalytics package to assign weights to our stocks and build a hypothetical portfolio from them. In the following code, we assume that we are investing one-third of our money in Starbucks, one-third in Carnival, and one-third in Apple, excluding the S&P 500 for the moment. The Return.portfolio() function allows us to pass in our individual stock data from the returns object along with their weights. We can set the wealth.index argument equal to TRUE to show how $1 invested in our portfolio in 2015 would have grown over time. Then, we can follow the same process for the S&P 500, excluding the weights argument. After merging our data into one xts object, we can contrast our portfolio with the S&P 500 using another graph (interactive version here):

Building and Testing Stock Portfolios in R (7)

If we had invested $1 into our Starbucks-Carnival-Apple portfolio at the beginning of 2015 and didn’t touch it (i.e., no re-balancing), our portfolio’s value would have almost doubled (92.31%). This beat the performance of the S&P 500, which still yielded an impressive return of about 73% over the same time horizon. Of course, we could make some minor tweaks to our code to change portfolio weights, add additional stocks (or other assets like government bonds and precious metals), and experiment with re-balancing. With R and its libraries, our ability to construct and test portfolios is virtually unlimited.

I hope I’ve made the process of getting and analyzing stock data a little less intimidating. With the code above, we were able to import a large amount of financial information, construct a portfolio, examine its composition, and analyze historical performance relative to a benchmark. In future posts, I’ll explore some other ways we can use R and its libraries to analyze financial data.

Thanks for reading!

Building and Testing Stock Portfolios in R (2024)

FAQs

How should I structure my stock portfolio? ›

The conservative allocation is composed of 15% large-cap stocks, 5% international stocks, 50% bonds and 30% cash investments. The moderately conservative allocation is 25% large-cap stocks, 5% small-cap stocks, 10% international stocks, 50% bonds and 10% cash investments.

How do you build a good stock portfolio? ›

6 Steps to Building Your Portfolio
  1. Step 1: Establish Your Investment Profile. No two people are exactly alike. ...
  2. Step 2: Allocate Assets. ...
  3. Step 3: Decide how to diversify. ...
  4. Step 4: Select investments. ...
  5. Step 5: Consider Taxes. ...
  6. Step 6: Monitor your portfolio.

What is R in portfolio management? ›

R-Squared (R²) is one of the statistical tools to measure the risk of a mutual fund. R-squared compares the performance of a mutual fund scheme to a given benchmark index. There are tools like alpha, beta as well, which measure the risk of a mutual fund in other ways.

What is the introduction of portfolio analysis? ›

Portfolio analysis is concerned with the development of theoretical models designed to analyse the factors affecting the financial assets held by economic agents, together with the empirical testing of these models.

What is the 5 portfolio rule? ›

The 5% rule says as an investor, you should not invest more than 5% of your total portfolio in any one option alone. This simple technique will ensure you have a balanced portfolio.

What are the 7 steps of the portfolio process? ›

Processes of Portfolio Management
  • Step 1 – Identification of objectives. ...
  • Step 2 – Estimating the capital market. ...
  • Step 3 – Decisions about asset allocation. ...
  • Step 4 – Formulating suitable portfolio strategies. ...
  • Step 5 – Selecting of profitable investment and securities. ...
  • Step 6 – Implementing portfolio. ...
  • Step 7 – ...
  • Step 8 –

How many stocks should a beginner portfolio have? ›

The question is when has volatility been reduced enough such that the marginal benefit of an additional holding is immaterial. Most studies use the fully diversified portfolio as a benchmark and then derive that a portfolio of 20-30 stocks achieves a 'similar' risk profile as the target portfolio.

What is the best ratio for a stock portfolio? ›

If you wish moderate growth, keep 60% of your portfolio in stocks and 40% in cash and bonds. Finally, adopt a conservative approach, and if you want to preserve your capital rather than earn higher returns, then invest no more than 50% in stocks.

How many stocks should be in an ideal portfolio? ›

What's the right number of companies to invest in, even if portfolio size doesn't matter? “Studies show there's statistical significance to the rule of thumb for 20 to 30 stocks to achieve meaningful diversification,” says Aleksandr Spencer, CFA® and chief investment officer at Bogart Wealth.

Is R good for stock analysis? ›

Quantmod is an R package specifically designed for quantitative financial modeling and trading. It provides a wide range of functions and tools for collecting, analyzing, and visualizing financial and stock market data.

How to perform a portfolio analysis? ›

There are four major steps to analysing a portfolio.
  1. Step 1: Revisit or Define investment objectives and understand your resources and requirements. ...
  2. Step 2: Determine asset allocation and benchmark. ...
  3. Step 3: Check the portfolio's performance in light of the objectives. ...
  4. Step 4: Rebalance the portfolio if required.
Sep 29, 2022

What does R mean in stocks? ›

The Letter R at the end of a NASDAQ ticker symbol means the security being quoted is a rights offering. Rights offerings that are sold by shareholders are traded on the open market. In financial formulas the letter R designates Returns.

What are the three main criteria used for portfolio analysis? ›

We propose as a first step, a classification of projects based on the three most important criteria namely the value maximization, risk minimization and strategic alignment.

What should a portfolio analysis include? ›

Portfolio analysis is a quantitative technique that is used to determine the specific characteristics of an investment portfolio. The process of analyzing a portfolio involves several stages, including a statistical performance review, risk and risk-adjusted metrics, attribution, and positioning.

What is the ideal stock portfolio mix? ›

Many financial advisors recommend a 60/40 asset allocation between stocks and fixed income to take advantage of growth while keeping up your defenses.

What is a 70 30 investment strategy? ›

This investment strategy seeks total return through exposure to a diversified portfolio of primarily equity, and to a lesser extent, fixed income asset classes with a target allocation of 70% equities and 30% fixed income. Target allocations can vary +/-5%.

What is the best portfolio allocation? ›

The 60/40 portfolio dictates a simple split of your assets— 60% for stocks and 40% for bonds. This asset allocation is simple to apply and understand, which may appeal to investors who prefer more of a hands-off approach.

How should my stock portfolio be balanced? ›

The best way to balance your portfolio should account for your risk tolerance, financial plans, and evolving needs over time. A good way to minimize risk is by creating a diversified and balanced portfolio with stocks, bonds, and cash that aligns with your short- and long-term goals.

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 6345

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.