#AlpacaforR

  • What is Alpaca and AlpacaforR
  • Some Example Functions
  • Implementing the Earnings Strategy
  • Some Bonus Example Functions - Live Account Users
  • Learn more about Alpaca and AlpacaforR Github


After writing my recent post Scaling a Simple Earnings Strategy to the NASDAQ Exchange, I started to research how I could implement that earnings strategy into a live brokerage account directly from R. Most of us have heard of Quantopian or other backtesting services, but things can get complicated quickly once you search for a way to implement a live strategy using R. I wanted to find an easy-to-use package or brokerage account that could allow me to implement live trades using only R. From my experience, R is a great tool to use for backtesting with packages like quantstrat offering a fast and powerful backtesting platform, but fails for live trade implementation. I think this might be due to a low number of exchanges that offer real-time and easy-to-use free API connection. I almost came to the conclusion that I would need to use other languages other than R to find a easy way to implement my earnings strategy until I found an online brokerage called Alpaca. Alpaca offers commission free trades through their free-to-use real-time API. Using a few R functions from the httr and jsonlite packages, I was able to create a package / SDK to fully interact with Alpacas API, called AlpacaforR.

AlpacaforR allows you to interact with everything Alpaca offers to its users, including access to some of Polygons API if you have a live brokerage account. I want to focus on how to use AlpacaforR, by using it to implement the earnings strategy from my last post. If you want to learn more about Alpaca and information on their Web API, then you should visit here. You can also go to visit their how-to-code-examples page for examples using JavaScript or Python. Since they currently do not offer any SDK’s for R, and since AlpacaforR is new and in its early development stage, you will not find any documentation on how to use it other than here and the AlpacaforR Github.


Downloading and Setting Up AlpacaforR

I will start off by of course downloading the package. To do this, I will need to have the ‘devtools’ package installed. I have it installed but I want to cover all of the steps here.

install.packages("devtools")
library(devtools)

Great, now we are able to download packages right off of github. We can do that easily by running the below.

install_github("jagg19/AlpacaforR")
library(AlpacaforR)

The next thing to do is very important and MUST not be skipped. This is when I set my Alpaca API Key ID and Secret Key in the R environment. This is the heart to the API connection as you cannot use any endpoints if your not properly authorized. It must match the proper header name when being sent in the HTTP request so we have to make sure we name and store these properly before moving forward. We can make sure this is permanent each time we open a R session by storing it in a .Renviron file, or we can set it manually each time we start a new R session by using the ‘Sys.setenv’ function. The below are examples of setting it manually, but I recommend storing these in your .Renviron file so these do not need to be loaded in every time we open a new R session.


Setting API & Secret Keys to Environment

Sys.setenv('APCA-API-KEY-ID' = VALUE)
Sys.setenv('APCA-API-SECRET-KEY' = VALUE)

These have to be the names of your keys. Please do not forget to set these, or you will not be able to use connect with Alpaca’s API properly. You can make sure that these have been set properly by calling Sys.getenv(‘APCA-API-KEY-ID’) and Sys.getenv(‘APCA-API-KEY-ID’) which the output should match your keys.


What About my URL?

One last thing that is required when interacting with Alpacas API is your URL. These will differ according to account type, but AlpacaforR will find the URL for you as long as you specify when your using a live account by setting ‘live = TRUE’ for functions such as ‘submit_order’. This also acts as a “confirmation” before sending orders to your live account. Not all functions require this since some functions use the same URL regardless of the account type. The functions that don’t require the live argument are get_assets, get_calendar , get_clock, and get_bars since the same URL is used for each account type.


Using AlpacaforR

Now for the fun stuff. I am using a Paper account for the examples below, but by setting live = TRUE we can use a live brokerage account as well. The first thing I will want to do is to get my account to ensure that I have connected correctly. We can see account details such as account id, portfolio value, buying power, cash, cash withdrawable, and etc. Below I will call get_account() to see these details.


Getting Your Account

#If paper account: 
get_account()

#If live account:
get_account(live = TRUE)

Awesome, it looks like I have connected my correct account (for this example I will connect to my paper account) and I can see the status of my account as ACTIVE. I could look at some of the account details like available funds for trading, but I am ready to begin! Although, I cant remember if had any open positions at the moment so I want to check if that is the case.


Getting Current Positions

#If paper account:
get_positions()

#If live account:
get_positions(live = TRUE)

Since I do not have any open positions, I’ll receive a message that states “No positions are open at this time” but lets change that. First, I want to bring up the price of SPY to see how the day finished for the overall market and I want to check out the prices for the last month on my favorite stock, GE (lol JK). We can easily so that by using the ‘get_bars’ function and setting the appropriate arguments like below.


Getting Price Bars

#Todays date
today = Sys.Date()
get_bars(ticker = "SPY", from = today)

#Getting the last month of daily prices for GE
get_bars(ticker = "GE", timeframe = "day", from = Sys.Date()-30, to = today)

It looks like the overall market ended slightly up on Friday while GE finished 1.3% lower. I decide I want to submit a limit order for GE at a price a little lower than we are currently at just by a little because I think this might be a good time to buy in. I also plan on trading alot this week, so I want to see what the market calendar looks like. We can do these two things by using ‘get_calendar’ and ‘submit_order’.


