The Alpaca API Explained for People Who Want to Get Started Trading

You don’t have to be an economist to get power out of Alpaca

Sebastian Theiler
Jan 17 · 9 min read
Adapted from: [1], [2], [3], [4]

The Alpaca Trade API allows you to buy and sell shares in real time, have access to unlimited paper trading, see how your algorithms are performing, all from your Python program. With zero commissions!

In its simplest form, buying a stock looks like:

Buying 5 shares of Apple (AAPL) with the Alpaca API

But that’s skipping a few steps — let’s see how we get there.

To make this article as accessible as possible, and since I’m not an economist, let’s define a few terms:

  • Share: A single unit issued by a company as a representation of ownership.
  • Stock: A collection of shares.
  • Paper Trading: A paper trade is simulated trading which allows investors to practice buying and selling securities without risking real money.
  • Live Trading: Trading with real money, allowing for true profits and losses.
  • Algo(rithm): A set of rules regarding when to buy, sell or hold shares.
  • Symbol: The identifier used for a stock, e.g., AAPL or MSFT. Symbols are subject to change over time.

If you ever have questions about trading terminology, I would recommend investopedia.com for more definitions.

The simple algo and trading CLI we will develop in this article is available on my GitHub here: https://github.com/EvolvedSquid/tutorials/tree/master/adversarial-attacks-defenses


Getting Started

The first thing you must do to have access to all of Alpaca’s features is, of course, sign up. After supplying your email address and setting a password, Alpaca will send you a verification code, and after entering that code, you’re nearly finished.

If all you’re interested in is Paper Trading, you can stop here. However, if you would like to create a live account, you must supply your financial information. Unfortunately, live trading on Alpaca is currently only available for U.S. citizens, permanent residents and eligible Visa holders. I have more information and possible solutions for this at the end.

After you make your account, you should see a screen like:

If you wish to go to your paper trading account, click the link in top left, titled “Go to Paper Account”

Then, you should see an interface like the following:

If you provide your financial information, your live trading interface should look extremely similar.

Finally, to install the Alpaca Trade API via pip so you can use it in Python, run the following in a terminal:

pip install alpaca-trade-api

The Basics of The API

To get familiar with the basics of using the Alpaca Trade API, let’s buy and sell our first paper stocks using Alpaca.

To initialize the API, you first need to get your API keys.

To do so, click on the “View” button on the right side of the screen:

After that, you should see something that looks like:

Click on “Generate New Key” and you’ll see your API Key ID and Secret Key in the following format:

By the time you see this, these keys will be invalid

Now, in a Python file, you can initialize the API with:

And finally, we can run the example from the beginning, and buy five shares of Apple: (this will only work when the market is opened, even for Paper Trading)

NOTE: For testing purposes, such as this example, use the Paper Trading API. Do not risk real money while testing.

Now, in your Alpaca dashboard, you can see your purchase:

We can also check our list of positions with:

Which in this case should print something like:

[Position({'asset_class': 'us_equity',
'asset_id': 'b0b6dd9d-8b9b-48a9-ba46-b9d54906e415',
'avg_entry_price': '311.98',
'change_today': '0.00544581574453',
'cost_basis': '1559.9',
'current_price': '312.02',
'exchange': 'NASDAQ',
'lastday_price': '310.33',
'market_value': '1560.1',
'qty': '5',
'side': 'long',
'symbol': 'AAPL',
'unrealized_intraday_pl': '0.2',
'unrealized_intraday_plpc': '0.0001282133470094',
'unrealized_pl': '0.2',
'unrealized_plpc': '0.0001282133470094'})]

If we want to sell these five shares, all we have to do is swap side=’buy’ to side=’sell’

And checking back on our Alpaca dashboard, we can see that our sell was successful.

We can verify that this transaction was successful, by using the list_positions command again:

Which now prints an empty list:

[]

Building a Simple Trading Command-Line-Interface (CLI)

To demonstrate the basics of the Alpaca Trading API, let’s build a simple CLI to manually buy and sell shares.

First, we initialize the API:

Then, we have to make sure the market is actually open. We can do that with the following:

Assuming that the market is open, we can enter a while True loop for trading.

Inside the try statement, we can first display some basic information about the user’s account:

After that we can query the user on whether they want to buy or sell a stock:

Then we can get a bit more information about the share the user would like to buy:

And finally, we can submit the order:

Putting that all together, with a bit of fancy printing, we end up with:

Which will build a simple CLI like the following:

==================================
Interactive paper-stock trading
==================================
---
Your cash: 100000
Your buying power: 400000
[B]uy or [s]ell? b
Ticker of the stock you would like to buy/sell: AAPL
Quantity of the stock you would like to buy/sell: 10
Order Submitted

Getting Stock and Share Information

Alpaca has the capability to gather basic stock information. You can use it as follows:

If you have a live account, Alpaca also offers market data from Polygon. However, this article will be written assuming you only have access to the basic Alpaca API.

The api.get_barset function gets a Barset with limit Bar objects for each given symbol. Each bar contains information about the open, close, high, etc., about the time-span it covers. It gets these bars in a frequency dependent on timeframe.

timeframe can be any of the following:

minute/1Min, 5Min, 15Min, or day/1D

Each bar the get_barset function returns looks like:

Bar({'c': 315.98, 'h': 316.03, 'l': 315.89, 'o': 315.91, 't': 1578948600, 'v': 4041})

All the data in each Bar is within the time set by timeframe — if you set timeframe=’minute’, the high will be the minute’s high, not the day’s.

The Barset object that get_barset returns is pretty annoying to work with. Let’s turn it into a Pandas DataFrame.

The function assumes that `api` has already been initialized properly

