1
$\begingroup$

The following function successfully imports historical stock market data from Alpaca's Market Data API.

data=URLFetch["https://data.alpaca.markets/v2/stocks/bars?symbols=NNE&
timeframe=1Min&start=2024-07-01&end=2024-07-01&limit=1000&adjustment=
raw&feed=sip&sort=asc","Headers" -> {"APCA-API-KEY-ID" -> apiKey,
"APCA-API-SECRET-KEY" -> secretKey}]

The variables apiKey and secretKey were obtained on the Alpaca dashboard and were defined in my notebook as strings. The authentication as a list of rules seems intuitive. This function returns a string that looks like:

enter image description here

In order to work with the bar data that this string represents, I'd need to extract the information using StringCases or something like it and then convert things into a format that is nice to work with. ie. The price data are actually numbers. I saw in the documentation that URLFetch is being depricated in favor of URLRead. I have two questions here.

  1. How would you implement the authentication with more appropriate WL functions?
  2. Can you get the data directly so that bascktesting strategies would be a bit more streamlined?

Edit:

Using ImportString:

dat = ImportString[data, "JSON"]
ListLinePlot[dat[[1, 2, 1, 2, All, 1, 2]],
PlotLabel -> "NNE Stock Price 01Jul24"]

enter image description here

Edit:

A very big step towards a working model for backtesting strategies.

This gets the data directly as a JSON file:

data = URLExecute[HTTPRequest[url,<|"Method" -> "GET",
"Headers" -> {
  "APCA-API-KEY-ID" -> apiKey,
  "APCA-API-SECRET-KEY" -> secretKey
  },

"Query" -> {
  "symbols" -> "NNE",
  "timeframe" -> "1Min",
  "start" -> "2024-07-05",
  "end" -> "2024-07-05",
  "limit" -> "1000",
  "adjustment" -> "raw",
  "feed" -> "sip",
  "sort" -> "asc"}
|>]]`

This uses the Part function to isolate the bar data:

dat = data[[1, 2, 1, 2]]

This formats the data to generate a Trading chart:

formattedData = dat /. {c_, h_, l_, n_, o_, t_, v_, 
 vw_} :> {DateObject[t[[2]]], {o[[2]], h[[2]], l[[2]], c[[2]], 
  v[[2]]}};

Here is the trading chart with a simple moving average of period 34.

TradingChart[formattedData, {"Volume", FinancialIndicator["SimpleMovingAverage", 34]},
PlotLabel -> "Nano Nuclear - 05 July 2024"]

enter image description here

$\endgroup$
3
  • $\begingroup$ It looks like a JSON string. Try ImportString[data, ”JSON”]. $\endgroup$
    – C. E.
    Commented Jul 7 at 1:49
  • $\begingroup$ ImportString worked nicely. Thank you. $\endgroup$
    – JEM
    Commented Jul 7 at 2:47
  • $\begingroup$ You can also import it as RawJSON which will return the data in the form of nested associations, which may be easier to work with. $\endgroup$
    – C. E.
    Commented Jul 8 at 10:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.