def __init__(self): self.dataclose = self.datas[0].close self.indicators = [] self.strategy_expression_buy = self.params.strategy_expression_buy self.strategy_expression_sell = self.params.strategy_expression_sell self.strategies_parameters = self.params.strategies_parameters for s, p in self.strategies_parameters.items(): if p["name"] == "CCI_buy_Strategy": self.indicators.append(bt.indicators.CommodityChannelIndex()) elif p["name"] == "CCI_sell_Strategy": self.indicators.append(bt.indicators.CommodityChannelIndex()) elif p["name"] == "Crossover_SMA_Strategy": sma_fast, sma_slow = bt.ind.SMA(period=p["parameter"]["fast"]), bt.ind.SMA(period=p["parameter"]["slow"]) self.indicators.append(bt.indicators.CrossOver(sma_fast, sma_slow)) self.strategy_parser = Grammar(""" start: exp ; @exp : strategy | atomic ; atomic: '\(' exp op exp '\)' | exp op exp ; strategy: 's\d+' ; op: '\&|\|' ; SPACES: '[ ]+' (%ignore) ; """) self.strategy_expression_buy = self.strategy_parser.parse(self.strategy_expression_buy) self.calc_buy = self.Calc(self.indicators, self.strategies_parameters) self.strategy_expression_sell = self.strategy_parser.parse(self.strategy_expression_sell) self.calc_sell = self.Calc(self.indicators, self.strategies_parameters)
import operator as op from plyplus import Grammar, STransformer calc_grammar = Grammar(""" start: add; ?add: (add add_symbol)? mul; ?mul: (mul mul_symbol)? atom; @atom: neg | number | '\(' add '\)'; neg: '-' atom; number: '[\d.]+'; mul_symbol: '\*' | '/'; add_symbol: '\+' | '-'; WS: '[ \t]+' (%ignore); """) class Calc(STransformer): def _bin_operator(self, exp): arg1, operator_symbol, arg2 = exp.tail operator_func = { '+': op.add, '-': op.sub, '*': op.mul, '/': op.div }[operator_symbol] return operator_func(arg1, arg2) number = lambda self, exp: float(exp.tail[0]) neg = lambda self, exp: -exp.tail[0] __default__ = lambda self, exp: exp.tail[0] add = _bin_operator mul = _bin_operator
list_parser = Grammar(r""" start : (command eol)* ; command : alpha_command | animate_command | color_command | 'display' | define_command | kill_command | spring_command | 'wait'; alpha_command: 'alpha' pattern number; animate_command: 'animate' geometry; color_command: 'color' pattern color; define_command: box_command ; // box_command : 'define' name 'box' number number (color)? (geometry)? (option)*; box_command : 'define' name 'box' number number color; kill_command: 'kill' pattern ; sleep_command: 'sleep' number; spring_command: 'spring' pattern (number number number number)? (option)*; pattern: name (name)* | regexp ; option: '-' name; geometry : number number | name (offset)?; offset : '\+' number '-' number ; color: simple_color ('\*' number)?; simple_color: name | '\#[\da-f]{6,8}' | number ',' number ',' number (',' number)? | name '\*' number; name : '[A-Za-z][0-9A-Za-z]*' ; number : '[\d\.]+' ; regexp: 'r\'.+?\'' ; eol : '\n' ; SPACES : ' +' (%ignore) ; """)
#tokens = tokens +' '+token[2].lower() return tokens path = 'Programas_MiniJava/programa1.java' with open(path) as f: texto_arq = f.readlines() #print(texto) texto = '' for i in texto_arq: texto = texto + i texto = retornaTokensArquivo(path) cont = 1 text = '' for i in texto: text = text + i if i == ' ': #print(text, cont) cont += 1 text = '' #print(texto) #texto = retornaTokensArquivo(path) parser = Grammar(open("MiniJava.g")) resp = parser.parse(texto) print(resp)
def buildGrammar(self): return Grammar(self.grammar)
calc_grammar = Grammar(""" @start: assign; // Rules ?assign: (id eq_symbol)? logic; ?logic: (logic logic_symbol)? add; ?add: (add add_symbol)? mul; ?mul: (mul mul_symbol)? atom; @atom: neg | number | '\(' add '\)' | boolean | id; neg: '-' atom; // Tokens number: '[\d.]+'; eq_symbol: '<-'; boolean : true | false; true: TRUE; false: FALSE; logic_symbol: '\&' | '\|'; id: ID; ID: '\w+' (%unless TRUE: 'TRUE'; FALSE: 'FALSE'; ); mul_symbol: '\*' | '/'; add_symbol: '\+' | '-'; WS: '[ \t]+' (%ignore); """)
# calc.py - # A simple calculator without using eval # A shorter and simpler re-implementation of http://www.dabeaz.com/ply/example.html import operator as op from plyplus import Grammar, STransformer calc_grammar = Grammar(open("calc.g")) class Calc(STransformer): def __init__(self): super() def _bin_operator(self, exp): arg1, operator_symbol, arg2 = exp.tail operator_func = { '+': op.add, '-': op.sub, '%': op.mod, '*': op.mul, '/': op.truediv, '^': op.pow }[operator_symbol] print(exp.tail, '=>', operator_func(arg1, arg2)) return operator_func(arg1, arg2) number = lambda self, exp: float(exp.tail[0]) negate = lambda self, exp: -exp.tail[0] __default__ = lambda self, exp: exp.tail[0]
from plyplus import Grammar, STransformer json_grammar = Grammar(r""" @start: value ; ?value : object | array | string | number | boolean | null ; string : '".*?(?<!\\)(\\\\)*?"' ; number : '-?([1-9]\d*|\d)(\.\d+)?([eE][+-]?\d+)?' ; pair : string ':' value ; object : '\{' ( pair ( ',' pair )* )? '\}' ; array : '\[' ( value ( ',' value ) * )? '\]' ; boolean : 'true' | 'false' ; null : 'null' ; WS: '[ \t\n]+' (%ignore) (%newline); """) class JSON_Transformer(STransformer): """Transforms JSON AST into Python native objects.""" number = lambda self, node: float(node.tail[0]) string = lambda self, node: node.tail[0][1:-1] boolean = lambda self, node: True if node.tail[0] == 'true' else False null = lambda self, node: None array = lambda self, node: node.tail pair = lambda self, node: {node.tail[0]: node.tail[1]} def object(self, node): result = {} for i in node.tail:
# Eval and bridge to the scripting lang. import operator as op import math # do not mess with following 3 lines. from plyplus import Grammar gram_text = open('grmr.g', 'r').read() grammar = Grammar(gram_text) class EvalError(BaseException): pass class Scope: def __init__(self, parent, isfunc, kwargs): self.parent = parent self.vars = {} self.isfunc = isfunc self.vars.update(kwargs) def __getitem__(self, item): try: return self.vars[item] except: try: return self.parent[item] except: raise EvalError, "Variable not defined: " + str(item)
# Python 3.x already have lazy map pass __all__ = ["parse"] __version__ = "0.2.0" grammar = Grammar(r""" @start : package ; package : name extras? specs? comment?; name : string ; specs : comparison version (',' comparison version)* ; comparison : '<' | '<=' | '!=' | '==' | '>=' | '>' | '~=' | '===' ; version : string ; extras : '\[' (extra (',' extra)*)? '\]' ; extra : string ; comment : '\#.+' ; @string : '[-A-Za-z0-9_\.]+' ; SPACES: '[ \t\n]+' (%ignore) (%newline); """) class Requirement(object): def __init__(self, name=None, extras=None, specs=None, comment=None): self.name = name self.extras = extras
"""Demonstrates the use of the permutation operator.""" from plyplus import Grammar # Basic Permutations perm1 = Grammar(""" start : a ^ b? ^ c ; a : 'a' ; b : 'b' ; c : 'c' ; WS: '[ \t]+' (%ignore); """) print perm1.parse(' c b a').pretty() print perm1.parse('c a ').pretty() # Permutations with a separator perm2 = Grammar(""" start : a ^ (b|d)? ^ c ^^ ( COMMA | SEMI ) ; a : 'a' ; b : 'b' ; c : 'c' ; d : 'd' ; COMMA : ',' ; SEMI : ';' ; WS: '[ \t]+' (%ignore); """)
user_grammar = Grammar(""" start: logical_or; ?logical_or: logical_or op_or logical_and | logical_and; ?logical_and: logical_and op_and expr | expr; ?expr: un_string_expr | un_expr | bin_expr | '\(' logical_or '\)'; ?bin_expr: (bin_string_expr | bin_passwd_expr | bin_pk_expr | bin_date_expr | bin_bool_expr); un_string_expr: (string_field | password) pr; un_expr: (date_field | bool_field) pr; bin_string_expr: string_field string_op t_string; bin_passwd_expr: password eq t_string; bin_pk_expr: pk eq t_string; bin_date_expr: date_field date_op t_date; bin_bool_expr: bool_field eq t_bool; ?string_op: eq | co | sw; ?date_op: eq | gt | ge | lt | le; ?op_or: '(?i)or'; ?op_and: '(?i)and'; pr: '(?i)pr'; eq: '(?i)eq'; co: '(?i)co'; sw: '(?i)sw'; gt: '(?i)gt'; ge: '(?i)ge'; lt: '(?i)lt'; le: '(?i)le'; ?string_field: username | first_name | last_name | email; ?date_field: date_joined; ?bool_field: is_active; username: '******'; first_name: '(?i)name\.givenName' | '(?i)givenName'; last_name: '(?i)name\.familyName' | '(?i)familyName'; password: '******'; pk: '(?i)id'; date_joined: '(?i)meta\.created' | '(?i)created'; email: '(?i)emails\.value' | '(?i)emails'; is_active: '(?i)active'; t_string: '"(?:[^"\\\\]|\\\\.)*"' ; t_date: '"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[Zz]?"'; t_bool: 'false' | 'true'; SPACES: '[ ]+' (%ignore); """)