All this function does is take the output of api.get_barset and turn it into a Pandas DataFrame. You may also like to make time your index, if it suits your purpose.

Calling this function with:

print(get_pandas_barset('AAPL', 'day', 10)['AAPL'])

Should print something like:

The basic Alpaca API cannot provide information at a higher rate than a minute, which means we do not have real time data.

Since I have not been able to find a simple Python package for real time stock prices, I have decided to write my own function using BeautifulSoup4 and marketwatch.com as a backend:

Five things about this function:

  1. At the time of writing marketwatch.com/robots.txt does not disallow web scraping https://www.marketwatch.com/investing/stock/*. With this said, I cannot guarantee this for the future, so please check their robots.txt before continuing. I am not responsible for any actions you may take.
  2. If marketwatch.com is ever down or changed, this function may no longer work.
  3. This function also relies on BeautifulSoup4 (bs4) to work. You may install bs4 with: pip install beautifulsoup4
  4. If you have a very slow internet connection, the expected latency of the Alpaca API (~30 seconds) may be shorter than the time it takes to get information from marketwatch.com
  5. Please do not spam marketwatch.com with requests. Try to limit yourself to a few requests a minute.

With the function in place, we can now get the live price of any stock:

print(get_live_price('aapl')) # something like: 316.96

A Simple Trading Algorithm

With the basics of Alpaca in place, let’s build a simple trading algorithm we could run once each morning to tell us what stocks to buy for the day.

The algorithm we will implement is based on the theory of stock momentum. Simply put, the momentum theory states that if a stock’s price has been increasing, it will continue to increase.

For our implementation, we will calculate the percentage increase of each stock in a list of stocks over the past d days, sort them in decreasing order, and choose the top n stocks.

If we choose, we may also want to sell every stock before the market closes.

First, let’s initialize the API, and define the helper functions we created earlier. You can set stocks equal to any list of symbols you would like.

Next, we will want to sell all the positions we currently own (if any):

Now, we can calculate the percent increase of each stock we are watching in the past d days:

Printing out percent_increases should return something like:

[('TSLA', 1.4220472866471514), ('AMD', 0.515133187088687), ('AAPL', 0.4865144739938809), ('NVDA', 0.44640149305960564), ('BABA', 0.32229914480190835), ('ZG', 0.3150841174793271), ('INTC', 0.2683917878528659), ('CRM', 0.23127749591248503), ('ATVI', 0.2216788916055421), ('FB', 0.21253570643814546), ('GOOG', 0.20723524615656164), ('MSFT', 0.18378456848370472), ('EA', 0.15916296766011406), ('YELP', 0.10860967447520542), ('TIVO', 0.10052219321148814), ('TTD', 0.08667693492491324), ('PYPL', 0.050937844795880816), ('MTCH', 0.04108205068857784), ('AMZN', 0.03659692392961067)]

Now it’s time to divvy our budget accordingly to each share. To do this choose the top n stocks that have increased the most in the past d days, then follow this equation:

Where:

  • S is the number of shares to buy
  • B is the total budget
  • i is the percent increase of a given stock
  • Σi is the sum of percent increases for all considered stocks
  • p is current price of a given stock

We can implement this as follows:

Note, this will return float values. Since Alpaca does not allow us to buy fractional shares, we will have to take the math.floor of them later. This will leave us with left over money.


Finally we can send requests to Alpaca to buy the shares: (this could have been done in the previous function, which is more efficient, but we will do this for the sake of explanation)

And now we’re technically finished!

If you would like to sell all shares for the night, (which you don’t really have to do in this case, since we are only trading each stock once per day; a long-term strategy), you can do this manually with:

Or, if you are willing to leave your program running all day, you could include a timer such as the following:

For this kind of trading algo, I don’t think leaving it running all day to sell shares at the end is worth it. You don’t even really have to sell the shares until next morning, when you buy new shares.

And to recap everything, here is the full stock trading program we just built:

Conclusion

Congratulations! With that, we’ve gone from (presumably) knowing very little about the Alpaca API, to implementing our first trading strategy.

I can’t guarantee the success of this strategy (or anything about the market), but it serves as a starting point for more advanced algorithms you can build. For some examples you can check out the examples folder of the Alpaca GitHub.

As a final warning, be careful with your money. Many people have gotten rich from the stock market (like the billionaire mathematician Jim Simons, interviewed on Numberphile), while others have lost everything they’ve put in. Don’t trust financial advice and algorithms from some random guy on the internet, understand what you’re doing and why you’re doing it.

As live-trading through Alpaca is currently only available for U.S. citizens, visa holders, etc., many of you may not be able to use this feature.

Two things:

  • If you are using a trading strategy that you only update positions for once per day (like the one we implement above), it isn’t hard to buy/sell shares manually through some application that you can use in your country.
  • The only part of the algorithm we implement above that relies on an Alpaca account with live-trading is selling all shares in the beginning, and buying shares at the end. If you have a working substitute, you can easily swap out the buying and selling parts. (Also, if you know a substitute that works outside of the U.S., consider leaving a reply so that others can find it too)

Alpaca is working hard to make live trading accounts available to everyone.


Anyway, until next time,

Happy coding!

If you have any questions, feel free to leave them in a reply below, and I’ll get back to you as soon as possible!


The code we’ve developed in this article is available on my GitHub here: https://github.com/EvolvedSquid/tutorials/tree/master/adversarial-attacks-defenses

Sorry for the slight delay, I’m working on a relatively big article about reinforcement-learning that should be out this month. Stay tuned if that interests you!

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Sebastian Theiler

Written by

I write articles about data science, artificial intelligence, and machine learning

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade