示例#1
0
 def makeCountNFA(count, nfa):
     s = FA.gensym()
     ret = FA.Nfa(states=[s],
                  alphabet=[],
                  transitions={},
                  start=s,
                  ends=[s])
     for i in range(count):
         ret = ret.concatenate(nfa)
     return ret
def exprToFA(expr_list):
    fa = FA({0}, set(), {}, 0, {0})
    if ('*' in expr_list):
        return star(expr_list[0])
    elif ('|' in expr_list):
        return exclusiveOr(expr_list)

    for char in expr_list:
        if (type(char) == type(FA())):
            fa = join(fa, char)
        else:
            fa = concat(fa, char)
    return fa.copy()
def exclusiveOr(expr):
    exclusiveList = []
    temp = []
    for char in expr:
        if (char == '|'):
            exclusiveList.append(temp)
            temp = []
            continue
        temp.append(char)
    exclusiveList.append(temp)

    #build FA in each elements in list
    faList = []
    for expr in exclusiveList:
        faList.append(exprToFA(expr))

    counter = 1
    list_end_subFA = []
    fa = FA({0}, set(), {}, 0, {0})
    fa.delta[(fa.q0, '')] = set()  #to prevent key error

    for sub_fa in faList:
        subFA = sub_fa.copy()
        subFA.Q = {i + counter for i in subFA.Q}
        new_delta = {}

        #update delta of subFA
        for i in subFA.delta:
            new_delta[(i[0] + counter,
                       i[1])] = {j + counter
                                 for j in subFA.delta[i]}
        subFA.delta = new_delta

        #update all attr of SubFA
        subFA.q0 += counter
        subFA.F = {list(subFA.F)[0] + counter}

        #join sigma and Q
        fa.Sigma = fa.Sigma | subFA.Sigma
        fa.Q = fa.Q | subFA.Q

        #connect transition
        fa.delta[(fa.q0, '')].add(subFA.q0)  #add empty move to join 2 FA
        fa.delta = {**fa.delta, **subFA.delta}  #combine dict
        list_end_subFA.append(list(subFA.F)[0])  #keep end state(s)

        #update counter
        counter = len(fa.Q)
    #connect to same end state
    fa.Q.add(counter)
    for end in list_end_subFA:  #set new end state
        fa.delta[(end, '')] = {counter}
    fa.F = {counter}

    return fa.copy()
示例#4
0
    def concatenate(self, other):
        start = self.start
        al = self.al + [a for a in other.al if a not in self.al]

        trans = self.trans
        otn = {}
        states = self.states
        for state in other.states:
            if state in self.states:
                c = FA.gensym()
                while c in self.states:
                    c = FA.gensym()
            else:
                c = state
            states.append(c)
            otn[state] = c

        ends = [otn[end] for end in other.ends]

        for state in other.states:
            ns = otn[state]
            if ns not in trans:
                trans[ns] = {}
            if state in other.trans:
                for sym, finstates in other.trans[state].items():
                    if sym not in trans[ns]:
                        trans[ns][sym] = []
                    for finstate in finstates:
                        nfs = otn[finstate]
                        if nfs not in trans[ns][sym]:
                            trans[ns][sym].append(nfs)

        nos = otn[other.start]
        for f in self.ends:
            if f not in trans:
                trans[f] = {}
            if "" not in trans[f]:
                trans[f][""] = []
            if nos not in trans[f][""]:
                trans[f][""].append(nos)

        return IterNfa(states, al, trans, start, ends)
示例#5
0
    def union(self, other):
        al = self.al + [a for a in other.al if a not in self.al]

        otn = {}
        states = self.states
        for state in other.states:
            if state in self.states:
                c = FA.gensym()
                while c in self.states:
                    c = FA.gensym()
            else:
                c = state
            states.append(c)
            otn[state] = c
        ends = self.ends + [otn[f] for f in other.ends]

        start = 0
        while start in states:
            start += 1

        states.append(start)

        trans = self.trans
        for state in other.states:
            ns = otn[state]
            if ns not in trans:
                trans[ns] = {}
            if state in other.trans:
                for sym, finstates in other.trans[state].items():
                    if sym not in trans[ns]:
                        trans[ns][sym] = []
                    for finstate in finstates:
                        nfs = otn[finstate]
                        if nfs not in trans[ns][sym]:
                            trans[ns][sym].append(nfs)

        trans[start] = {"": [self.start, otn[other.start]]}

        return IterNfa(states, al, trans, start, ends)
示例#6
0
    def test_find_glocal_maximum_for_nonsmooth_multipeak_function(self):
        nonsmooth_multipeak_function_wrapper = NonsmoothMultipeakFunctionWrapper(
        )

        number_of_variables = 2
        objective = "maximization"

        firefly_algorithm = FA(nonsmooth_multipeak_function_wrapper,
                               number_of_variables, objective)

        number_of_fireflies = 10
        maximun_generation = 10
        randomization_parameter_alpha = 0.2
        absorption_coefficient_gamma = 1.0

        result = firefly_algorithm.search(
            number_of_fireflies=number_of_fireflies,
            maximun_generation=maximun_generation,
            randomization_parameter_alpha=randomization_parameter_alpha,
            absorption_coefficient_gamma=absorption_coefficient_gamma)
        print("the result[0]", result)
        print("the result[0]", result["best_decision_variable_values"][0])
        print("the result[1]", result["best_decision_variable_values"][1])
示例#7
0
 def combine_s_a_f(self, enfa):
     ls = len(self.state)
     # combine states
     self.state += [i + ls for i in enfa.state]
     enfa.init_state += ls
     enfa.final_state = [i + ls for i in enfa.final_state]
     # combine alphabet
     self.alphabet += enfa.alphabet
     self.alphabet = FA.sls(self.alphabet)
     # combine t_func
     temp_t_func_list = []
     for (k, v) in enfa.t_func_list.items():
         temp_t_func_list.append(((k[0] + ls, k[1] + ls), v))
     self.t_func_list = dict(list(self.t_func_list.items()) + temp_t_func_list)
示例#8
0
    def star(self):
        trans = self.trans

        al = self.al
        states = self.states
        start = 0
        while start in states:
            start += 1

        start = FA.gensym()
        while start in self.states:
            start = FA.gensym()

        ends = [start]

        for end in self.ends:
            if end not in trans:
                trans[end] = {}
            if "" not in trans[end]:
                trans[end][""] = []
            if start not in trans[end][""]:
                trans[end][""].append(start)

        trans[start] = {"": [self.start]}

        if start not in states:
            states.append(start)

        if start not in ends:
            ends.append(start)

        return IterNfa(states=states,
                       alphabet=al,
                       transitions=trans,
                       start=start,
                       ends=ends)
示例#9
0
    def __init__(self, user='******', robot_name='FA-20'):
        self.straight_control_data = []

        self.full_power = 100
        self.one_block_distance = 10  #180 for 83 #175 for 20
        self.right_angle_turn = 90  #87 for 20 #90 for 83
        self.degree_adjustment = 4
        self.open_adjacency_max = 25
        self.needs_adjustment_min = 30
        self.straight_enough_margin = 100
        self.tooFarFromWall = 200

        user_ports = pd.read_csv(RobotControl.port_file)
        port = user_ports.loc[user, robot_name]

        self.robot = FA.Create()
        self.robot.ComOpen(port)  #83 is 16   #720 is 15
        self.robot.Forwards(30)
