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:
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.
- How would you implement the authentication with more appropriate WL functions?
- 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"]
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"]
ImportString[data, ”JSON”]
. $\endgroup$RawJSON
which will return the data in the form of nested associations, which may be easier to work with. $\endgroup$