0

Is there any function in DolphinDB that is similar to the Crossover in Backtrader?

For example, the initial state is "A < B". When "A > B", the A line crosses over the B line, which is expected to be output as an anomaly.

an example of the scenario

zhihengqu
  • 371
  • 5

1 Answers1

0

For the current points A, B, three indicators can be used together to determine whether the A line crosses over B line:

  • previous value A < previous value B

  • current value A > current value B

  • the slope of the line segment where point A is located > the slope of the line segment where B is located

Here are the script:

share streamTable(1000:0, `time`sym`qty1`qty2, [TIMESTAMP, SYMBOL, INT, INT]) as trades
outputTable = table(1000:0, `time`sym`type`metric, [TIMESTAMP, SYMBOL, INT, STRING])
engine = createAnomalyDetectionEngine(name="anomalyDetection1", metrics=<[prev(qty1) <= prev(qty2) && qty1 >= qty2 && (qty1 - prev(qty1)) > (qty2-prev(qty2))]>, dummyTable=trades, outputTable=outputTable, timeColumn=`time, keyColumn=`sym)
subscribeTable(tableName="trades", actionName="anomalyDetectionSub1", offset=0, handler=append!{engine}, msgAsTable=true)
def writeData(n){
    timev = 2018.10.08T01:01:01.001 + 1..n
    symv =take(`A`B, n)
    qtyv1 = rand(1..10, n)
    qtyv2 = rand(4..14, n)
    trades.append!(table(timev, symv, qtyv1, qtyv2))
}
writeData(40);
select * from trades;
select * from outputTable

(1) Verify whether the crossover points exist when sym=`A.

t = select * from trades where sym = `A
plot(data=[t.qty1, t.qty2], labels=t.time)

enter image description here

According to the results, it can be seen that the crossover points are at time 2018.10.08T01:01:01.014, 2018.10.08T01:01:01.020, and 2018.10.08T01:01:01.030, respectively.

select * from outputTable where sym=`A

enter image description here

The result meet the expectation.

(2) Verify whether the crossover points exist when sym=`B.

t = select * from trades where sym = `B
plot(data=[t.qty1, t.qty2], labels=t.time)

enter image description here

select * from outputTable where sym=`B

enter image description here

The result meet the expectation.

molddd123
  • 297
  • 6