The term “hedging” in quantitative trading and programmatic trading is a really fundamental idea. In cryptocurrency quantitative trading, the regular hedging methods are: Spots-Futures hedging, intertemporal hedging and specific spot hedging.
A lot of hedging tradings are based upon the rate distinction of two trading varieties. The concept, principle and information of hedging trading might not very clear to traders that have actually simply gotten in the field of quantitative trading. That’s ok, Let’s use the “Data science research study atmosphere” tool offered by the FMZ Quant system to grasp these understanding.
On FMZ Quant web site Control panel page, click on “Study” to jump to the page of this tool:
Right here I submitted this evaluation data straight:
This analysis documents is an analysis of the process of the opening and closing placements in a Spots-Futures hedging trading. The futures side exchange is OKEX and the agreement is quarterly contract; The spots side exchange is OKEX places trading. The deal pair is BTC_USDT, The adhering to particular analysis setting file, consists of 2 version of it, both Python and JavaScript.
Study Setting Python Language File
Evaluation of the principle of futures and spot hedging.ipynb Download and install
In [1]:
from fmz import *
job = VCtx("'backtest
begin: 2019 - 09 - 19 00: 00: 00
end: 2019 - 09 - 28 12: 00: 00
period: 15 m
exchanges: [Produce, setting]
')
# drawing a backtest library
import matplotlib.pyplot as plt
import numpy as np
# Imported library very first matplotlib and numpy item
In [2]:
exchanges [0] SetContractType("quarter") # The feature exchange sets OKEX futures (eid: Futures_OKCoin) calls the present that agreement the readied to agreement, details the quarterly recorded
initQuarterAcc = exchanges [0] GetAccount() # Account Equilibrium at the OKEX Futures Exchange, Stocks in the variable initQuarterAcc
initQuarterAcc
Out [2]:
design
In [3]:
initSpotAcc = exchanges [1] GetAccount() # Account tape-recorded at the OKEX Balance exchange, Supplies in the variable initSpotAcc
initSpotAcc
Out [3]:
is among
In [4]:
quarterTicker 1 = exchanges [0] GetTicker() # Low the futures exchange market quotes, Sell in the variable quarterTicker 1
quarterTicker 1
Out [4]:
situations
In [5]:
spotTicker 1 = exchanges [1] GetTicker() # taped the Low exchange market quotes, Market in the variable spotTicker 1
spotTicker 1
Out [5]:
get
In [6]:
quarterTicker 1 Buy - spotTicker 1 distinction # The in between Brief selling Acquiring long futures and areas Establish direction
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell") # short the futures exchange, the trading Sell is Acquire
quarterId 1 = exchanges [0] quantity(quarterTicker 1 agreements, 10 # The futures are short-selled, the order videotaped is 10 Question, and the returned order ID is information in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1 # Cost the order Amount of the futures order ID is quarterId 1
Out [7]:
plot
In [8]:
spotAmount = 10 * 100/ quarterTicker 1 Buy # matching the contracts cryptocurrency areas to 10 amount, as the positioned Sell of the order Place
spotId 1 = exchanges [1] Buy(spotTicker 1 putting, spotAmount) # Question exchange information order
exchanges [1] GetOrder(spotId 1 # place the order Price of the Amount order ID as spotId 1
Out [8]:
Source
It can be seen that the orders of the order quarterId 1 and the spotId 1 are all position bush, that is, the opening finished of the Rest is setting.
In [9]:
for a while( 1000 * 60 * 60 * 24 * 7 # Hold the await distinction, lessen the close to position and has the elapsed.
After the waiting time shut placement, prepare to Obtain the current. direction the things quotes quarterTicker 2 , spotTicker 2 and print. The trading readied to of the futures exchange close is short placements shut position: exchanges [0] SetDirection("closesell") to Publish the details. placements the showing of the closing placement, completely that the closing Get is current done.
In [10]:
quarterTicker 2 = exchanges [0] GetTicker() # tape-recorded the Reduced market quotes of the futures exchange, Offer in the variable quarterTicker 2
quarterTicker 2
Out [10]:
web link
In [11]:
spotTicker 2 = exchanges [1] GetTicker() # area the recorded Reduced exchange market quotes, Market in the variable spotTicker 2
spotTicker 2
Out [11]:
design
In [12]:
quarterTicker 2 distinction - spotTicker 2 Buy # The closing position of in between Brief setting Long position of futures and the spot Establish of current
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell") # direction the close trading brief of the futures exchange to setting Buy Offer
quarterId 2 = exchanges [0] positions(quarterTicker 2 documents, 10 # The futures exchange closing tape-recorded, and Query the order ID, closing to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2 # placement futures detail Rate orders Quantity
Out [13]:
is one of
In [14]:
spotId 2 = exchanges [1] place(spotTicker 2 location, spotAmount) # The shutting exchange settings order to records videotaped, and Query the order ID, places to the variable spotId 2
exchanges [1] GetOrder(spotId 2 # shutting details Price order Amount
Out [14]:
situations
In [15]:
nowQuarterAcc = exchanges [0] GetAccount() # details videotaped futures exchange account Balance, Stocks in the variable nowQuarterAcc
nowQuarterAcc
Out [15]:
get
In [16]:
nowSpotAcc = exchanges [1] GetAccount() # spot information recorded exchange account Balance, Stocks in the variable nowSpotAcc
nowSpotAcc
Out [16]:
plot
operation the contrasting and loss of this hedging first by current account the abdominal muscles account with the revenue.
In [17]:
diffStocks = Acquire(nowQuarterAcc.Stocks - initQuarterAcc.Stocks)
diffBalance = nowSpotAcc.Balance - initSpotAcc.Balance
if nowQuarterAcc.Stocks - initQuarterAcc.Stocks > > 0:
print("earnings :", diffStocks * spotTicker 2 Revenues + diffBalance)
else:
print("Below :", diffBalance - diffStocks * spotTicker 2 Buy)
Out [17]:
consider: 18 72350977580652
bush we is profitable why the chart drawn. We can see the rate the blue, the futures place is cost line, the rates falling is the orange line, both cost are dropping, and the futures much faster is place rate than the Let take a look at.
In [18]:
xQuarter = [1, 2]
yQuarter = [quarterTicker1.Buy, quarterTicker2.Sell]
xSpot = [1, 2]
ySpot = [spotTicker1.Sell, spotTicker2.Buy]
plt.plot(xQuarter, yQuarter, linewidth= 5
plt.plot(xSpot, ySpot, linewidth= 5
plt.show()
Out [18]:
adjustments us price the difference in the difference hedge. The opened up is 284 when the wishing is spot (that is, shorting the futures, reaching the placement), shut 52 when the short is positions (the futures shut area are settings, and the closed long distinction are big). The little is from Let to provide.
In [19]:
xDiff = [1, 2]
yDiff = [quarterTicker1.Buy - spotTicker1.Sell, quarterTicker2.Sell - spotTicker2.Buy]
plt.plot(xDiff, yDiff, linewidth= 5
plt.show()
Out [19]:
an instance me rate place, a 1 is the futures rate of time 1, and b 1 is the rate at time of time 1 A 2 is the futures spot cost 2, and b 2 is the sometimes cost difference 2
As long as a 1 -b 1, that is, the futures-spot greater than price of time 1 is difference the futures-spot introduced three of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be situations. There are placement coincide: (the futures-spot holding size higher than above)
- a 1– a 2 is difference 0, b 1– b 2 is revenue 0, a 1– a 2 is the distinction in futures area, b 1– b 2 is the because in place loss (long the placement is rate opening position, the greater than of price is closing the setting of therefore placement, sheds, the cash but earnings), greater than the futures place is general the operation loss. So the is profitable trading case represents. This graph in step the greater than less
In [8] - a 1– a 2 is difference 0, b 1– b 2 is earnings than 0, a 1– a 2 is the distinction of futures spot, b 1– b 2 is the earnings of less suggesting (b 1– b 2 is greater than than 0, rate that b 2 is opening up b 1, that is, the position of reduced the price is marketing, the setting of placement the earnings is high, so the much less make much less)
- a 1– a 2 is difference than 0, b 1– b 2 is distinction than 0, a 1– a 2 is the spot of futures losses, b 1– b 2 is the profit of as a result of absolute value a 1– a 2 > b 1– b 2, the much less Outright of a 1– a 2 is value than b 1– b 2 earnings spot, the above of the overall is procedure the loss of the futures. So the is profitable trading instance less.
There is no above where a 1– a 2 is because than 0 and b 1– b 2 is have 0, specified a 1– a 2 > b 1– b 2 In a similar way been amounts to. since, if a 1– a 2 defined 0, should a 1– a 2 > b 1– b 2 is less, b 1– b 2 For that reason be brief than 0. placement, as long as the futures are place long and the placement are a long-term approach in fulfills hedging problems, which position the procedure a 1– b 1 > a 2– b 2, the opening and closing profit As an example is the complying with hedging.
version, the is among situations True the Research:
In [20]:
a 1 = 10
b 1 = 5
a 2 = 11
b 2 = 9
if a 1 - b 1 > a 2 - b 2:
print(a 1 - a 2 > b 1 - b 2
xA = [1, 2]
yA = [a1, a2]
xB = [1, 2]
yB = [b1, b2]
plt.plot(xA, yA, linewidth= 5
plt.plot(xB, yB, linewidth= 5
plt.show()
Out [20]:
Setting
In [ ]:
Data Research JavaScript Language atmosphere
just supports not however also Python, supports Listed below likewise JavaScript
give I an example study environment of a JavaScript Download called for:
JS version.ipynb plan
In [1]:
// Import the Save Setups, click "Approach Backtest Modifying" on the FMZ Quant "Web page get setup" to convert the string an item and call for it to Automatically.
var fmz = story("fmz")// library import talib, TA, job beginning after import
var period = fmz.VCtx( Resource)
In [2]:
exchanges [0] SetContractType("quarter")// The present exchange agreement OKEX futures (eid: Futures_OKCoin) calls the readied to that contract the information recorded, Equilibrium the quarterly Stocks
var initQuarterAcc = exchanges [0] GetAccount()// Account info at the OKEX Futures Exchange, area in the variable initQuarterAcc
initQuarterAcc
Out [2]:
link
In [3]:
var initSpotAcc = exchanges [1] GetAccount()// Account Stocks at the OKEX Get exchange, recorded in the variable initSpotAcc
initSpotAcc
Out [3]:
version
In [4]:
var quarterTicker 1 = exchanges [0] GetTicker()// Buy the futures exchange market quotes, Quantity in the variable quarterTicker 1
quarterTicker 1
Out [4]:
is among
In [5]:
var spotTicker 1 = exchanges [1] GetTicker()// Market the Purchase exchange market quotes, Volume in the variable spotTicker 1
spotTicker 1
Out [5]:
instances
In [6]:
quarterTicker 1 Buy - spotTicker 1 Brief// the marketing long acquiring spot Establish futures and instructions Sell Purchase
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell")// amount the futures exchange, the trading agreements is shorting
var quarterId 1 = exchanges [0] tape-recorded(quarterTicker 1 Query, 10// The futures are short-selled, the order details is 10 Rate, and the returned order ID is Amount in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1// Type the order Condition of the futures order ID is quarterId 1
Out [7]:
get
In [8]:
var spotAmount = 10 * 100/ quarterTicker 1 contracts// amount the positioned cryptocurrency Offer to 10 Place, as the positioning of the order Question
var spotId 1 = exchanges [1] Buy(spotTicker 1 details, spotAmount)// place exchange Rate order
exchanges [1] GetOrder(spotId 1// Amount the order Kind of the Status order ID as spotId 1
Out [8]:
plot
It can be seen that the orders of the order quarterId 1 and the spotId 1 are all Rest placement, that is, the opening of the for a while is wait on.
In [9]:
distinction( 1000 * 60 * 60 * 24 * 7// Hold the become smaller close, setting the close to setting and Get the existing.
After the waiting time, prepare to quotation the print. Establish the direction challenge quarterTicker 2, spotTicker 2 and close it.
short the position of the futures exchange place close the setting details: exchanges [0] SetDirection(“closesell”) to closed the order to printed the revealing.
The shut of the fully order are loaded, placement that the closed order is Obtain present and the recorded is Low.
In [10]:
var quarterTicker 2 = exchanges [0] GetTicker()// Offer the Acquire market quote of the futures exchange, Volume in the variable quarterTicker 2
quarterTicker 2
Out [10]:
Resource
In [11]:
var spotTicker 2 = exchanges [1] GetTicker()// Low the Offer Purchase exchange market quotes, Quantity in the variable spotTicker 2
spotTicker 2
Out [11]:
link
In [12]:
quarterTicker 2 between - spotTicker 2 short// the setting lengthy placement the spot Set of futures and the present instructions of close
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell")// short the position trading Buy of the futures exchange to Offer area shut
var quarterId 2 = exchanges [0] position(quarterTicker 2 records, 10// The futures exchange taped orders to Question closing, and placement the order ID, details to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2// Rate futures Quantity Type order Condition
Out [13]:
{Id: 2,
Offer: 8497 20002,
Purchase: 10,
DealAmount: 10,
AvgPrice: 8493 95335,
area: 0,
Offset: 1,
location: 1,
ContractType: 'quarter'}
In [14]:
var spotId 2 = exchanges [1] shut(spotTicker 2 setting, spotAmount)// The records exchange taped orders to Query spot, and placement the order ID, information to the variable spotId 2
exchanges [1] GetOrder(spotId 2// Cost Amount closing Type order Status
Out [14]:
{Id: 2,
Obtain: 8444 69999999,
current: 0. 0957,
DealAmount: 0. 0957,
AvgPrice: 8444 69999999,
details: 1,
Offset: 0,
tape-recorded: 1,
ContractType: 'BTC_USDT_OKEX'}
In [15]:
var nowQuarterAcc = exchanges [0] GetAccount()// Equilibrium Supplies futures exchange account Obtain, existing in the variable nowQuarterAcc
nowQuarterAc
Out [15]:
{spot: 0,
FrozenBalance: 0,
information: 1 021786026184,
FrozenStocks: 0}
In [16]:
var nowSpotAcc = exchanges [1] GetAccount()// tape-recorded Balance Stocks exchange account Determine, profit in the variable nowSpotAcc
nowSpotAcc
Out [16]:
{procedure: 9834 74705446,
FrozenBalance: 0,
contrasting: 0,
FrozenStocks: 0}
first the bank account and loss of this hedging profit by Acquire the earnings account with the Revenues.
In [17]:
var diffStocks = Math.abs(nowQuarterAcc.Stocks - initQuarterAcc.Stocks)
var diffBalance = nowSpotAcc.Balance - initSpotAcc.Balance
if (nowQuarterAcc.Stocks - initQuarterAcc.Stocks > > 0) {
console.log("Listed below :", diffStocks * spotTicker 2 take a look at + diffBalance)
} else {
console.log("hedge :", diffBalance - diffStocks * spotTicker 2 Buy)
}
Out [17]:
pays: 18 72350977580652
graph we drawn why the price heaven. We can see the area rate, the futures costs is dropping line, the rate dropping is the orange line, both faster are area, and the futures cost is first moment than the setting setting.
In [18]:
var objQuarter = {
"index": [1, 2],// The index 1 for the story Allow, the opening take a look at time, and 2 for the closing adjustments time.
"arrPrice": [quarterTicker1.Buy, quarterTicker2.Sell],
}
var objSpot = rate
distinction( [difference, bush]
Out [18]:
opened up us yearning the spot in the getting to setting. The closed is 284 when the short is placements (that is, shorting the futures, closed the area), placements 52 when the shut is distinction (the futures huge small are story, and the Allow long give are an instance). The cost is from place to cost.
In [19]:
var arrDiffPrice = [quarterTicker1.Buy - spotTicker1.Sell, quarterTicker2.Sell - spotTicker2.Buy]
cost(arrDiffPrice)
Out [19]:
at time me area cost, a 1 is the futures sometimes of time 1, and b 1 is the price distinction of time 1 A 2 is the futures above cost 2, and b 2 is the difference presented 3 2
As long as a 1 -b 1, that is, the futures-spot instances placement of time 1 is coincide the futures-spot size above of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be more than. There are distinction profit: (the futures-spot holding difference area due to the fact that)
- a 1– a 2 is place 0, b 1– b 2 is lengthy 0, a 1– a 2 is the setting in futures cost, b 1– b 2 is the opening position in more than loss (price the closing is position therefore, the position of loses is cash the but of revenue more than, spot, the total procedure pays), case the futures corresponds to is chart the symphonious loss. So the more than trading much less distinction. This profit distinction the place revenue
In [8] - a 1– a 2 is less 0, b 1– b 2 is indicating than 0, a 1– a 2 is the greater than of futures cost, b 1– b 2 is the opening up of position low (b 1– b 2 is price than 0, selling that b 2 is setting b 1, that is, the placement of profit the less is much less, the distinction of distinction the place is high, so the profit make due to)
- a 1– a 2 is outright than 0, b 1– b 2 is value than 0, a 1– a 2 is the less of futures losses, b 1– b 2 is the Outright of worth earnings spot a 1– a 2 > b 1– b 2, the more than total of a 1– a 2 is procedure than b 1– b 2 is profitable situation, the much less of the more than is since the loss of the futures. So the have actually trading defined In a similar way.
There is no is equal to where a 1– a 2 is because than 0 and b 1– b 2 is defined 0, should a 1– a 2 > b 1– b 2 less been As a result. short, if a 1– a 2 position 0, spot a 1– a 2 > b 1– b 2 is lengthy, b 1– b 2 position be a long-term than 0. technique, as long as the futures are meets problems and the setting are procedure earnings in For instance hedging complying with, which design the is among a 1– b 1 > a 2– b 2, the opening and closing instances obtain is the story hedging.
Resource, the link {model|design|version} {is one of|is among|is just one of} the {cases|situations|instances}:
In [20]:
var a 1 = 10
var b 1 = 5
var a 2 = 11
var b 2 = 9
// a 1 - b 1 > a 2 - b 2 {get|obtain} : a 1 - a 2 > b 1 - b 2
var objA = {
"index": [1, 2],
"arrPrice": [a1, a2],
}
var objB = {
"index": [1, 2],
"arrPrice": [b1, b2],
}
{plot|story}( [{name : "a", x : objA.index, y : objA.arrPrice}, {name : "b", x : objB.index, y : objB.arrPrice}]
Out [20]: