Functions
Index
Stonks.APIClients.AlphavantageJSONClient
Stonks.APIClients.YahooClient
Stonks.Parsers.parse_content
Stonks.Stores.load
Stonks.Stores.save
Stonks.Stores.update
Stonks.get_balance_sheet
Stonks.get_cashflow_statement
Stonks.get_data
Stonks.get_earnings
Stonks.get_exchange_rate
Stonks.get_income_statement
Stonks.get_info
Stonks.get_price
Client setup
The library comes with methods for creating APIClient
instances with preconfigured data for these providers:
Stonks.APIClients.YahooClient
— FunctionYahooClient(api_key::String) -> APIClient
Utility function for creating a client for accessing yahoofinance API. Contains the following resources
:
- info =>
APIResource{AssetInfo}
- price =>
APIResource{AssetPrice}
- exchange =>
APIResource{ExchangeRate}
- income_statement =>
APIResource{IncomeStatement}
- balance_sheet =>
APIResource{BalanceSheet}
- cashflow_statement =>
APIResource{CashflowStatement}
- earnings =>
APIResource{Earnings}
Stonks.APIClients.AlphavantageJSONClient
— FunctionAlphavantageJSONClient(api_key::String) -> APIClient
Utility function for creating a client for accessing alphavantage API. Contains the following resources
:
- info =>
APIResource{AssetInfo}
- price =>
APIResource{AssetPrice}
- exchange =>
APIResource{ExchangeRate}
- income_statement =>
APIResource{IncomeStatement}
- balance_sheet =>
APIResource{BalanceSheet}
- cashflow_statement =>
APIResource{CashflowStatement}
- earnings =>
APIResource{Earnings}
You can omit the client
parameter in all functions IF you set an environment variables:
- Alphavantage:
ALPHAVANTAGE_TOKEN
=> will build anAPIClient
usingAlphavantageJSONClient
- Yahoo Finance:
YAHOOFINANCE_TOKEN
=> will build anAPIClient
usingYahooClient
Retrieving data
Stonks.get_price
— Functionget_price(
symbols, [client], [T<:AbstractStonksRecord];
[interval] = "1d", [from] = missing, [to] = missing, [kwargs...]
) -> Union{Vector{T}, Exception}
Retrieves historical time series price data from the configured API client.
Arguments
symbols
can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client::APIClient]
: can be ommited if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
: data type used for parsing. Change it only if you want to use your custom model. default =AssetPrice
Keywords
[interval]
: values = [1d, 1wk, 1mo]. Frequency lower than daily is not supported. default = 1d[from]
: a Date oject indicating lower date limit. default =missing
[to]
: a Date objject indicating upper date limit. default =missing
[kwargs...]
: use it to pass keyword arguments if you have url / query parameters that need to be resolved at runtime.
Examples
julia> today = Dates.today()
2022-02-18
julia> length(ENV["YAHOOFINANCE_TOKEN"]) # value will be used to create a client
40
julia> get_price("AAPL", from = today - Dates.Day(1))
1-element Vector{AbstractStonksRecord}
AssetPrice("AAPL", Date("2022-02-17"), 168.88, missing, missing, missing, missing, missing)
AssetPrice("AAPL", Date("2022-02-18"), 167.3, missing, missing, missing, missing, missing)
julia> from = today - Dates.Day(2)
2022-02-16
julia> prices = get_price(["AAPL", "MSFT"], from = from)
AssetPrice("MSFT", Date("2022-02-16"), 299.5, missing, missing, missing, missing, missing)
AssetPrice("MSFT", Date("2022-02-17"), 290.73, missing, missing, missing, missing, missing
AssetPrice("MSFT", Date("2022-02-18"), 287.93, missing, missing, missing, missing, missing
AssetPrice("AAPL", Date("2022-02-16"), 172.55, missing, missing, missing, missing, missing
AssetPrice("AAPL", Date("2022-02-17"), 168.88, missing, missing, missing, missing, missing
AssetPrice("AAPL", Date("2022-02-18"), 167.3, missing, missing, missing, missing, missing)
julia> prices = get_price([
("AAPL", Date("2022-02-17")),
("MSFT", Date("2022-02-18"))
])
3-element Vector{AbstractStonksRecord}:
AssetPrice("AAPL", Date("2022-02-17"), 168.88, missing, missing, missing, missing, missing)
AssetPrice("AAPL", Date("2022-02-18"), 167.3, missing, missing, missing, missing, missing)
AssetPrice("MSFT", Date("2022-02-18"), 287.93, missing, missing, missing, missing, missing)
julia> prices = get_price([
("AAPL", Date("2022-02-15"), Date("2022-02-16")),
("MSFT", Date("2022-02-14"), Date("2022-02-15"))
])
5-element Vector{AbstractStonksRecord}:
AssetPrice("MSFT", Date("2022-02-14"), 295.0, missing, missing, missing, missing, missing)
AssetPrice("MSFT", Date("2022-02-15"), 300.47, missing, missing, missing, missing, missing)
AssetPrice("AAPL", Date("2022-02-15"), 172.79, missing, missing, missing, missing, missing)
AssetPrice("AAPL", Date("2022-02-16"), 172.55, missing, missing, missing, missing, missing)
Stonks.get_info
— Functionget_info(symbols, [client], [T<:AbstractStonksRecord]) -> Union{Vector{T}, Exception}
Retrieves general information about symbols
.
Arguments
symbols::Union{String, Vector{String}}
[client]::APIClient
: can be ommited if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
: data type used for parsing. Change it only if you want to use your custom model. default =AssetInfo
Examples
julia> get_info(client, "AAPL")
1-element Vector{AssetInfo}:
AssetInfo("AAPL", "USD", "Apple Inc.", "EQUITY", "NMS", "United States",
"Consumer Electronics", "Technology", "America/New_York", 100000)
julia> length(ENV["YAHOOFINANCE_TOKEN"]) # value will be used to create a client
40
julia> get_info(["AAPL", "MSFT"])
2-element Vector{AssetInfo}:
AssetInfo("AAPL", "USD", "Apple Inc.", "EQUITY", "NMS", "United States",
"Consumer Electronics", "Technology", "America/New_York", 100000)
AssetInfo("MSFT", "USD", "Microsoft Corporation", "EQUITY", "NMS", "United States",
"Software—Infrastructure", "Technology", "America/New_York", 181000)
Stonks.get_exchange_rate
— Functionget_exchange_rate(
symbols, [client], [T<:AbstractStonksRecord];
[from] = missing, [to] = missing
) -> Union{Vector{T}, Exception}
Retrieves historical exchange rate information
Arguments
symbols
can be:String
formated as base/quote, each having exactly 3 characters, e.g.: 'EUR/USD', 'USD/CAD'Vector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client]::APIClient
can be omitted if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
is the data type used for parsing. Change it only if you want to use your custom model. default =ExchangeRate
Keywords
[from]
: a Date object. default =missing
[to]
: a Date object. default =missing
Examples
julia> get_exchange_rate("EUR/USD", from=ref_date-Day(1), to=ref_date)
3-element Vector{ExchangeRate}:
ExchangeRate("EUR", "USD", Date("2022-02-18"), 1.13203)
ExchangeRate("EUR", "USD", Date("2022-02-17"), 1.13592)
julia> get_exchange_rate(["EUR/USD", "USD/CAD"], from=ref_date-Day(1), to=ref_date)
# 4-element Vector{ExchangeRate}:
ExchangeRate("EUR", "USD", Date("2022-02-18"), 1.13203)
ExchangeRate("EUR", "USD", Date("2022-02-17"), 1.13592)
ExchangeRate("USD", "CAD", Date("2022-02-18"), 1.2748)
ExchangeRate("USD", "CAD", Date("2022-02-17"), 1.2707)
# Also works with []Tuple{String, Date} or []Tuple{String, Date, Date}
julia>get_exchange_rate([
("EUR/USD", Date("2022-02-15"), Date("2022-02-16")),
("USD/CAD", Date("2022-02-14"), Date("2022-02-15")),
])
4-element Vector{ExchangeRate}:
...
Stonks.get_balance_sheet
— Functionget_balance_sheet(
symbols, [client], [T<:AbstractStonksRecord];
[frequency] = missing, [from] = missing, [to] = missing, [kwargs...]
) -> Union{Vector{T}, Exception}
Retrieves main information from balance sheet statement.
Arguments
symbols
can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client::APIClient]
: can be ommited if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
: data type used for parsing. Change it only if you want to use your custom model. default =BalanceSheet
Keywords
[frequency]
: values = [yearly, quarterly]. default =missing
, which will include both yearly and quarterly frequencies.[from]
: a Date oject indicating lower date limit. default =missing
[to]
: a Date objject indicating upper date limit. default =missing
[kwargs...]
: use it to pass keyword arguments if you have url / query parameters that need to be resolved at runtime.
Examples
get_balance_sheet("AAPL")
get_balance_sheet(["AAPL", "IBM"])
get_balance_sheet(["AAPL", "IBM"]; frequency="yearly")
get_balance_sheet([
("AAPL", Date("2020-01-01"), Date("2020-12-31")),
("MSFT", Date("2020-01-01"), Date("2020-12-31")),
]; frequency="quarterly")
Stonks.get_income_statement
— Functionget_income_statement(
symbols, [client], [T<:AbstractStonksRecord];
[frequency] = missing, [from] = missing, [to] = missing, [kwargs...]
) -> Union{Vector{T}, Exception}
Retrieves main information of income (profit and loss) statement.
Arguments
symbols
can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client::APIClient]
: can be ommited if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
: data type used for parsing. Change it only if you want to use your custom model. default =IncomeStatement
Keywords
[frequency]
: values = [yearly, quarterly]. default =missing
, which will include both yearly and quarterly frequencies.[from]
: a Date oject indicating lower date limit. default =missing
[to]
: a Date objject indicating upper date limit. default =missing
[kwargs...]
: use it to pass keyword arguments if you have url / query parameters that need to be resolved at runtime.
Examples
get_income_statement("AAPL")
get_income_statement(["AAPL", "IBM"])
get_income_statement(["AAPL", "IBM"]; frequency="yearly")
get_income_statement([
("AAPL", Date("2020-01-01"), Date("2020-12-31")),
("MSFT", Date("2020-01-01"), Date("2020-12-31")),
]; frequency="quarterly")
Stonks.get_cashflow_statement
— Functionget_cashflow_statement(
symbols, [client], [T<:AbstractStonksRecord];
[frequency] = missing, [from] = missing, [to] = missing, [kwargs...]
) -> Union{Vector{T}, Exception}
Retrieves main information from cash flow statement.
Arguments
symbols
can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client::APIClient]
: can be ommited if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
: data type used for parsing. Change it only if you want to use your custom model. default =CashflowStatement
Keywords
[frequency]
: values = [yearly, quarterly]. default =missing
, which will include both yearly and quarterly frequencies.[from]
: a Date oject indicating lower date limit. default =missing
[to]
: a Date objject indicating upper date limit. default =missing
[kwargs...]
: use it to pass keyword arguments if you have url / query parameters that need to be resolved at runtime.
Examples
get_cashflow_statement("AAPL")
get_cashflow_statement(["AAPL", "IBM"])
get_cashflow_statement(["AAPL", "IBM"]; frequency="yearly")
get_cashflow_statement([
("AAPL", Date("2020-01-01"), Date("2020-12-31")),
("MSFT", Date("2020-01-01"), Date("2020-12-31")),
]; frequency="quarterly")
Stonks.get_earnings
— Functionget_earnings(
symbols, [client], [T<:AbstractStonksRecord];
[frequency] = missing, [from] = missing, [to] = missing, [kwargs...]
) -> Union{Vector{T}, Exception}
Retrieves historical informaton about earnings per share announcements.
Arguments
symbols
can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client::APIClient]
: can be ommited if one of the correct environmental variable is set (YAHOOFINANCE_TOKEN
orALPHAVANTAGE_TOKEN
)[T<:AbstractStonksRecord]
: data type used for parsing. Change it only if you want to use your custom model. default =Earnings
Keywords
[frequency]
: values = [yearly, quarterly]. default =missing
, which will include both yearly and quarterly frequencies.[from]
: a Date oject indicating lower date limit. default =missing
[to]
: a Date objject indicating upper date limit. default =missing
[kwargs...]
: use it to pass keyword arguments if you have url / query parameters that need to be resolved at runtime.
Examples
get_earnings("AAPL")
get_earnings(["AAPL", "IBM"])
get_earnings(["AAPL", "IBM"]; frequency="yearly")
get_earnings([
("AAPL", Date("2020-01-01"), Date("2020-12-31")),
("MSFT", Date("2020-01-01"), Date("2020-12-31")),
]; frequency="quarterly")
Stonks.get_data
— Functionget_data(resource, symbols; kwargs...) -> Union{Vector{<:AbstractStonksRecord}, Exception}
Generic function to get data of type resource{T}. Functions such as getprice, getinfo, call this.
Arguments
resource::APIResource
: instance of anAPIResource
.symbols::Symbol
can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)Vector{UpdatableSymbol}
: type Stonks.UpdatableSymbol(symbol; [from], [to])
Keywords
[interval]
: values = 1d, 1wk, 1mo. Frequency lower than daily is not supported. default = 1d[from]
: a Date oject indicating lower date limit. default =missing
[to]
: a Date objject indicating upper date limit. default =missing
[kwargs...]
: use it to pass keyword arguments if you have url / query parameters that need to be resolved at runtime.
Tables.jl conversion
Missing docstring for to_table
. Check Documenter's build log for details.
Persisting data
Stonks.Stores.load
— Functionload(ds, [partitions]) -> Union{Vector{<:AbstractStonksRecord}, Exception}
Read data from an FileStore
instance into a Vector{:<AbstractStonksRecord}. If there is no data at ds.path
, a file with 0 records and the correct types with be created.
Arguments
ds::FileStore{<:AbstractStonksRecord}
: aFileStore
instance[partitions]::Dict{String, Vector{String}}
: a dict of column => values, used for partition pruning. default =missing
Examples
dest = joinpath(@__DIR__, "data/prices")
ds = FileStore{AssetPrice}(; path=dest, ids=[:symbol], partitions=[:symbol], time_column="date")
data = load(ds)
2-element Vector{AssetPrice}:
AssetPrice("AAPL", Date("2022-03-01"), 163.2, 164.695, 166.6, 161.97, missing, 83474425)
AssetPrice("AAPL", Date("2022-02-28"), 165.12, 163.06, 165.42, 162.43, missing, 95056629)
Stonks.Stores.save
— Functionsave(ds, data) -> Union{Nothing, Exception}
Writes data using the information provided in the FileStore (path, format, partitions, writer) In case of a FileStore
with partitions, the partition values where data
has records will be overwritten.
Arguments
ds::FileStore
data::Vector{<:AbstractStonksRecord}
Examples
julia> dest = joinpath(@__DIR__, "data/prices")
julia> ds = FileStore{AssetPrice}(; path=dest, ids=["symbol"], partitions=["symbol"], time_column="date")
julia> data
2-element Vector{AssetPrice}:
AssetPrice("MSFT", Date("2022-03-04"), 289.86, missing, missing, missing, missing, missing)
AssetPrice("TSLA", Date("2022-03-04"), 838.29, missing, missing, missing, missing, missing)
julia> save(ds, data)
julia> readdir(ds.path)
2-element Vector{String}:
"symbol=MSFT"
"symbol=TSLA"
Stonks.Stores.update
— Functionupdate(ds, [symbols], [client]; [to], [force]) -> Union{Nothing, FileStore}
Updates or inserts data in the datastore. If symbols
are not provided, the updates will be inferred based on ds.ids
and ds.time_column
. If symbols
are provided, only the symbols will be updated.
Arguments
ds::FileStore{<:AbstractStonksRecord}
[symbols::Symbol]
. Default = missing. Can be:String
with one symbol / tickerVector{String}
with multiple symbolsVector{Tuple{String, Date}}
: tuples of form (symbol, from)Vector{Tuple{String, Date, Date}}
, tuples of form (symbol, from, to)
[client::APIClient]
: can be omitted if the one of the client can be built from ENV vars
Keywords
[to::Date]
: default = most recent working day. upper date limit.[force::Bool]
: default =false
. Indicates how to handle the case whenismissing(ds.time_column) && ismissing(symbols)
:false
=> does nothingtrue
=> makes requests for allds.ids
from the min until maxds.time_column
and rewrites all data
Examples
julia> Dates.today()
Date("2022-02-04")
julia> @chain load(ds) Stonks.groupby(prices, [:symbol]) Stonks.aggregate(_, [:date => maximum => :date_max])
2-element Vector{NamedTuple{(:symbol, :date_max), Tuple{String, Date}}}:
(symbol = "AAPL", date_max = Date("2022-03-02"))
(symbol = "MSFT", date_max = Date("2022-03-02"))
julia> update(ds)
julia> @chain load(ds) Stonks.groupby(prices, [:symbol]) Stonks.aggregate(_, [:date => maximum => :date_max])
2-element Vector{NamedTuple{(:symbol, :date_max), Tuple{String, Date}}}:
(symbol = "AAPL", date_max = Date("2022-03-04"))
(symbol = "MSFT", date_max = Date("2022-03-04"))
julia> update(ds, ["IBM", "AMD"])
julia> @chain load(ds) Stonks.groupby(prices, [:symbol]) Stonks.aggregate(_, [:date => maximum => :date_max])
4-element Vector{NamedTuple{(:symbol, :date_max), Tuple{String, Date}}}:
(symbol = "AAPL", date_max = Date("2022-03-04"))
(symbol = "MSFT", date_max = Date("2022-03-04"))
(symbol = "IBM", date_max = Date("2022-03-04"))
(symbol = "AMD", date_max = Date("2022-03-04"))
Content parsers
Stonks.Parsers.parse_content
— Functionparse_content(p::AbstractContentParser, c::AbstractString; kwargs...) -> Vector{T<:AbstractStonksRecord}
Interface for parsing raw data into a data model. All main functions responsible for getting data from APIs will call parse_content
with a concrete subtype of AbstractContentParser
.
Example - Create a custom type and parser
using Dates, JSON3, Stonks
# Assume we have the following raw data
julia> content
{
"name": "Inflation - US Consumer Prices",
"interval": "annual",
"unit": "percent",
"data": [
{"date": "2020-01-01", "value": "1.2335"},
{"date": "2019-01-01", "value": "1.8122"}
]
}
# Create your custom type
struct MacroIndicator <: AbstractStonksRecord
name::String
date::Date
value::Number
end
# Define a function with the same signature as parse_content.
function parse_inflation_data(content::AbstractString; kwargs...)
js = JSON3.read(content)
return map(x ->
MacroIndicator("Inflation", tryparse(Date, x[:date]), tryparse(Float64, x[:value])),
js["data"])
end
# Wrap it around a concrete subtype of AbstractContentParser
my_parser = Stonks.Parsers.JSONParser(parse_inflation_data)
julia> parse_content(my_parser, content)
2-element Vector{MacroIndicator}:
MacroIndicator("Inflation", Date("2020-01-01"), 1.2335)
MacroIndicator("Inflation", Date("2019-01-01"), 1.8122)