API
SaguaroTrader.AlphaModelSaguaroTrader.AlwaysOpenExchangeSaguaroTrader.AssetSaguaroTrader.BacktestDataHandlerSaguaroTrader.BrokerSaguaroTrader.BuyAndHoldRebalanceSaguaroTrader.CSVDailyBarSourceSaguaroTrader.CashSaguaroTrader.DailyRebalanceSaguaroTrader.DataHandlerSaguaroTrader.DataSourceSaguaroTrader.DollarWeightedOrderSizerSaguaroTrader.DynamicUniverseSaguaroTrader.EqualWeightPortfolioOptimizerSaguaroTrader.EquitySaguaroTrader.ExchangeSaguaroTrader.FeeModelSaguaroTrader.FixedSignalsAlphaModelSaguaroTrader.FixedSlippageModelSaguaroTrader.FixedWeightPortfolioOptimizerSaguaroTrader.LongShortOrderSizerSaguaroTrader.MonthlyRebalanceSaguaroTrader.OrderSaguaroTrader.OrderSizerSaguaroTrader.PercentFeeModelSaguaroTrader.PercentSlippageModelSaguaroTrader.PortfolioSaguaroTrader.PortfolioConstructionModelSaguaroTrader.PortfolioEventSaguaroTrader.PortfolioOptimizerSaguaroTrader.PositionSaguaroTrader.PositionHandlerSaguaroTrader.RebalanceSaguaroTrader.RollingSignalsAlphaModelSaguaroTrader.SimulatedBrokerSaguaroTrader.SimulatedExchangeSaguaroTrader.SingleSignalAlphaModelSaguaroTrader.SlippageModelSaguaroTrader.StaticUniverseSaguaroTrader.TransactionSaguaroTrader.UniverseSaguaroTrader.VolumeSharesSlippageModelSaguaroTrader.ZeroFeeModelSaguaroTrader.ZeroSlippageModelSaguaroTrader.calculate_feeSaguaroTrader.cost_with_feeSaguaroTrader.cost_without_feeSaguaroTrader.create_asset_transactionSaguaroTrader.create_portfolio!SaguaroTrader.create_subscriptionSaguaroTrader.create_withdrawalSaguaroTrader.get_askSaguaroTrader.get_asset_latest_bid_ask_priceSaguaroTrader.get_asset_latest_mid_priceSaguaroTrader.get_assets_historical_bidsSaguaroTrader.get_assets_historical_range_close_priceSaguaroTrader.get_bidSaguaroTrader.position_from_transactionSaguaroTrader.subscribe_funds!SaguaroTrader.subscribe_funds_to_portfolio!SaguaroTrader.total_equitySaguaroTrader.total_market_valueSaguaroTrader.withdraw_funds!SaguaroTrader.withdraw_funds_from_portfolio!
Asset
SaguaroTrader.Asset — TypeMetadata about an Asset
SaguaroTrader.Cash — TypeEquity asset type.
Fields
currency::String- currency of the cash
SaguaroTrader.Equity — TypeEquity asset type.
Fields
symbol::Symbol- asset symbolname::String- name of the assettax_exempt::Bool=false- asset tax exemption status
SaguaroTrader.Universe — TypeAbstract type for asset universes
SaguaroTrader.DynamicUniverse — TypeDynamic asset universe. Each asset has a start date
Parameters
asset_dates::AbstractVector{Dict{Symbol,DateTime}}
SaguaroTrader.StaticUniverse — TypeStatic asset universe
Parameters
assets
Order
SaguaroTrader.Order — TypeThis is an Order for an asset.
Fields
created_dt::DateTime- datetime that the order was placedquantity::Real- order quantityasset::Asset- order assetfee::Float64- order feeorder_id::String- unique order iddirection::Int1=>buy, -1=>selldirection::Float64- Asset volume (for predicting slippage)
Portfolio Optimization
SaguaroTrader.PortfolioOptimizer — TypeAbstract type for portfolio optimization.
generate_weights(opt, initial_weights)SaguaroTrader.FixedWeightPortfolioOptimizer — TypePortfolio optimizer for fixed asset weights
Fields
data_handler::DataHandler
SaguaroTrader.EqualWeightPortfolioOptimizer — TypePortfolio optimizer for fixed asset weights
Fields
data_handler::DataHandlerscale::Float64
Exchange
SaguaroTrader.Exchange — TypeAbstract type for trading exchange
SaguaroTrader.SimulatedExchange — TypeSimulate live trading
Fields
start_dt::DateTimeopen_time::Time=Time(14,30)close_time::Time=Time(21,00)
SaguaroTrader.AlwaysOpenExchange — TypeSimulate an exchange that never closes
Fields
start_dt::DateTime
Fee Model
SaguaroTrader.FeeModel — TypeAbstract type to handle the calculation of brokerage fee, fees and taxes.
SaguaroTrader.ZeroFeeModel — TypeA FeeModel that produces no fee/fees/taxes.
total_fee = 0.0
SaguaroTrader.PercentFeeModel — TypeA Fee model that calculates tax and fee fees using a percentage of the total order price (considaration).
feefee = (order.price * order.quantity) * feemodel.feepct taxfee = (order.price * order.quantity) * feemodel.taxpct totalfee = taxfee + fee_fee
Fields
fee_pct::Float64= 0.0tax_pct::Float64= 0.0
SaguaroTrader.calculate_fee — Functioncalculate_fee(fee_model, quantity::Real, price::Float64)Calculate the fee for an order
Parameters
fee_modelquantity::Realprice::Float64
Returns
Float64: The total fee for the order (tax + fee)
Data Source
SaguaroTrader.DataSource — TypeAbstract type for a data source.
SaguaroTrader.CSVDailyBarSource — TypeEncapsulates loading, preparation and querying of CSV files of daily 'bar' OHLCV data. The CSV files are converted into a intraday timestamped Pandas DataFrame with opening and closing prices.
Optionally utilises adjusted closing prices (if available) to adjust both the close and open.
Fields
csv_dir::StringThe full path to the directory where the CSV is located.asset_type::StringThe asset type that the price/volume data is for.adjust_prices::StringWhether to utilise corporate-action adjusted prices for both the open and closing prices. Defaults to True.csv_symbols::VectorAn optional list of CSV symbols to restrict the data source to. The alternative is to convert all CSVs found within the provided directory.dict_asset_dfs::Dict{Symbol, DataFrame}Automatically generated dictionary of asset symbols, and pricing dataframes
SaguaroTrader.get_bid — Functionget_bid(ds::CSVDailyBarSource, dt::DateTime, asset::Symbol)Get the bid price for an asset at a certain time.
Parameters
ds::CSVDailyBarSourcedt::DateTimeasset::Symbol
Returns
Float64: bid for an asset at the given datetime
SaguaroTrader.get_ask — Functionget_ask(ds::CSVDailyBarSource, dt::DateTime, asset::Symbol)Get the ask price for an asset at a certain time.
Parameters
ds::CSVDailyBarSourcedt::DateTimeasset::Symbol
Returns
Float64: ask for an asset at the given datetime
SaguaroTrader.get_assets_historical_bids — Functionget_ask(ds::CSVDailyBarSource, dt::DateTime, asset::Symbol)Obtain a multi-asset historical range of closing prices as a DataFrame
Parameters
ds::CSVDailyBarSourcestart_dt::DateTimeend_dt::DateTimeasset::Symbol
Returns
DataFrame: Dataframe with the bid timestamps, asset symbols, and
Data Handler
SaguaroTrader.DataHandler — TypeAbstract type for a data handler.
SaguaroTrader.BacktestDataHandler — TypeData Handler for backtesting Fields –––
- `data_sources
SaguaroTrader.get_asset_latest_bid_ask_price — Functionget_asset_latest_bid_ask_price(dh::DataHandler, dt::DateTime, asset::Symbol)Get the bid, ask price for an asset at a certain time.
Parameters
dh::DataHandlerdt::DateTimeasset::Symbol
Returns
Tuple{Float64, Float64}: (bid, ask) for an asset at the given datetime
SaguaroTrader.get_asset_latest_mid_price — Functionget_asset_latest_mid_price(dh::DataHandler, dt::DateTime, asset::Symbol)Get the average of bid/ask price for an asset at a certain time.
Parameters
dh::DataHandlerdt::DateTimeasset::Symbol
Returns
Float64: mid point between bid/ask for an asset at the given datetime
SaguaroTrader.get_assets_historical_range_close_price — Functionget_assets_historical_range_close_price(
dh::DataHandler,
start_dt::DateTime,
end_dt::DateTime,
assets::AbstractVector{Symbol},
) All closing prices for the given assets in the given timerange
Parameters
dh::DataHandlerstart_dt::DateTimeend_dt::DateTimeasset::AbstractVector{Symbol}
Returns
DataFrame: dataframe of close prices for the assets
Transaction
SaguaroTrader.Transaction — TypeMetadata about a transaction of an asset
Fields
asset::Symbolquantity::Float64dt::DateTimeprice::Float64fee::Float64order_id::String
SaguaroTrader.cost_without_fee — Functioncost_without_fee(txn::Transaction)Cost of a transaction without fee
Parameters
txn::Transaction
Returns
Float64
SaguaroTrader.cost_with_fee — Functioncost_with_fee(txn::Transaction)Cost of a transaction with fee
Parameters
txn::Transaction
Returns
Float64
Position
SaguaroTrader.Position — TypeHandles the accounting of a position in an asset.
Fields
asset::Symbolcurrent_price::Float64current_dt::DateTimebuy_quantity::Float64sell_quantity::Float64net_quantity::Float64avg_bought::Float64avg_sold::Float64buy_fee::Float64sell_fee::Float64
SaguaroTrader.position_from_transaction — Functionposition_from_transaction(txn::Transaction)::PositionCreate a position using a transaction
Parameters
txn::Transaction
Returns
Position
SaguaroTrader.PositionHandler — TypeStore all open positions
Portfolio
SaguaroTrader.PortfolioEvent — TypeSnapshot of the portfolio at a given time.
Fields
dt::DateTimetype::Stringdebit::Float64credit::Float64balance::Float64
SaguaroTrader.create_subscription — Functioncreate_subscription(dt::DateTime, credit::Float64, balance::Float64)Create a subscription portolio event
Parameters
dt::DateTimecredit::Float64balance::Float64
Returns
PortfolioEvent
SaguaroTrader.create_withdrawal — Functioncreate_withdrawal(dt::DateTime, credit::Float64, balance::Float64)Create a withdrawal portolio event
Parameters
dt::DateTimecredit::Float64balance::Float64
Returns
PortfolioEvent
SaguaroTrader.create_asset_transaction — Functioncreate_asset_transaction(
dt::DateTime,
txn_total_cost::Float64,
balance::Float64,
direction::Int,
)Create an asset buy/sell portfolio event
Parameters
dt::DateTimetxn_total_cost::Float64balance::Float64direction::Int
Returns
PortfolioEvent
SaguaroTrader.Portfolio — TypePortfolio
Fields
current_dt::DateTimecash::Float64currency::Stringpos_handler::PositionHandlerportfolio_id::Stringname::Stringhistory::AbstractVector{PortfolioEvent}
SaguaroTrader.total_market_value — Functiontotal_market_value(pos_handler::PositionHandler)Total market value of all open positions
Parameters
pos_handler::PositionHandler
Returns
Float64
total_market_value(port::Portfolio)Total market value of the portfolio excluding cash.
Parameters
ord1ord2
Returns
Float64
SaguaroTrader.total_equity — Functiontotal_equity(port::Portfolio)Total market value of the portfolio including cash.
Parameters
ord1ord2
Returns
Float64
Alpha Model
SaguaroTrader.AlphaModel — TypeAbstract type for alpha models
SaguaroTrader.FixedSignalsAlphaModel — TypeA simple AlphaModel that provides a single scalar forecast value for each Asset in the Universe.
Fields
signal_weights::Dict{Symbol,Float64}
SaguaroTrader.RollingSignalsAlphaModel — TypeSignals that change through time. Produces the most recent signal at a given time
Fields
dict_signal_weights::Dict{DateTime, Dict{Asset,Float64}}
SaguaroTrader.SingleSignalAlphaModel — TypeFixed signal for all assets in the universe
Fields
universesignal::Float64
Slippage Model
SaguaroTrader.SlippageModel — Typeabstract type for slippage models
SaguaroTrader.ZeroSlippageModel — TypeA SlippageModel that produces no slippage.
Returns
Float64: The original price
SaguaroTrader.FixedSlippageModel — TypeFixed spread for all assets
Buy orders will execute at ask + spread / 2 Sell orders will execute at bid - spread / 2
Fields
spread::Float64
Returns
Float64: The price including slippage
SaguaroTrader.PercentSlippageModel — TypeSpread is a percent of the asset price
Buy orders will execute at ask * (1 + (slippage_pct/100)) Sell orders will execute at bid * (1 - (slippage_pct/100))
Fields
slippage_pct::Float64
Returns
Float64: The price including slippage
SaguaroTrader.VolumeSharesSlippageModel — TypeSlippage is based on the ratio of order volume to total volume
Buy orders will execute at ask + (volume_share^2 * price_impact * price * direction) Sell orders will execute at bid - (volume_share^2 * price_impact * price * direction)
Fields
price_impact::Float64=0.1- The scaling coefficient for price impact. Larger values will result in larger price impacts.
Returns
Float64: The price including slippage
Broker
SaguaroTrader.Broker — TypeAsset
SaguaroTrader.SimulatedBroker — TypeSimlated broker for transacting assets
Fields
start_dt::DateTimecurrent_dt::DateTimeexchangedata_handler::DataHandleraccount_id::Stringbase_currency::Stringinitial_cash::Float64fee_modelcash_balances::Dict{String,Float64}portfolios::Dict{String,Portfolio}open_orders::Dict{String,Queue{Order}}
SaguaroTrader.create_portfolio! — Functionfunction create_portfolio!(
broker,
initial_cash::Real;
name::String = "",
portfolio_id::String = string(UUIDs.uuid1()),
)function create_portfolio!(
broker;
name::String = "",
portfolio_id::String = string(UUIDs.uuid1()),
)Create a portolio using the broker's cash balance to fund the initial capital.
Parameters
brokerinitial_cash::Realname::String = ""portfolio_id::String = string(UUIDs.uuid1())
SaguaroTrader.subscribe_funds! — Functionsubscribe_funds!(broker, amount::Real)subscribe_funds!(broker, amount::Real, currency::String)Add funds to broker
Parameters
brokeramount::Realcurrency::String
SaguaroTrader.withdraw_funds! — Functionwithdraw_funds!(broker, amount::Real)withdraw_funds!(broker, amount::Real, currency::String)Withdraw funds from broker
Parameters
brokeramount::Realcurrency::String
SaguaroTrader.subscribe_funds_to_portfolio! — Functionsubscribe_funds_to_portfolio!(broker, portfolio_id::String, amount::Real)Add funds to portfolio from the broker
Parameters
brokerportfolio_id::Stringamount::Real
SaguaroTrader.withdraw_funds_from_portfolio! — Functionwithdraw_funds_from_portfolio!(broker, portfolio_id::String, amount::Real)Withdraw funds from portfolio into the broker
Parameters
brokerportfolio_id::Stringamount::Real
Order Sizer
SaguaroTrader.OrderSizer — TypeCreate target asset quantities for portfolios
SaguaroTrader.DollarWeightedOrderSizer — TypeCreate target portfolio quantities using the total equity available to the order sizer.
Fields
brokerportfolio_id::Stringcash_buffer_percentage::Float64=0.05
SaguaroTrader.LongShortOrderSizer — TypeCreate target portfolio quantities using the total equity available to the order sizer.
Fields
brokerportfolio_id::Stringgross_leverage::Float64=1.0
Portfolio Construction Model
SaguaroTrader.PortfolioConstructionModel — TypeStruct needed to generate target portfolio weights
Fields
brokerportfolio_id::Stringuniverseorder_sizerportfolio_optimizeralpha_model
Rebalance
SaguaroTrader.Rebalance — TypeRebalance periods for backtesting
SaguaroTrader.BuyAndHoldRebalance — TypeOnly rebalance at the start date
Fields
start_dt::DateTimerebalances::AbstractVector{DateTime}
SaguaroTrader.DailyRebalance — TypeRebalance daily
Fields
start_date::Dateend_date::Datemarket_time::DateTimerebalances::AbstractVector{DateTime}
SaguaroTrader.MonthlyRebalance — TypeRebalance monthly
Fields
start_date::Dateend_date::Datemarket_time::DateTimerebalances::AbstractVector{DateTime}