参考:
上一节我们编写的EBNF还不能解决算数运输的优先级问题, 也不能解决表达式前面的负号等运算符的表达, 这次我们修正一下
EBNF修正
算数运算的优先级
// mw strategy meta grammar
?start: logic_expr
?logic_expr: logic_expr LOGIC_2_OP logic_expr -> logic_2
| LOGIC_1_OP logic_expr -> logic_1
| "(" logic_expr ")"
| compare_expr
?compare_expr: math_expr CMP_OP math_expr -> compare
| "(" compare_expr ")"
?math_expr: prod_expr
| math_expr MATH_OP prod_expr -> math
?prod_expr: expr
| prod_expr PROD_OP expr -> prod
?expr: constant
| func_expr
| MATH_OP expr
| "(" math_expr ")"
?func_expr: FUNC "(" arg_expr ("," arg_expr)* ")" [index_expr] -> func
?arg_expr: [string|math_expr] -> arg
?index_expr: "[" constant "]" -> index
string: WORD -> string
constant: SIGNED_NUMBER -> number
MATH_OP: "+" | "-"
PROD_OP: "*" | "/"
LOGIC_1_OP: "NOT"
LOGIC_2_OP: "AND" | "OR"
CMP_OP: ">" | ">=" | "<" | "<=" | "==" | "!="
FUNC: "MA"
| "OPEN"
| "CLOSE"
| "HIGH"
| "LOW"
| "RSI"
| "BUP"
| "BDN"
| "ADX"
| "ATR"
| "DMI"
%import common.WORD
%import common.SIGNED_NUMBER
%import common.WS
%ignore WS
测试公式
我们来测试一个公式:
- 前天的RSI小于25
- 4天前20日均线 + 5天前2倍的ATR - 3 大于 10.8 元
- 上述2个条件成立, 则产生信号, 公式计算结果为True
# (公式1)
RSI(14)[-2] < 25 AND MA(SIM, 20)[-4] + 2 * ATR(14)[-5] - 3 > 10.8
AST语法树
我们来看生成的AST, 可以看出运算优先级已经正确了, 下一节, 我们开始解释执行这个公式
logic_2
compare
func
RSI
arg
number 14
index
number -2
<
number 25
AND
compare
math
math
func
MA
arg
string SIM
arg
number 20
index
number -4
+
prod
number 2
*
func
ATR
arg
number 14
index
number -5
-
number 3
>
number 10.8