示例#10
0
def parseStock(oneStock):
    symbol = oneStock["symbol"]
    data = getStockInfoData(stockInfoAPI, oneStock)

    try:
        #正常的操作#获取最新价格
        oneStock['current'] = data[symbol]['current']
    except:
        #发生异常,执行这块代码
        print '数据解析出错,可能是cookie问题,请尝试更新'

    #获取股票的近季度的利润情况
    oneStock['profit'] = FA.parseIncstatementData(symbol)

    #获取pe
    oneStock['pe_lyr'] = data[symbol]['pe_lyr']
    oneStock['pe_ttm'] = data[symbol]['pe_ttm']

    #获取最新pb
    latestPB = data[symbol]['pb']
    oneStock['latestPB'] = latestPB
    #根据pb获取配置额度
    money = getMoney(latestPB)
    oneStock['canUseMoney'] = money
    #是否可以继续配置
    if money - oneStock['latestCost'] > 0:
        canContinueBuy = True
        oneStock['canContinueBuy'] = canContinueBuy
    else:
        canContinueBuy = False
        oneStock['canContinueBuy'] = canContinueBuy
    #如果可以配置的话,还能配置多少股
    if canContinueBuy:
        nowCanUse = money - oneStock['latestCost']
        nowCanBuyStockNumber = nowCanUse / float(data[symbol]['current'])
        nowCanBuyStockNumber = int(round(nowCanBuyStockNumber, 0))
        nowCanBuyStockNumber2 = int(round(nowCanBuyStockNumber / 100)) * 100
        oneStock['nowCanUse'] = nowCanUse
        oneStock['nowCanBuyStockNumber'] = nowCanBuyStockNumber
        oneStock['nowCanBuyStockNumber2'] = nowCanBuyStockNumber2
    else:
        oneStock['nowCanUse'] = 0
        oneStock['nowCanBuyStockNumber'] = 0
        oneStock['nowCanBuyStockNumber2'] = 0
示例#11
0
def process_finite_automaton(json):
    fa = FA.FiniteAutomaton(json)
    while True:
        print_fa_menu()
        option = input()
        if option == "0":
            break
        elif option == "1":
            print(fa.get_states())
        elif option == "2":
            print(fa.get_alphabet())
        elif option == "3":
            print(fa.get_transitions())
        elif option == "4":
            print(fa.get_final_states())
        elif option == "5":
            print(fa.convert())
        else:
            print("Invalid option")
示例#12
0
文件: main.py 项目: PugnaBogdan/FLCD
class main:

    finiteAutomata = f.FA()

    def readFile(self):

        self.finiteAutomata.getInput()

    def printFA(self):
        if self.finiteAutomata.getOK():
            print(self.finiteAutomata)
        else:
            print("read file first")

    def checkSequence(self):
        seq = input("type sequence here: ")
        print(self.finiteAutomata.checkSequence(seq))

    def menu(self):
        print("1 - read input")
        print("2 - print fa")
        print("3 - check sequence")

    def run(self):
        menuChoices = {
            '1': self.readFile,
            '2': self.printFA,
            '3': self.checkSequence
        }
        exit = False
        while True:
            self.menu()
            choice = input("-")
            if choice in menuChoices.keys():
                menuChoices[choice]()
            else:
                break
示例#13
0
    #max_size = max(left_side, right_side)
    #full_power = 100
    #robot.SetMotors(left_side/max_size * full_power, right_side/max_size * full_power)


def explore():
    front = robot.ReadIR(2)
    left = robot.ReadIR(0)
    right = robot.ReadIR(4)

    print("Left: " + str(left) + ", front: " + str(front) + ", Right: " +
          str(right))


#Initialize Connection and open port
robot = FA.Create()
robot.ComOpen(16)
#83 is 16
#other is 15

full_power = 100
#Test robot controls

print("Let's Go!")
#cmd_stack = [Directions.forwards, Directions.left, Directions.forwards, Directions.left, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards]
#cmd_stack = [Directions.forwards, Directions.right, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards, Directions.forwards]
#reverse_stack = convertFromInstructionsToMovement(cmd_stack)
#adjustStraight()
#robot.Right(180)
#convertFromInstructionsToMovement(reverse_stack)
explore()
        def invest(self):
            self.name.set("Loading...")
            
            self.name_label.update()
            
            ticker = self.ticker.get() in ticker_to_name_dict
            if self.ticker.get() in ticker_to_name_dict:
                print("reset")
                predictions = fa.company_worth_investing(self.ticker.get(), iters=self.dayn.get())
            else:
                predictions = fa.company_worth_investing(name_to_ticker(self.ticker.get().lower()), iters=self.dayn.get())

            if predictions != None:
                n = ""
                if ticker:
                    n = self.ticker.get()
                else:
                    n = name_to_ticker(self.ticker.get().lower())
                info = fa.get_company_info(n)
                
                real = list(map(eval, info['history'])) + [info['Current']]
                pred = list(map(lambda x: x[5], predictions))
                
                self.subplot.clear()
                self.subplot.plot(real + pred, zorder=1)
                
                x = range(len(real+pred))
                y = real+pred
                def choose_color(i):
                    if i >= len(real):
                        return '#ff0000'
                    else:
                        return '#0000ff'
                    
                c = [choose_color(i) for i in x]
                self.subplot.scatter(x, y, c=c, s=12, zorder=2, edgecolor='white')
                
                self.subplot.set_xlim([0, len(real+pred)])
                
            if predictions == None:
                self.name.set("Company '"+self.ticker.get()+"' not found.")
                self.info.set("")
                self.subplot.cla()
            else:
                n, r, b, pi, cpps, ppps = predictions[-1]
                self.name.set("\n"+ticker_to_name_dict[n].title()
                                .replace("Stk", "").replace(" Common Stock", "").replace(" Com", "") + " ("+n+") \n")
                self.risk.set("Risk Level: " + r.upper() + "\n")
                if r == 'low':
                    self.risk_label.config(fg="green")
                elif r == 'medium':
                    self.risk_label.config(fg="#CCCC00")
                elif r == 'high':
                    self.risk_label.config(fg="red")
                    
                self.info.set("Current Price per Share: $" + str(round(cpps, 2)) + "\n" + \
                              "Beta: " + str(b) + "\n\n\n")

                self.info_list.delete(0, END)
                for n, r, b, pi, cpps, ppps in predictions:
                    self.info_list.insert(END, "Increase: " + str(round(pi*100, 2)) + "%" + ", " + \
                                               "Predicted Price: $" + str(round(ppps, 2)) + "\n\n")
示例#15
0
 def add_alphabet(self, inp):
     self.alphabet.append(inp)
     self.alphabet = FA.sls(self.alphabet)
示例#16
0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 21:20:59 2019

