Site icon R-bloggers

Authenticate with Alpaca API

[This article was first published on R - datawookie, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The {alpacar} package for R is a wrapper around the Alpaca API. API documentation can be found here. In this introductory post I show how to install and load the package, then authenticate with the API and retrieve account information.

Creating an Account

I’ve been using a paper trading account for testing purposes. To get this set up:

  1. Go to https://alpaca.markets/.
  2. Click the link to create an account.
  3. Fill in your details and submit.
  4. Verify your email.
  5. Login to your new account.
  6. Configure an authentication app (I’m using Google Authenticator).
  7. Click on the Home tab.
  8. Find the API Keys section and press the Generate New Keys link.
  9. Record the key and secret somewhere secure.

I have stored my key and secret in environment variables.

Now you’re all set up, we can move onto the package.

Install & Load

Install from GitHub (it’s not yet published on CRAN).

remotes::install_github("datawookie/alpacar")

Now load the package.

library(alpacar)

By default the package will select the paper trading API.

alpacar v0.0.8
Selecting paper trading API by default.

I also routinely load {dplyr} and tweak the number of significant figures in tibble output.

library(dplyr)

# Expand decimal places.
options(pillar.sigfig = 8)

Authenticate

I store my credentials in environment variables. Specifically I use a .env file in my project directory, which I load using the {dotenv} package.

library(dotenv)

load_dot_env()

Now authenticate with the API.

authenticate(
  key = Sys.getenv("ALPACA_KEY"),
  secret = Sys.getenv("ALPACA_SECRET_KEY")
)

Account Information

Since you have connected with the API you’re ready to retrieve your account information.

info <- account()

The result is a list with a bunch of fields:

names(info)

 [1] "id"                          "admin_configurations"       
 [3] "user_configurations"         "account_number"             
 [5] "status"                      "crypto_status"              
 [7] "options_approved_level"      "options_trading_level"      
 [9] "currency"                    "buying_power"               
[11] "regt_buying_power"           "daytrading_buying_power"    
[13] "effective_buying_power"      "non_marginable_buying_power"
[15] "options_buying_power"        "bod_dtbp"                   
[17] "cash"                        "accrued_fees"               
[19] "portfolio_value"             "pattern_day_trader"         
[21] "trading_blocked"             "transfers_blocked"          
[23] "account_blocked"             "created_at"                 
[25] "trade_suspended_by_user"     "multiplier"                 
[27] "shorting_enabled"            "equity"                     
[29] "last_equity"                 "long_market_value"          
[31] "short_market_value"          "position_market_value"      
[33] "initial_margin"              "maintenance_margin"         
[35] "last_maintenance_margin"     "sma"                        
[37] "daytrade_count"              "balance_asof"               
[39] "crypto_tier"                 "intraday_adjustments"       
[41] "pending_reg_taf_fees"

You can access those fields individually, but there’s also an S3 generic print() method that presents the information concisely. Here’s the account information for a pristine new paper trading account:

================================================================================
Alpaca Account: PA39TI9AF7CO (bf24d452-0bd5-3de5-98e8-e794046094ad)
Currency:       USD
Created:        2024-10-14 05:11:14
Status:         ACTIVE
================================================================================

Balances (2024-10-11) ----------------------------------------------------------
Equity:                    = 100000.00
Cash:                      = 100000.00
Buying power: Nominal      = 200000.00   Daytrading       =      0.00
              Regulation-T = 200000.00   Non-marginable   = 100000.00
              Effective    = 200000.00   Options          = 100000.00
Market value: Position     =      0.00   Long             =      0.00
                                         Short            =      0.00
Margin:       Initial      =      0.00   Maintenance      =      0.00
                                         Last maintenance =      0.00
--------------------------------------------------------------------------------

I’ll be publishing further posts as I add more functionality to the package. Ultimately the goal is to have a package that will enable fully automated trading on Alpaca from R.

To leave a comment for the author, please follow the link and comment on their blog: R - datawookie.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version