Checking Market Calendar

#Getting specific dates using date ranges
get_calendar(from = "2019-04-15", to = "2019-04-20")

Hmm, anything off? I entered the dates for Monday - Friday but only four days were returned. Thankfully we checked the market calendar because it shows that the market will not be open on Friday 4/19/2019.


Submitting Orders to Alpaca

#A limit order - Paper
#submit_order(ticker = "GE", qty = "5", side = "buy", type = "limit", limit_price = "9")


#A limit order - Live
submit_order(ticker = "GE", qty = "5", side = "buy", type = "limit", limit_price = "9", live = TRUE)

After submitting a order to our live account..


Perfect, the order went through just as planned!! I just submitted an order to my Live Alpaca brokerage account from R! Also, the market is open all next week so I can look forward to a week full of excitement! Now I think its time to implement the earnings strategy from my previous post.

Implementing the Earnings Strategy

As a reminder, the earnings strategy from my previous post was pretty simple to illustrate how a “simple” go-to strategy for someone new to investing would perform against the same strategy but against the entire NASDAQ exchange. This time we will do it against the NASDAQ and the NYSE, but first filter out every company that does not have a market capitalization above $5 Billion. The strategy buys the company at the open one day prior to the report date, and sells it the same day of reporting if the company reports before market open. If the company reports after market close, then the strategy will sell it one day after the report date at the open. This is ran once a day before the market opens to get the pipeline filled with orders which will all trigger at the open.

This is what it looks like on my end when it runs each day, using the AlpacaforR functions of ‘get_account’, ‘get_bars’, ‘get_positions’, ‘get_calendar’, and ‘submit_order’ to assist and execute with various functions in bringing my strategy script to Alpacas platform. I will run the R Script that contains the strategy in my terminal.

Ran on Friday 4/12/2019 Before Market Open


As we can see, alot of stuff is happening as far as the order flow being sent to Alpaca in R (sorry for the emoji’s inside script lol). If all worked correctly, then you should see a bunch of orders in your pipeline, waiting to trigger at the next market open.



As we see, this was a success! This script was ran last Friday 04/12/2019 before market open. This means that all of the stocks it purchased Friday, should have reported earnings this morning. When we run our script again, the strategy should submit orders to sell those positions and open any new positions for companies that report the following day. Let’s see the result of the output below.


Ran on Monday 4/15/2019 Before Market Open


Nice!! Our algo is doing its job while AlpacaforR is working hard behind to scenes to make it possible to effortlessly submit these orders live in R.


Polygon API support - Alpaca Live Brokerage Accounts Only

If you have a live account, you have access to a few additional functions by using Polygon’s API. One difference between using Polygon data is that it is using consolidated market data. Alpaca defines consolidated market data as;

“Aggregated reporting of all securities exchanges’ and alternative trading venues’ quote and trade data. It is the most relied upon type of market data, providing investors and traders globally with a unified view of U.S. stock market prices and volumes. It also underpins the National Best Bid and Offer (NBBO), which provides investors with a continuous view of the best available displayed buy and sell prices, and through Rule 611 ensures that investors receive the best available displayed prices on their trades, with a few exceptions”.

These functions will start with “get_poly” and “get_meta”. Get meta supplies endpoints such as “news”, “dividends”,“earnings”,“analysts” and “company” to supply other data aside from pricing. Below are examples of “get_poly_agg_quote” and “get_meta” using the news endpoint.


Get Poly Aggregate Price Data

#Getting default pricing data on GE (daily): 
get_poly_agg_quote(ticker = "GE",from = "2019-04-01", to = "2019-04-12")

#Getting minute pricing data on GE: 
get_poly_agg_quote("GE", from = "2019-04-11", to = "2019-04-12", timespan = "minute")


#Getting quarterly pricing data on GE: 
get_poly_agg_quote("GE", from = "2018-01-01", to = "2019-04-12", timespan = "quarter") 

#Getting yearly pricing data on GE: 
get_poly_agg_quote("GE", from = "2015-01-01", to = "2019-12-31", timespan = "year")


Daily timespan

Minute timespan

Quarterly timespan

Yearly timespan


Get Meta News Endpoint

#Getting the last 100 news articles for GE:
get_meta(ticker = "GE", endpoint = "news", perpage = "100")

Can we say possible news sentiment algo? The opportunities are endless with AlpacaforR :)


So much more with AlpacaforR!

We have only scratched the surface and its just getting started with AlpacaforR! I’ve connected to our account, checked my positions, checked the prices of individual assets, looked at recent news of that asset, and even submitted orders straight to our Alpaca account. Only a few of the available AlpacaforR functions were covered in this post, but there are many more cool things that you can do interacting with Alpaca’s API. The goal of this post was to hopefully encourage you to checkout Alpaca if your looking for a brokerage account to connect and implement your strategies with, and to also checkout AlpacaforR if you are an R user that is interested in either paper trading real-time quotes or live trading using R. As a reminder, this package / SDK is in its early development stages but can still execute all of its functions in paper or live trading accounts. Feedback as well as advice is very much appreciated from anyone who is interested. If you want to see the rest of AlpacaforR functions then visit AlpacaforR Github page and monitor for new updates!