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.


  • 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 for more definitions.

The simple algo and trading CLI we will develop in this article is available on my GitHub here:

Getting Started

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

Initializing the API

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:

Buying Shares

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'})]

Selling Shares

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)

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

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.

Getting the Data into a Better Format

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:

Real, Real-Time Stock 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 as a backend:

Five things about this function:

  1. At the time of writing does not disallow web scraping*. 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 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
  5. Please do not spam 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

The Algorithm

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.


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:


  • 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:


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.

Unable to Trade with Alpaca?

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:

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…

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

More From Medium

More from Analytics Vidhya

More from Analytics Vidhya

More from Analytics Vidhya

The Illustrated Word2vec

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