API
SaguaroTrader.AlphaModel
SaguaroTrader.AlwaysOpenExchange
SaguaroTrader.Asset
SaguaroTrader.BacktestDataHandler
SaguaroTrader.Broker
SaguaroTrader.BuyAndHoldRebalance
SaguaroTrader.CSVDailyBarSource
SaguaroTrader.Cash
SaguaroTrader.DailyRebalance
SaguaroTrader.DataHandler
SaguaroTrader.DataSource
SaguaroTrader.DollarWeightedOrderSizer
SaguaroTrader.DynamicUniverse
SaguaroTrader.EqualWeightPortfolioOptimizer
SaguaroTrader.Equity
SaguaroTrader.Exchange
SaguaroTrader.FeeModel
SaguaroTrader.FixedSignalsAlphaModel
SaguaroTrader.FixedSlippageModel
SaguaroTrader.FixedWeightPortfolioOptimizer
SaguaroTrader.LongShortOrderSizer
SaguaroTrader.MonthlyRebalance
SaguaroTrader.Order
SaguaroTrader.OrderSizer
SaguaroTrader.PercentFeeModel
SaguaroTrader.PercentSlippageModel
SaguaroTrader.Portfolio
SaguaroTrader.PortfolioConstructionModel
SaguaroTrader.PortfolioEvent
SaguaroTrader.PortfolioOptimizer
SaguaroTrader.Position
SaguaroTrader.PositionHandler
SaguaroTrader.Rebalance
SaguaroTrader.RollingSignalsAlphaModel
SaguaroTrader.SimulatedBroker
SaguaroTrader.SimulatedExchange
SaguaroTrader.SingleSignalAlphaModel
SaguaroTrader.SlippageModel
SaguaroTrader.StaticUniverse
SaguaroTrader.Transaction
SaguaroTrader.Universe
SaguaroTrader.VolumeSharesSlippageModel
SaguaroTrader.ZeroFeeModel
SaguaroTrader.ZeroSlippageModel
SaguaroTrader.calculate_fee
SaguaroTrader.cost_with_fee
SaguaroTrader.cost_without_fee
SaguaroTrader.create_asset_transaction
SaguaroTrader.create_portfolio!
SaguaroTrader.create_subscription
SaguaroTrader.create_withdrawal
SaguaroTrader.get_ask
SaguaroTrader.get_asset_latest_bid_ask_price
SaguaroTrader.get_asset_latest_mid_price
SaguaroTrader.get_assets_historical_bids
SaguaroTrader.get_assets_historical_range_close_price
SaguaroTrader.get_bid
SaguaroTrader.position_from_transaction
SaguaroTrader.subscribe_funds!
SaguaroTrader.subscribe_funds_to_portfolio!
SaguaroTrader.total_equity
SaguaroTrader.total_market_value
SaguaroTrader.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::Int
1=>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::DataHandler
scale::Float64
Exchange
SaguaroTrader.Exchange
— TypeAbstract type for trading exchange
SaguaroTrader.SimulatedExchange
— TypeSimulate live trading
Fields
start_dt::DateTime
open_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_model
quantity::Real
price::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::String
The full path to the directory where the CSV is located.asset_type::String
The asset type that the price/volume data is for.adjust_prices::String
Whether to utilise corporate-action adjusted prices for both the open and closing prices. Defaults to True.csv_symbols::Vector
An 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::CSVDailyBarSource
dt::DateTime
asset::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::CSVDailyBarSource
dt::DateTime
asset::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::CSVDailyBarSource
start_dt::DateTime
end_dt::DateTime
asset::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::DataHandler
dt::DateTime
asset::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::DataHandler
dt::DateTime
asset::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::DataHandler
start_dt::DateTime
end_dt::DateTime
asset::AbstractVector{Symbol}
Returns
DataFrame
: dataframe of close prices for the assets
Transaction
SaguaroTrader.Transaction
— TypeMetadata about a transaction of an asset
Fields
asset::Symbol
quantity::Float64
dt::DateTime
price::Float64
fee::Float64
order_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::Symbol
current_price::Float64
current_dt::DateTime
buy_quantity::Float64
sell_quantity::Float64
net_quantity::Float64
avg_bought::Float64
avg_sold::Float64
buy_fee::Float64
sell_fee::Float64
SaguaroTrader.position_from_transaction
— Functionposition_from_transaction(txn::Transaction)::Position
Create 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::DateTime
type::String
debit::Float64
credit::Float64
balance::Float64
SaguaroTrader.create_subscription
— Functioncreate_subscription(dt::DateTime, credit::Float64, balance::Float64)
Create a subscription portolio event
Parameters
dt::DateTime
credit::Float64
balance::Float64
Returns
PortfolioEvent
SaguaroTrader.create_withdrawal
— Functioncreate_withdrawal(dt::DateTime, credit::Float64, balance::Float64)
Create a withdrawal portolio event
Parameters
dt::DateTime
credit::Float64
balance::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::DateTime
txn_total_cost::Float64
balance::Float64
direction::Int
Returns
PortfolioEvent
SaguaroTrader.Portfolio
— TypePortfolio
Fields
current_dt::DateTime
cash::Float64
currency::String
pos_handler::PositionHandler
portfolio_id::String
name::String
history::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
ord1
ord2
Returns
Float64
SaguaroTrader.total_equity
— Functiontotal_equity(port::Portfolio)
Total market value of the portfolio including cash.
Parameters
ord1
ord2
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
universe
signal::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::DateTime
current_dt::DateTime
exchange
data_handler::DataHandler
account_id::String
base_currency::String
initial_cash::Float64
fee_model
cash_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
broker
initial_cash::Real
name::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
broker
amount::Real
currency::String
SaguaroTrader.withdraw_funds!
— Functionwithdraw_funds!(broker, amount::Real)
withdraw_funds!(broker, amount::Real, currency::String)
Withdraw funds from broker
Parameters
broker
amount::Real
currency::String
SaguaroTrader.subscribe_funds_to_portfolio!
— Functionsubscribe_funds_to_portfolio!(broker, portfolio_id::String, amount::Real)
Add funds to portfolio from the broker
Parameters
broker
portfolio_id::String
amount::Real
SaguaroTrader.withdraw_funds_from_portfolio!
— Functionwithdraw_funds_from_portfolio!(broker, portfolio_id::String, amount::Real)
Withdraw funds from portfolio into the broker
Parameters
broker
portfolio_id::String
amount::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
broker
portfolio_id::String
cash_buffer_percentage::Float64=0.05
SaguaroTrader.LongShortOrderSizer
— TypeCreate target portfolio quantities using the total equity available to the order sizer.
Fields
broker
portfolio_id::String
gross_leverage::Float64=1.0
Portfolio Construction Model
SaguaroTrader.PortfolioConstructionModel
— TypeStruct needed to generate target portfolio weights
Fields
broker
portfolio_id::String
universe
order_sizer
portfolio_optimizer
alpha_model
Rebalance
SaguaroTrader.Rebalance
— TypeRebalance periods for backtesting
SaguaroTrader.BuyAndHoldRebalance
— TypeOnly rebalance at the start date
Fields
start_dt::DateTime
rebalances::AbstractVector{DateTime}
SaguaroTrader.DailyRebalance
— TypeRebalance daily
Fields
start_date::Date
end_date::Date
market_time::DateTime
rebalances::AbstractVector{DateTime}
SaguaroTrader.MonthlyRebalance
— TypeRebalance monthly
Fields
start_date::Date
end_date::Date
market_time::DateTime
rebalances::AbstractVector{DateTime}