Adding artificial intelligence to your investing strategy; part 1

Patrick Collins
Alpha Vantage
Published in
5 min readJan 10, 2020
Photo by Franck V. on Unsplash

At the end of this article will be an example of how to build a simple model that predicts the prices of stocks in the future, integrated with some AI tools.

With all the advances in artificial intelligence (AI), it’s easier than ever to get started building a strategy that uses machine learning and AI right out of the box. There are a plethora of reasons why individuals and institutions choose to have strategies involving AI techniques.

Robo-advisors like Betterment, SoFi, and Wealthfront stake the majority of their existence on their AI-powered strategies.

It can sound daunting to get started, but their are a lot of reasons why a lot of these companies have popped up in the last few years, and there are a lot of tools for you to start integrating AI into your investment strategies right now.

Before we get started, first a little bit of a clarification.

AI vs Machine Learning

AI and machine learning are often used interchangeably, but they mean slightly different things. Simply put, AI is the execution of learnt information while machine learning is the process of gaining insight from data.

In order to have AI, you need to learn or be learning first. Only then can your system actually make decisions. We want to first teach a system, and then have it make decisions. It’s the same as how a human works to build strategies:

  1. Learn and train your decision making (Machine learning)
  2. Make decisions/predictions (AI)

Tools

One of the main reasons it has become so easy to get started in AI is the massive amount of tools available. We are going to look at the python ones for this article, since python has recently become the most popular language in the world, and its library of AI tools.

To get started, we’ve recently become fans of the book Hands-On Machine Learning with Scikit-Learn and TensorFlow. It has all of its examples online that you can try out right now.

A-Z of AI

Python also has some additional open source and out-of-the box tools to play with:

  • Pandas/Numpy for easy data manipulation.
  • Keras for deep learning. Here is GitHub user driemworks’ implementation of Keras on Alpha Vantage data. A little humor thrown in there too :)
  • Matplotlib for data visualization.
  • Theano so you can define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays efficiently.
  • Scikit-image for image processing.
  • PyBrain for neural networks, unsupervised and reinforcement learning.

Now as I mentioned above, with so many tools, it’s easy to feel overwhelmed. You can start however, with something as simple as a linear regression.

Linear Regression -> Sophisticated AI strategy

A linear regression is a simple type of predictive analysis. It is the attempt to model the behavior of two variables in a linear way. Or put more simply, get a straight line on a graph that somewhat accurately shows the relationship.

For example, if we want to look at the variables time (x axis) and price (y axis) and see if there is a relationship for a ticker (TSLA).

As stated above, the two steps are:

  1. Learn/train
  2. Make decisions/predictions

Let’s start with TSLA. Here is a graph of the TSLA’s stock price dating back to its IPO:

We can get this graph pretty easily with this code:

# Code example
import matplotlib.pyplot as plt
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
# Remember to have an environment variable named:
#ALPHAVANTAGE_API_KEY
# otherwise, use:
# ts = TimeSeries(output_format = "pandas", key = <key_here>)
ts = TimeSeries(output_format = "pandas")
tsla_data, meta_data = ts.get_daily_adjusted(symbol = 'TSLA', outputsize = 'full')# Visualize the data
tsla_data = tsla_data.reset_index() # Make the index a column
tsla_data.plot(x = 'date', y = '5. adjusted close')
plt.show()

This is the dataset that we want to train on.

Remember we are going to make a linear regression, so we are looking for a simple straight line. I’m sure many of you know a number of ways you could do it yourself, but python tools make it easier so you can save your brainpower and time elsewhere.

Using the sklearn.linear_model python package, we can simply tell your computer to train on this dataset, and then use that data to make a linear prediction. Add the following code to the code above:

import sklearn.linear_model
# The prediction package doesn't work with dates
# So we convert all the dates in the index to floats
tsla_data['date'] = tsla_data['date'].values.astype(float)
# # We can go over what .c_ does later
X = np.c_[tsla_data['date']]
Y = np.c_[tsla_data['5. adjusted close']]
# Select a linear model
model = sklearn.linear_model.LinearRegression()
# Train the model
model.fit(X, Y)
# Make a prediction
date = [[1736208000000000000.0]] # This is the float value of 2025-01-07
print(model.predict(date))

With this package, you simply tell it what variables to look for a relationship on, create the model, and then make the predictions.

As you can see, the model.predict method takes a list of lists, so you can pass in as many dates as you’d like for the model to predict.

With a little extra credit, we can even see what the model would predict in the next few years:

You will notice it’s a straight line! Perfect.

Now it’s safe to say a model like this probably would not perform all that well (although… maybe you can make some tweaks to make it perform amazingly), but this is the first step to becoming stronger at creating your AI strategy and backtesting.

What do you think? Is a linear regression model something that you think could be added to your investing tool kit? What did you learn from here?

Share your implementation of Alpha Vantage with Scikit and Linear regressions!

Follow Alpha Vantage on Slack, Twitter, Discord, Medium, and Linkedin for updates, new announcements, competitions, tutorials, and more!

--

--