Account#

class swordfish.plugins.backtest.Account(account_type, engine)#
Parameters:
account_type: AccountType#
engine: BacktesterBase#
property cash#

Query available cash in the account.

property trade_details#

Retrieve order trade details.

Returns:

Return a table with the following structure:

Field

Description

orderId

Order ID

symbol

Security code

direction

Order direction: 1: Buy open 2: Sell open 3: Sell close 4: Buy close

sendTime

Order submission time

orderPrice

Order submission price

orderQty

Order quantity

tradeTime

Trade time

tradePrice

Trade price

tradeQty

Trade quantity

orderStatus

Order status: 4: Submitted 2: Cancel successful 1: Filled 0: Partially filled -1: Approval rejected -2: Cancel rejected -3: Unfilled order

label

Label

outputOrderInfo

Risk control log, included only if engine parameter outputOrderInfo=true

seqNum

Sequence number column, included only if engine parameter outputSeqNum=true

Return type:

Table

get_position(symbol=None)#

Retrieve position information.

  • If symbol is not specified, a table is returned.

  • If symbol is specified, a dictionary is returned.

  • When JIT optimization is enabled, symbol must be specified.

Parameters:

symbol (str, optional) – A STRING scalar indicating the symbol code.

Returns:

For assets other than SSE bonds, the returned structure is as follows:

Field

Description

symbol

Stock symbol

lastDayLongPosition

Long position at previous close

lastDayShortPosition

Short position at previous close

longPosition

Current long position

longPositionAvgPrice

Average price of long position

shortPosition

Current short position

shortPositionAvgPrice

Average price of short position

todayBuyVolume

Buy volume today

todayBuyValue

Buy value today

todaySellVolume

Sell volume today

todaySellValue

Sell value today

For SSE bonds, the returned structure is as follows:

Field

Description

symbol

Bond symbol

lastDayLongPosition | Long position at previous close

longPosition

Current long position

longPositionAvgPrice | Average price of long position

todayBuyVolume

Buy volume today

todayBuyValue

Buy value today

totalValue

Total position value

accruedInterest

Accrued interest

fullBondPrice

Full bond price

lastPrice

Bond clean price

yield

Yield

interestIncome

Interest income

floatingProfit

Floating profit/loss

realizedProfit

Realized profit/loss

totalProfit

Total profit/loss

duration

Duration

convexity

Convexity

DV01

DV01

Return type:

Table

set_position(symbol, qty, order_price, last_price=None)#

Set the initial position. This function must be called before “append_data” is used to insert market data, and it is typically invoked within the initialize callback function.

Unlike set_last_day_position config, which defines base positions that do not occupy initial capital, set_position defines initial positions whose cost does occupy initial capital.

Parameters:
  • symbol (str) – A STRING scalar indicating the security code.

  • qty (int) –

    An INT scalar indicating the position quantity:

    • qty > 0: indicates a long (buy) position.

    • qty < 0: indicates a short (sell) position. Short selling is not supported for stocks and bonds.

  • order_price (float) – A DOUBLE scalar indicating the cost price of the position.

  • last_price (float, optional) – A DOUBLE scalar indicating the latest price of the security (i.e., the previous closing price). If omitted or set to 0, the default value is orderPrice.

get_daily_position(symbol=None)#

This function is typically called after the backtest completes to retrieve detailed end-of-day position data.

If it is called during the trading session, the current day’s data will be unavailable, and only the previous day’s position data will be returned.

When the asset type is stocks, futures, or options, the structure of the returned position detail table is as follows:

Field

Description

symbol

Symbol code

tradeDate

Trading date

lastDayLongPosition

Long position from the previous day

lastDayShortPosition

Short position from the previous day

longPosition

Current long position

longPositionAvgPrice

Average long trade price

shortPosition

Current short position

shortPositionAvgPrice

Average short trade price

todayBuyVolume

Today’s total buy volume

todayBuyValue

Today’s total buy amount

todaySellVolume

Today’s total sell volume

todaySellValue

Today’s total sell amount

When in margin trading mode, the detailed position table has the following structure:

Field

Description

symbol

Symbol code

tradeDate

Trading date

lastDayMarginSecuPosition

Collateral buy position at previous close

lastDayMarginDebt

Margin loan debt at previous close

lastDaySecuLendingDebt

Securities lending debt at previous close

marginSecuPosition

Collateral buy position

marginSecuAvgPrice

Average price of collateral buy position

marginBuyPosition

Margin buy position

marginBuyValue

Margin buy value

secuLendingPosition

Securities lending (short sell) position

secuLendingSellValue

Securities lending (short sell) value

closePrice

Closing price

longPositionConcentration

Long position concentration ratio

shortPositionConcentration

Net short position concentration ratio

marginBuyProfit

Profit/loss from margin buying

financialFee

Margin interest fee

secuLendingProfit

Profit/loss from securities lending

secuLendingFee

Securities lending fee

When the asset type is a bond, the detailed position table has the following structure:

Field

Description

symbol

Symbol code

tradeDate

Trading date

lastDayLongPosition

Long position quantity at previous close

longPosition

Long position quantity

longPositionAvgPrice

Average buy price

todayBuyVolume

Buy volume of the day

todayBuyValue

Buy value of the day

totalValue

Total position value

accruedInterest

Accrued interest

fullBondPrice

Full bond price

lastPrice

Net bond price

yield

Yield

interestIncome

Interest income

floatingProfit

Unrealized profit/loss

realizedProfit

Realized profit/loss

totalProfit

Total profit/loss

duration

Duration

convexity

Convexity

DV01

DV01 (Dollar Value of 1 Basis Point)

Parameters:

symbol (str, optional) – A STRING scalar indicating the target instrument to query. The default is empty, in which case the function returns position data for all instruments.

property total_portfolios#

Retrieve the current strategy equity metrics.

Returns:

A dictionary is returned with the following structure:

For stocks:

Field Name

Description

tradeDate

Trading date

cash

Available cash

totalMarketValue

Total market value of the account

totalEquity

Total equity of the account

netValue

Unit net value of the account

totalReturn

Cumulative return up to the day

ratio

Daily return of the account

pnl

Daily profit and loss of the account

frozenFunds

Frozen funds

totalFee

Total fees

floatingPnl

Floating profit and loss

realizedPnl

Realized profit and loss

totalPnl

Total profit and loss

For Margin Trading and Securities Lending:

Field Name

Description

tradeDate

Trading date

lineOfCredit

Credit line

availableCash

Available cash

lastDayMarginDebt

Margin debt at previous close

lastDaySecuLendingDebt

Securities lending debt at previous close

marginSecuMarketValue

Market value of collateral purchased

marginDebt

Margin debt

secuLendingSellValue

Securities lending sell value

marginBalance

Margin trading balance

secuLendingDebt

Securities lending debt

financialFee

Financing interest

secuLendingFee

Securities lending fee

maintenanceMargin

Maintenance margin ratio

availableMarginBalance

Available margin balance

totalMarketValue

Total market value of the account

totalEquity

Total equity of the account

netValue

Unit net value of the account

totalReturn

Cumulative return up to the day

yield

Daily return of the account

pnl

Daily profit and loss of the account

frozenFunds

Frozen funds

For Futures/Options:

Field Name

Description

tradeDate

Trading date

margin

Margin used

floatingPnl

Floating PnL

realizedPnl

Realized cumulative PnL

totalPnl

Total PnL

cash

Available cash

totalEquity

Total equity of the account

marginRatio

Margin usage ratio

pnl

Daily profit and loss

netValue

Account unit net value

totalReturn

Cumulative return up to the day

ratio

Daily return of the account

totalFee

Total fees

For Bonds:

Field Name

Description

tradeDate

Trading date

cash

Available cash

totalMarketValue

Total market value of account

totalEquity

Total equity of account

netValue

Account unit net value

totalReturn

Cumulative return up to date

ratio

Daily return

pnl

Daily profit and loss

totalProfit

Total profit and loss

Return type:

Dictionary

property daily_total_portfolios#

Called at the end of a backtest to obtain the strategy’s daily equity metrics table.

Returns:

Return a table. The structure of the returned table varies depending on the asset type of the backtest.

For Stocks:

Field Name

Description

tradeDate

Date

cash

Available cash

totalMarketValue

Total market value of the account

totalEquity

Total equity of the account

netValue

Unit net value of the account

totalReturn

Cumulative return up to the current day

ratio

Daily return of the account

pnl

Daily P&L of the account

frozenFunds

Frozen funds

totalFee

Total fees

floatingPnl

Floating P&L

realizedPnl

Realized P&L

totalPnl

Total P&L

benchmarkClosePrice

Benchmark daily closing price; returned only if benchmark is set

benchmarkNetValue

Benchmark daily net value; returned only if benchmark is set

For Margin Trading and Securities Lending:

Field Name

Description

tradeDate

Date

lineOfCredit

Line of credit

availableCash

Available cash

lastDayMarginDebt

Previous day’s closing margin debt

lastDaySecuLendingDebt

Previous day’s closing securities lending debt

marginSecuMarketValue

Market value of collateral purchased

marginDebt

Margin debt

secuLendingSellValue

Amount from securities lending sell (lending liability)

marginBalance

Margin trading and securities lending balance

secuLendingDebt

Securities lending debt

financialFee

Financing interest

secuLendingFee

Securities lending fee

maintenanceMargin

Maintenance margin ratio

availableMarginBalance

Available margin balance

totalMarketValue

Total market value of the account

totalEquity

Total equity of the account

netValue

Unit net value of the account

totalReturn

Cumulative return up to the current day

yield

Daily return of the account

pnl

Daily P&L of the account

benchmarkClosePrice

Benchmark daily closing price; returned only if benchmark is set

benchmarkNetValue

Benchmark daily net value; returned only if benchmark is set

For Futures/Options:

Field Name

Description

tradeDate

Date

margin

Margin used

floatingPnl

Floating P&L

realizedPnl

Realized cumulative P&L

totalPnl

Total P&L

totalMarketValue

Total market value (options only)

cash

Available cash

totalEquity

Total equity of the account

marginRatio

Margin usage ratio

pnl

Daily P&L of the account

netValue

Unit net value of the account

totalReturn

Cumulative return up to the current day

ratio

Daily return of the account

benchmarkClosePrice

Benchmark daily closing price; returned only if benchmark is set

benchmarkNetValue

Benchmark daily net value; returned only if benchmark is set

For Bonds:

Field Name

Description

tradeDate

Date

cash

Available cash

totalMarketValue

Total market value of the account

totalEquity

Total equity of the account

netValue

Unit net value of the account

totalReturn

Cumulative return up to the current day

ratio

Daily return of the account

pnl

Daily P&L of the account

totalProfit

Total profit/loss

benchmarkClosePrice

Benchmark daily closing price; returned only if benchmark is set

benchmarkNetValue

Benchmark daily net value; returned only if benchmark is set

Return type:

Table

property return_summary#

Used to calculate the strategy’s performance summary at the end of backtesting.

Returns:

A table is returned with the following structure:

For Stocks/Futures/Options/Bonds:

Field Name

Description

totalReturn

Total return

annualReturn

Annualized return

annualVolatility

Annualized volatility

annualSkew

Return skewness

annualKur

Return kurtosis

sharpeRatio

Sharpe ratio

maxDrawdown

Maximum drawdown

drawdownRatio

Drawdown-to-return ratio

beta

Beta coefficient

alpha

Alpha coefficient

benchmarkReturn

Benchmark return

annualExcessReturn

Annualized excess return

turnoverRate

Turnover rate

dailyWinningRate

Daily winning rate

maxMarginRatio

Maximum margin usage (field unique to futures/options)

In Margin Trading and Securities Lending mode, the returned table contains the above fields as well as the following additional fields:

Field Name

Description

totalFee

Total commission and fees

financialFee

Financing interest

secuLendingFee

Securities lending fee

bottomRet

Base position return

bottomExcessRet

Base position excess return

Return type:

Table