Adding constraints in grammar for Grammatical Evolution I'm trying to use Grammatical Evolution for creating trading strategies. Each sentence in the grammar when evaluated gives a weight matrix of size n x p . (n is the length of backtesting period and p is the total number of stocks in portfolio)

BNF form of Grammar

&lt;expr&gt;  ::= (&lt;foptr&gt;(&lt;expr&gt;,&lt;expr&gt;,&lt;day&gt;))| 
        (&lt;fopbi&gt;(&lt;expr&gt;,&lt;day&gt;))| 
        (&lt;fopun&gt;(&lt;expr&gt;))| 
        (&lt;expr&gt;&lt;matbi&gt;&lt;expr&gt;)  |
        &lt;var&gt;
&lt;foptr&gt; ::= corr | covariance
&lt;fopbi&gt; ::= mean |    
            sma|
            ema
&lt;fopun&gt; ::= rank| -1* | 1/ 
&lt;matbi&gt; ::= + | - | * | /
&lt;var&gt; ::= Open|High|Low|Close|Volume
&lt;day&gt; ::=  5 | 10 | 15 | 20


The problem is some expressions in this grammar do not make sense. For example, we cannot have a strategy like $Volume/Volume$ or $Low-Low$, etc. And some of the strategies do not have any physical significance, for example, the strategy $Volume+Close$ is not valid as the units of volume and close are different. Any suggestions/references on how to add these constraints to the grammar or circumventing this issue in genetic algorithms will be helpful.
You can enforce that units match by duplicating nonterminals, one per unit.  For instance, instead of var, you can have varA and varB (if A and B are the two types of units); instead of expr, you can have exprA and exprB; with rules like &lt;varA&gt; ::= Close, &lt;varB&gt; ::= Volume, &lt;exprA&gt; ::= ...|&lt;exprA&gt;&lt;matbi&gt;&lt;exprA&gt;|...|varA, &lt;exprB&gt; ::= ...|&lt;exprB&gt;&lt;matbi&gt;&lt;exprB&gt;|...|varB, and so on.

There's no good way to modify the grammar to ensure that it cannot generate any expression that would evaluate to 0.  That is best handled by other methods, not by changing the grammar.