R-programming and Investing

Hello!

I pursue investing and R programming purely because both are fun and useful hobbies. I couldn’t find a thread here about R programming related to investing. This primarily indicates that the topic isn’t hot. However, I’ve heard it’s even used on Wall Street. :slight_smile: Potentially, I see R as an interesting topic for an investor.

I’ve gone through R programming material related to investing on Google and YouTube and familiarized myself with the quantmod and PerformanceAnalytics packages. The packages are great in themselves, but perhaps they don’t quite fit my needs. Of course, it’s cool to be able to draw price curves based on price data downloaded from Yahoo or similar sources.

I’ve defined my first investing-related project to be a small Rmarkdown document that provides a summary of my investments. I thought I’d do it by downloading trades and other events from Nordnet and manually entering the latest prices. The output should be statistics on my annual returns in tabular form. Of course, curves would be neat, but is it realistic to get current price data for all Finnish small-cap companies smoothly from one place, at least for free?

It would be nice to hear if there are other investors interested in R on this forum! Additionally, I’d love to hear book recommendations, blog/YouTube video, etc. related to the topic. I prefer using the Tidyverse library, and it’s even better if the examples are implemented with it.

13 Likes

Interesting thread! Nowadays, as Python is one of the most popular first programming languages and a very widely known language, could you explain what makes R interesting from an investor’s perspective? Does knowing R provide any special advantage, or is it mainly a matter of preference? I know that some MATLAB/Octave guys have found transitioning to R easier. I also understand that in the deepest depths of statistics, R has some competitive advantage over Python, but few of us end up doing such in-depth stock analysis :smiley:

2 Likes

Nice that the discussion has started! I haven’t delved into Python myself, but I’ve read some blog posts comparing the languages mainly from a data analytics perspective, and apparently, both can handle the job well. As I understand it, Python is more versatile if you want to develop software. I’m more interested in statistics, and I find R pleasant to use when it comes to manipulating data and getting results/graphs out with a small amount of code. As a non-programmer, the code is quite easy to produce. This is the area that particularly interests me. If I wanted to create actual applications, I would probably consider another language. If one hasn’t delved into either language, I would certainly seriously consider where to put one’s resources. :slight_smile:

2 Likes

Have you checked this out?

2 Likes

I don’t know anything about coding and so on, at least not yet, but the R-language has come up in the university’s course selection and seemed interesting. Even more interesting if it could be of some benefit for investing or for crunching my own numbers :grin:

2 Likes

I talked a lot with a former colleague about utilizing ML in stocks, but it’s a bit touch and go whether models can actually benefit real stock purchases. Especially if you can’t access real-time APIs.

More benefit could come from supporting your own analyses (custom charts and implementations). R and Python certainly offer good opportunities for that :slight_smile:

2 Likes

What’s more, R has been made into a plug-in for Python, so I don’t see why R should be used. Perhaps it is easier to learn when using R-Studio, but otherwise, I would study Python.

1 Like

Many others have surely thought about this too. In my own experiments, I’ve found that it’s simple in concept but almost impossible to implement at home. I see the greatest benefit in using technical signals to support decision-making, i.e., coding a script to notify you when desired signals occur in your preferred stocks, so you don’t have to actively monitor prices yourself.

It’s worth mentioning that several high-level researchers who have studied Google Trends have concluded that even though people’s search behaviors offer great signals and extremely fascinating information, turning them into money is very challenging, if not impossible. I recommend coding tweet sentiment analyzers and similar projects as an exercise, but don’t expect to make money from them easily.

I’ve been thinking lately that if I had flexible access to Inderes forum data (I wouldn’t want to scrape the entire site…), it would be interesting to dig out trending companies and the development of sentiment/activity around different companies, and explore if any signals could be found there. Generally, following Verneri, the model portfolio, etc., has been one of the most successful trends during this bull market. Also, buying companies with traditional “buy” recommendations or those that have given positive profit warnings have been quite successful strategies.

It’s also worth noting that, based on Inderes’ own user survey, favoring the top-trending companies has been quite profitable: Apparently, the swarm intelligence of “windbreaker investors” (casual investors) has worked quite well during the bull market. I’m curious to see how Inderes’ favored growth companies will fare during the next downturn and crash: Will big, stable, and boring Kesko, Elisa, and Kone be strong then, or will Inderes’ model portfolio beat the index now and always?

I’m also eagerly waiting to see if, over the next couple of decades, profitable models in stock trading, online poker, and similar areas can be achieved purely through reinforcement learning or similar methods. There are very interesting open-source projects for those interested in the topic (for example, TensorFlow-based TensorTrade, which aims to autonomously learn profitable trading strategies. The hobbyist community is reasonably sized and the skill level is excellent, but I haven’t heard of anyone making money in that field to date - or at least no one has been shouting about it).

If you only want to run data analytics, it probably doesn’t matter whether you learn R or Python (or perhaps JavaScript). If you want to monitor your own portfolio, JavaScript makes it very easy to create very stylish plots that you can run and monitor on your home computer. If you want to run ML, you should immediately turn your attention to Python. Most quantitative analytics courses and programs I’ve seen are taught specifically in Python. In job postings for “big boys” in the field, it probably invariably says “advanced knowledge in python and/or R,” so I wouldn’t strongly differentiate R from Python in discussions on this topic.

7 Likes

In fundamental analysis, programming can be very beneficial when you don’t constantly have to calculate key figures. Of course, even the simplest implementations can be done with Excel. You also don’t need access to the most up-to-date course data when your investment horizon is a bit longer. You can then sort stocks according to the key figures in any way you want or do something else. A Five-Factor Asset Pricing Model https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2287202 might be a good one to check out to see one approach.

3 Likes

Try R’s BatchGetSymbols package. If you need technical indicators, R’s TTR package works well.

3 Likes

Thanks for the tip, I hadn’t. That Jupyter Notebook seems like an interesting project and looks like it supports R code as well. Beautiful images that look like they were drawn with ggplot, which is definitely a plus. It would be nice to create exactly that type of informative graphics from my own portfolio at a glance. :slight_smile:

1 Like

It certainly increases motivation, e.g., for making analyses for a thesis, if synergies can be found in investing.. :wink:

1 Like

Thanks, I’ll have to look into those.. :slight_smile:

1 Like

You can use code blocks here if you want to share something. Those 3 backticks.

public class CodeFormatting {
    public static void main(String[] args) {
        System.out.println("I can format code now!");
    }
}
5 Likes

{“content”:“Good thread. I once took R basics through Datacamp, it was pretty okay for the basics as I recall.”,“target_locale”:“en”}

2 Likes

That’s exactly what I’m looking for. Once I get the basic statistical analysis of my own portfolio in order, I’ll try to develop my own company analysis/familiarization workflow, where I would utilize data produced by Inderes and then draw my own graphs and tables based on that and the data provided by the company. So, nothing fancy like machine learning, but just basic long-term investing, which I thought I’d make easier with my own R scripts/RMarkdown documents. :slight_smile: An interesting article, and apparently considered very interesting based on the citation count in Web of Science. Not the easiest read, but I’ll have to delve into it. After all, Fama is one of those well-known experts repeated in economics podcasts.

1 Like

I still have a way to go with this, but if someone smarter wants to share their code, I’d be really interested to check it out.. :slight_smile:

1 Like

It’s great that the forum also has an interest in a more quantitative analysis!

Based on what wiser people have told me, I’ve understood that R’s strengths (vs. Python) are:

  1. Agility in exploratory data analysis. With R, checking many small things is quick when you want to get to know the data and aren’t yet completely clear about what you want to learn and with what methods. The plotting capabilities in R are also first-class (ggplot2).

  2. A huge number of packages. Almost anything you want to do with R, someone else has probably already done it, and ready-made functions can be found by just searching for the right package.

On the other hand, R’s downsides, as I understand it, are its somewhat difficult syntax and slowness with heavier analyses. Additionally, Python can do more than just data analysis-related programming, so in that sense, it’s a more versatile language.

I’ve been using R (and Stan) myself for a few years now while working on my dissertation and have started to wonder if the tools I’ve acquired could also be used in my budding investment hobby. I don’t know the answer. I’ve intended to read some ML + finance textbook, but haven’t gotten around to it yet. My impression, however, is that applying machine learning/statistics to investing is quite challenging, especially when you only have a finite amount of time and a graduate student’s budget.

Nevertheless, just for hobby purposes and possibly later also for employment, I’ve been thinking about getting some project going at some point. I don’t have any grand visions at the moment, but I’ll have to check out the paper linked above and the machine learning thread to see if I can get some inspiration from them. If anyone has good ideas, feel free to share! Also, if anyone is interested in a playful joint project, that could be a fun experience too :slight_smile:

2 Likes

I’ve been working on a model that predicts stock returns, using daily price data and financial statement information to create a forecast. Min and max refer to the predicted price movement minus/plus the risk (standard deviation of the forecast). Sharpe is then the predicted return divided by the risk, and based on its highest value, the return forecast and associated risk are selected.

Then, using simulation and an investment plan, we determine how much to invest with this information. The investment plan is compared to equal diversification, where an equal amount is invested in each stock.

1 Like

Great! :slight_smile: R has a lot of good sides, but there’s a kind of historical baggage in base R, which manifests as inconsistencies in some respects. As I understand it, Hadley Wickham, the developer of tidyverse and RStudio, has criticized this and apparently wants to create his own R entirely around tidyverse…? :slight_smile: R is a high-level language, and with just a few lines of code, you can do really impressive things, if you know how. The downside is that it’s devilishly difficult to grasp, at least at first. I’m talking about, for example, the iteration functions in the purrr package. And even base R’s lapply and sapply make the brain cells heat up. I don’t really want to go back to having to manually allocate memory space if I want to create a variable. :smiley:

I learned the basics of R using the swirl package and materials found online. Then I read Hadley Wickham and Garrett Grolemund’s “R for Data Science” book (freely available). When I first read it, I thought I didn’t understand anything about R. :smiley: But the tidyverse world is a place of its own, and pleasantly consistent. I think that book is really good both as a textbook and as a reference, and I always flip through it when I encounter a problem. I would recommend it to anyone interested in R.

I plan to proceed project by project, and currently, I’m working on calculating the returns of my modest “portfolio.” I’ve scoured Google, and I’m quite surprised that apparently no one has seen fit to calculate their own returns with R (and make their code available to others)? Or even in general. The best starting point, in my opinion, is the Portfolio Management with R (PMwR) package. But it’s also quite unfinished. It allows you to create a “journal,” i.e., put transactions into a table, but then when you need to start calculating returns, this object apparently cannot be used directly; instead, the package’s functions want only vectors as parameters, e.g., for prices. My conclusion is that apparently it’s considered more interesting to calculate the returns of various stocks and funds that one doesn’t actually own, but instead to create some theoretical portfolio. :smiley:

From an employment perspective, it could be a good addition to a CV to have cool coding projects on GitHub. :wink:

1 Like