@author: Rui Kong
"""
import FA
if __name__ == "__main__":

    bound = np.tile([[-600], [600]], 25)
    fa = FA(60, 25, bound, 200, [1.0, 0.000001, 0.6])
    fa.solve()
示例#17
0
 def get_all_acceptors():
     return [
         FiniteStateMachine(*FA.init_punctuation_FA()),
         FiniteStateMachine(*FA.init_relop_FA()),
         FiniteStateMachine(*FA.init_intent_FA()),
         FiniteStateMachine(*FA.init_number_FA()),
         FiniteStateMachine(*FA.init_string_FA()),
         FiniteStateMachine(*FA.init_multiline_string_FA()),
         FiniteStateMachine(*FA.init_operation_FA()),
         FiniteStateMachine(*FA.init_id_FA()),
         FiniteStateMachine(
             *FA.init_key_word_FA('class', Tokens_Enum.CLASS)),
         FiniteStateMachine(*FA.init_key_word_FA('from', Tokens_Enum.FROM)),
         FiniteStateMachine(
             *FA.init_key_word_FA('import', Tokens_Enum.IMPORT)),
         FiniteStateMachine(
             *FA.init_key_word_FA('while', Tokens_Enum.WHILE)),
         FiniteStateMachine(*FA.init_key_word_FA('for', Tokens_Enum.FOR)),
         FiniteStateMachine(*FA.init_key_word_FA('in', Tokens_Enum.IN)),
         FiniteStateMachine(*FA.init_key_word_FA('if', Tokens_Enum.IF)),
         FiniteStateMachine(*FA.init_key_word_FA('else', Tokens_Enum.ELSE)),
         FiniteStateMachine(*FA.init_key_word_FA('elif', Tokens_Enum.ELIF)),
         FiniteStateMachine(
             *FA.init_key_word_FA('raise', Tokens_Enum.RAISE)),
         FiniteStateMachine(
             *FA.init_key_word_FA('except', Tokens_Enum.EXCEPT)),
         FiniteStateMachine(*FA.init_key_word_FA('None', Tokens_Enum.NONE)),
         FiniteStateMachine(
             *FA.init_key_word_FA('return', Tokens_Enum.RETURN)),
         FiniteStateMachine(*FA.init_key_word_FA('def', Tokens_Enum.DEF)),
         FiniteStateMachine(*FA.init_key_word_FA('and', Tokens_Enum.AND)),
         FiniteStateMachine(*FA.init_key_word_FA('or', Tokens_Enum.OR)),
         FiniteStateMachine(*FA.init_key_word_FA('not', Tokens_Enum.NOT)),
     ]
 def copy(self):
     return FA(self.Q.copy(), self.Sigma.copy(), self.delta.copy(), self.q0,
               self.F.copy())
示例#19
0
def getAllData(page=0, stockArr=[]):

    data = {"count": 1, "list": [{"symbol": symbolCode, "name": symbolCode}]}

    arr = data["list"]

    #在函数中使用全局变量需要这里声明
    global dealNum

    # 股票总条数
    count = data["count"]
    totalPages = int(math.ceil(count / 30))

    #处理一页中,各个股票的数据
    for one in arr:

        #用来统计进度
        dealNum = dealNum + 1
        perc = round((dealNum / count), 3) * 100

        name = one['name']
        symbol = one['symbol']

        print('您查询的股票是:' + name)
        print(
            '---------------------------------------------------------------------------------------------------------------'
        )

        #判断股票是否存在
        # cursor = dataBase.getStock(symbol);
        # if cursor.count()>=1:
        #     for document in cursor:
        #         oneStock = document
        #     print(name+u' 已经存在数据库中,不再处理')
        #     print('--------------------------------------------------------------------------------------------------------------- '+str(perc)+'%')
        #     stockArr.append(oneStock);
        #     continue

        #非常核心的数据提炼部分1
        lows = getLowPriceArr(symbol, 6)
        #这里使用第2个接口
        #提炼低点占比
        percents = getSellPercent(lows)
        #提炼低点占比
        continueDays = lows[2]
        continueDaysText = lows[3]
        #提炼最近一天涨跌百分比 和 连续几天的涨跌百分比
        upOrDownPercent = lows[4]
        upOrDownContinuePercent = lows[5]

        #非常核心的数据提炼部分2
        info = getStockInfoData(stockInfoAPI, config3, symbol)
        #这里使用第3个接口

        #需要再增加一个key,用来排序
        averagePrecent = percents[1]
        #需要再增加一个key,用来排序
        lastPrecent = percents[0][0]

        #新增 停牌信息
        halt = info['halt']
        #新增 财务分析
        cashFlow = FA.parseCfstatementData(symbol)
        profit = FA.parseIncstatementData(symbol)

        #新增 名字(本来是第一个接口中就有的,因为改了,所以再获取下)
        nameStr = info['nameStr']

        #完成一个完整的股票分析
        oneStock = Stock(
            name,
            symbol,
            lows,
            percents,
            info,
            averagePrecent,
            lastPrecent,
            continueDays,
            continueDaysText,
            upOrDownPercent,
            upOrDownContinuePercent,
            halt,
            cashFlow,
            profit,
            nameStr,
        )

        #屏幕输出
        print(u"【" + oneStock['nameStr'] + u"】")
        print(oneStock['lows'][3].encode("utf-8") + ',合计涨/跌百分比:' +
              str(oneStock['lows'][5]) + '%,当天' + str(oneStock['lows'][4]) +
              '%')
        print('推荐购买' + str(oneStock['info']['buyNum2']) + '(' +
              str(oneStock['info']['buyNum']) + ')')
        print('成本为 ' + str(oneStock['info']['buyNum2'] * oneStock['lows'][1]) +
              ' 元(每股 ' + str(oneStock['lows'][1]) + ')')

        print('【PB/TTM/LYR】' + str(oneStock['info']['pb']) + '/' +
              str(oneStock['info']['pe_ttm']) + '/' +
              str(oneStock['info']['pe_lyr']))
        print('【EPS/每股净资产/ROE(季)/ROE(年)】' + str(oneStock['info']['eps']) +
              '/' + str(oneStock['info']['net_assets']) + '/' +
              str(oneStock['info']['roe'])) + '%/' + str(
                  oneStock['info']['roe2']) + '%'

        print('N年内低点 ' + str(oneStock['lows'][0]))
        print('N年内卖点占比 ' + str(oneStock['percents'][0]) + ',平均 ' +
              str(oneStock['percents'][1]))
        print('总股本' + str(oneStock['info']['totalShares2']) + '亿')
        print('最近季度利润' + str(oneStock['profit'][1]) + '亿')

        print(oneStock['profit'][0])
        print(oneStock['cashFlow'][0])
        print(oneStock['cashFlow'][1])
        print(oneStock['cashFlow'][2])
        print(
            '--------------------------------------------------------------------------------------------------------------- '
            + str(perc) + '%')

        #保存到数据库
        #dataBase.save(oneStock);

        #并保存到全局对象中(这个其实没啥用呢)
        #补充,现在有用了,最后的时候,用来作为全部数据导出到txt
        #为什么不是和数据库存入一样,在每一次中完成,而选择了最后一次性处理
        #因为主要是为了解决排序的问题
        stockArr.append(oneStock)

    return stockArr
示例#20
0
        def tonfa(self):
            def makeCountNFA(count, nfa):
                s = FA.gensym()
                ret = FA.Nfa(states=[s],
                             alphabet=[],
                             transitions={},
                             start=s,
                             ends=[s])
                for i in range(count):
                    ret = ret.concatenate(nfa)
                return ret

            if self.type == self.CHAR_SECTION:
                return FA.Nfa(states=[0, 1],
                              alphabet=[self.content],
                              start=0,
                              ends=[1],
                              transitions={0: {
                                  self.content: [1]
                              }})

            elif self.type == self.SET_SECTION:
                if len(self.content) == 0:
                    raise ValueError(
                        "Set Section is given an empty set of regexs")
                else:
                    unionreg = self.content[0].tonfa()
                    for section in self.content[1:]:
                        unionreg = unionreg.union(section.tonfa())
                    return unionreg

            elif self.type == self.SEQUENCE_SECTION:
                if len(self.content) == 0:
                    raise ValueError(
                        "Sequence Section is given an empty set of regexs")
                else:
                    concatreg = self.content[0].tonfa()
                    for section in self.content[1:]:
                        concatreg = concatreg.concatenate(section.tonfa())
                    return concatreg

            elif self.type == self.STAR_SECTION:
                if self.content == None:
                    raise ValueError("Star Section has no preceding regex")
                else:
                    return self.content.tonfa().copy().star()

            elif self.type == self.PLUS_SECTION:
                if self.content == None:
                    raise ValueError("Plus Section has no preceding regex")
                else:
                    return self.content.tonfa().concatenate(
                        self.content.tonfa().star())

            elif self.type == self.QUESTION_SECTION:
                if self.content == None:
                    raise ValueError("Plus Section has no preceding regex")
                else:
                    s = FA.gensym()
                    return self.content.tonfa().union(
                        FA.Nfa(states=[s],
                               alphabet=[],
                               transitions={},
                               start=s,
                               ends=[s]))

            elif self.type == self.REPEAT_SECTION:

                if self.content == None:
                    raise ValueError("Repeat Section has no preceding regex")
                if self.andmore == None:
                    raise ValueError("Repeat Section has no andmore arg")
                if self.start == None:
                    raise ValueError(
                        "Repeat Section has no repeat start number")
                if self.start <= 0:
                    raise ValueError(
                        "Repeat Section has an invalid repeat start number")
                if self.end is not None and self.end <= 0:
                    raise ValueError(
                        "Repeat Section has an invalid repeat start number")

                if self.end == None:  # we only have a start
                    if self.andmore:  # we want more than that number of repetitions
                        cnfa = self.content.tonfa()
                        repnfa = makeCountNFA(self.start, cnfa)
                        return repnfa.concatenate(cnfa.star())
                    else:  # we only want that number of repetitions
                        cnfa = self.content.tonfa()
                        return makeCountNFA(self.start, cnfa)

                else:
                    s = FA.gensym()
                    ret = FA.Nfa(states=[s],
                                 alphabet=[],
                                 transitions={},
                                 start=s,
                                 ends=[s])
                    cnfa = self.content.tonfa()
                    for i in range(self.start, self.end + 1):
                        repeatnfa = makeCountNFA(i, cnfa)
                        ret = ret.union(repeatnfa)
                    return ret

            else:
                raise RuntimeError("Unknown Section type: ", self.type)
import FA
import time

fa = FA.Create()

fa.ComOpen(6)

fa.LCDClear()
treshold = 3000
pos = "A"
movement = 5

while True:
    illumination = fa.ReadLight()
    print(illumination)

    if (illumination > treshold):
        pos = "A"
        fa.Forwards(100)

    else:
        if pos == "A":
            pos = "B"
            fa.Left(movement)
        elif pos == "B":
            pos = "C"
            fa.Right(movement)
        elif pos == "C":
            pos = "D"
            fa.Right(movement)
        else:
示例#22
0
    print('\nSymbol Table:\n')
    for i in range(len(ST)):
        print("Nr: {} Type: {} Value: {}.".format(i, ST[i][0], ST[i][1]))


def print_PIF(PIF):

    print('\nProgram Internal Form:\n')
    for i in range(len(PIF)):
        print("Token: {} Position in ST: {}".format(PIF[i][0], PIF[i][1]))


if __name__ == '__main__':

    #Creating FA for Identifiers
    identifierFA = FA.FA(2)
    identifierFA.register_accept(1)
    identifierFA.register(0, "_", 1)
    for i in string.ascii_letters:
        identifierFA.register(0, i, 1)
        identifierFA.register(1, i, 1)
    for i in string.digits:
        identifierFA.register(1, i, 1)
    identifierFA.register(1, "_", 1)

    #Creating FA for Constants
    constantsFA = FA.FA(3)
    constantsFA.register_accept(1)
    constantsFA.register_accept(2)
    constantsFA.register(0, "-", 1)
    for i in ("123456789"):
示例#23
0
def getAllData(page=0,stockArr=[]):

    json = getScreenerData(screenerAPI,config,page);    #这里使用第1个接口

    try:
        #正常的操作
        data = Payload(json);
    except:
        #发生异常,执行这块代码
        print '【xm】股票筛选接口崩坏!'
        print json

    if(~~hasattr(data,'list')==0):
        print('获取数据的接口似乎有点问题哦=================> 请尝试更新cookie!');

    arr  = data.list;

    #在函数中使用全局变量需要这里声明
    global dealNum;

    # 股票总条数
    count = data.count;
    totalPages = int(math.ceil(count/30))
    if page == 0:
        page = 1;
    else:
        page = page+1;
        #处理一页中,各个股票的数据
        for one in arr:

            #用来统计进度
            dealNum = dealNum + 1;
            perc = round((dealNum/count),3)*100;

            name = one['name'];
            symbol = one['symbol'];

            #白云山A,已经退市不在处理
            if symbol=='SZ000522':
                print('============ 已经退市,跳过!===========')
                continue

            #判断股票是否存在
            cursor = dataBase.getStock(symbol);
            if cursor.count()>=1:
                for document in cursor:
                    oneStock = document
                print(name+u' 已经存在数据库中,不再处理')
                print('--------------------------------------------------------------------------------------------------------------- '+str(perc)+'%')
                stockArr.append(oneStock);
                continue


            #非常核心的数据提炼部分1
            lows     = getLowPriceArr(symbol,6);                      #这里使用第2个接口
            #提炼低点占比
            percents = getSellPercent(lows);
            #提炼低点占比
            continueDays     = lows[2];
            continueDaysText = lows[3];
            #提炼最近一天涨跌百分比 和 连续几天的涨跌百分比
            upOrDownPercent         = lows[4];
            upOrDownContinuePercent = lows[5];

            #非常核心的数据提炼部分2
            info     = getStockInfoData(stockInfoAPI,config3,symbol); #这里使用第3个接口

            #需要再增加一个key,用来排序
            averagePrecent = percents[1];
            #需要再增加一个key,用来排序
            lastPrecent    = percents[0][0];

            #新增 停牌信息
            halt = info['halt']
            #新增 财务分析
            cashFlow = FA.parseCfstatementData(symbol)
            profit = FA.parseIncstatementData(symbol)

            messages = industryConfig.get(symbol) # Check for key existence
            if messages is None:                  # Check if key is there, but None
                industryId   = 9999
                industryName = "未分类"
            else:
                industryId   = industryConfig[symbol]['id']
                industryName = industryConfig[symbol]['industry']

            messages2 = stockPoolConfig.get(symbol) 
            if messages2 is None:                 
                stockPoolInfo = {}
            else:
                stockPoolInfo = stockPoolConfig[symbol]
            


            #完成一个完整的股票分析
            oneStock = Stock(
                name,
                symbol,
                lows,
                percents,
                info,
                averagePrecent,
                lastPrecent,
                continueDays,
                continueDaysText,
                upOrDownPercent,
                upOrDownContinuePercent,
                halt,
                cashFlow,
                profit,
                industryId,
                industryName,

                stockPoolInfo,
            );

            #屏幕输出
            print(oneStock['name'])
            print(oneStock['info'])
            print(oneStock['lows'])
            print(oneStock['percents'])
            print(oneStock['continueDaysText'] + u',合计涨/跌百分比:' + str(oneStock['upOrDownContinuePercent']) )
            print(oneStock['profit'][0])
            print(oneStock['cashFlow'][0])
            print(oneStock['cashFlow'][1])
            print(oneStock['cashFlow'][2])
            print('--------------------------------------------------------------------------------------------------------------- '+str(perc)+'%')

            #保存到数据库
            dataBase.save(oneStock);

            #并保存到全局对象中(这个其实没啥用呢)
            #补充,现在有用了,最后的时候,用来作为全部数据导出到txt
            #为什么不是和数据库存入一样,在每一次中完成,而选择了最后一次性处理
            #因为主要是为了解决排序的问题
            stockArr.append(oneStock);

    if page<=totalPages:
        getAllData(page,stockArr);

    return stockArr;
示例#24
0
# -*- coding: utf-8 -*-
import numpy as np
import FA
import data

#-------------------
# 1. データの作成
myData = data.unsupervised()
myData.makeData(dataType=1)
#-------------------

#-------------------
# 2. 主因子法による因子の抽出
myModel = FA.FA(myData.X)
myModel.extractFactor(lowerDim=2)
#-------------------

#-------------------
# 3. 因子の表示
print(f"因子負荷量:\nW=\n{np.round(myModel.W,decimals=2)}")
print(f"独自因子の分散:\nE=\n{np.round(myModel.E,decimals=2)}")
#-------------------

#-------------------
# 4. 因子のプロット
# 主成分得点のプロット(2次元への次元削減時のみ実行可)
if myModel.lowerDim == 2:
    myModel.drawRadarChart(labels=myData.labels,
                           fName=f"../results/FA_result_{myData.dataType}.pdf")
#-------------------