コード例 #1
0
ファイル: robobee.py プロジェクト: raphi1790/robobee
def collect_honey(account_connector: AccountConnector, strategy: Strategy,
                  live_trades_connector_name):
    while True:

        strategy.apply(connector=account_connector,
                       live_trades_connector_name=live_trades_connector_name)
        account_connector.update_balance()

        print("updated...")
        time.sleep(30)
コード例 #2
0
ファイル: views.py プロジェクト: dxcv/ForexWeb
def add_strategy(request):
    if request.method == 'GET':
        return render(request, 'Strategy/add.html')
    if request.method == 'POST':
        title = request.POST['Title']
        desc = request.POST['Description']
        code = request.POST['Code']
        if title == '' or code == '':
            return render(request, 'error.html',
                          {'error': 'Please input all the fields'})
        else:
            strategy = Strategy(title=title,
                                user=request.user,
                                description=desc,
                                code=code,
                                status='INITIAL')
            strategy.save()
            return HttpResponseRedirect('/strategy/all/')
コード例 #3
0
def load_strategy():
    import pandas as pd
    data = pd.read_excel('kpi.xlsx',
                         header=None,
                         names=['id', 'content', 'owner_id'],
                         sheet_name='strategy_list')
    for idx, rec in data.iterrows():
        org = Org.query.get(rec['owner_id'])
        s = Strategy(refno=str(rec['id']), org=org, content=rec['content'])
        db.session.add(s)
    db.session.commit()
コード例 #4
0
ファイル: app.py プロジェクト: renejra/full-stack-nd-capstone
    def post_strategy(payload):
        body = request.get_json()
        count = Strategy.query.count()

        try:
            record = Strategy(id=body.get('id'),
                              name=body.get('name'),
                              params=body.get('params').split(', '))
            record.insert()

            response = {
                'success': True,
                'id': record.id,
                'name': record.name,
                'params': record.params,
            }

            return jsonify(response), 200

        except Exception:
            abort(400)
コード例 #5
0
def main(*args, **kwargs):

    # Fetch distinct user IDs from the question data
    user_ids = [
        question.user_id for question in
        Question.select(Question.user_id).group_by(Question.user_id)
    ]

    # Yield a record of all participant responses for each participant
    for user_id in user_ids:

        # Build a new blank record for this participant that we can index by concern index.
        user_record = {
            'strategies': ["No response." for _ in range(len(CONCERNS_SHORTHAND))],
            'evidence': ["No response." for _ in range(len(CONCERNS_SHORTHAND))],
        }

        # Fetch a reference to the pair of packages that the participant used
        package_pair = PackagePair.select().where(PackagePair.user_id == user_id).first()

        # Save all of the "evidence" question responses, in concern order
        for question in Question.select().where(Question.user_id == user_id):
            concern_index = _get_concern_index(user_id, question.question_index)
            user_record['evidence'][concern_index] = question.evidence

        # Save all of the "strategy" question responses, in concern order
        for strategy in Strategy.select().where(Strategy.user_id == user_id):
            concern_index = _get_concern_index(user_id, strategy.question_index)
            user_record['strategies'][concern_index] = strategy.strategy

        # Assemble and return a single row of a CSV file for the user
        response_list = [
            "Search study responses",
            "Participant " + str(user_id),
            package_pair.package1,
            package_pair.package2,
        ]
        response_list.extend(user_record['strategies'])
        response_list.extend(user_record['evidence'])
        yield [response_list]

    raise StopIteration
コード例 #6
0
ファイル: report_job.py プロジェクト: helloWorld141/algotrade
def getViableStrategy(asset_id) -> typing.List[Strategy]:
    '''
    DB access to 'assets' entity, getting the list of viable_strategies
    :param asset_id:
    :return: list of viable strategies
    '''
    ### simulate the DB access for asset strategy mapping
    hardCodedStrat = Strategy(
        'test',
        '3Head',
        {
            'ma_type': 'SMA',  # TODO: make Enum
            'short_allowed': False,
            'ceil_window_size': 10,  # -1 for previous day
            'floor_window_size': 21,  # 0 for case of constant boundary,
            'cur_window_size': 3  # 1 for current price
        })
    assetQuery = lambda doc_name, id, attrs: {'viable_strategies': ['test']}
    stratQuery = lambda doc_name, ids: [hardCodedStrat]
    ########## below part is independent of how to fetch data ########
    stratIds = assetQuery('Asset', asset_id, ['viable_strategies'])
    viableStrategies = stratQuery('Strategy', stratIds)
    return viableStrategies
コード例 #7
0
ファイル: views.py プロジェクト: SQuantTeam/SQuant
def do_backtest(request):
    response = {}
    try:
        # get data from POST request
        user_data = json.loads(request.body)
        start_date = user_data['start_date']
        end_date = user_data['end_date']
        universe = user_data['universe']
        benchmark = user_data['benchmark']
        period = user_data['period']
        pc_method = user_data['pc_method']
        stock_index = user_data['stock_index']
        rank_index = user_data['rank_index']
        amount = user_data['amount']
        strategy_name = user_data['strategy_name']
        # 参数的中文释义字符串
        obvious_param = user_data['obvious_param']

        # user indentity
        phone = request.session.get('phone', None)
        token = request.session.get('token', None)
        email = request.session.get('email', None)
        if phone is None or token is None:
            response['msg'] = 'no connection'
            response['error_num'] = 1
            return JsonResponse(response)
            # phone = DefaultPhone
            # token = DefaultToken
        if email is None:
            response['msg'] = "未登录"
            response['err_num'] = 1
            return JsonResponse(response)

        user = User.objects.get(email=email)
        stra = Strategy.objects.all().filter(user=user, name=strategy_name)
        if stra.count() != 0:
            response['msg'] = "该策略已存在"
            response['err_num'] = 1
            return JsonResponse(response)

        alpha_strategy = AlphaStraGenerator(start_date=start_date,
                                            end_date=end_date,
                                            universe=universe,
                                            benchmark=benchmark,
                                            period=period,
                                            pc_method=pc_method,
                                            stock_index=stock_index,
                                            rank_index=rank_index,
                                            amount=amount,
                                            phone=phone,
                                            token=token,
                                            email=email,
                                            strategy_name=strategy_name)

        # get the folder of strategy
        strategy_path = alpha_strategy.strategy_param_path

        # save strategy params
        alpha_strategy.save_stra()
        # run strategy backtest
        alpha_strategy.run_stra()
        # update database
        stra = Strategy(user=user,
                        name=strategy_name,
                        file_path=strategy_path,
                        remote_report_path=alpha_strategy.remote_report_path,
                        obvious_param=obvious_param)
        stra.save()

        response['result'] = alpha_strategy.remote_report_path
        response['err_num'] = 0

    except Exception, e:
        response['msg'] = str(e)
        response['err_num'] = 2
コード例 #8
0
ファイル: strategy.py プロジェクト: jiffies/aip
def create_strategy(name, content, period, money):
    with DBSession() as session:
        new = Strategy(name=name, content=content, period=period, money=money)
        session.add(new)
コード例 #9
0
for __ppl in ROLES_LIST:
    for __duty in DUTY[__ppl]:
        person[__ppl].add_duty(question[__duty])

# Manually input at each running,
# print("Input duties of each person, splits by space if has multiple duties")
# print("Current question: {}".format(QUESTIONS_LIST))
#
# for ppl in ROLES_LIST:
#     __tmp = input("Duties of {}, split by space: ".format(ppl))
#     __duties = __tmp.split()
#     for __duty in __duties:
#         person[ppl].add_duty(question[__duty])


# print("Input queries of each person, splits by space if has multiple queries")
# print("Current question: {}".format(QUESTIONS_LIST))
# for __ppl in ROLES_LIST:
#     __tmp = input("queries of {}, split by space: ".format(__ppl))
#     __duties = __tmp.split()
#     for __duty in __duties:
#         person[__ppl].add_query(question[__duty])

for __ppl in ROLES_LIST:
    for __query in QUERY[__ppl]:
        person[__ppl].add_query(question[__query])

strategy = Strategy(person_list, question_list).maximized_strategy()
print(strategy)

コード例 #10
0
        code为None,默认代码,否则为模板代码,保存代码
    2,如果strategy_id 不为None,说明为更新策略
    :param account_id:
    :param strategy_id
    :param code
    :param params: {'start': '', 'end': '', 'capital_base': '', 'freq': ''}
    :return:
    """
    if strategy_id:
        #更新策略信息
        try:
            strategy = Strategy.objects.get(id=int(strategy_id))
        except Exception, e:
            return {'status': 'error', 'data': 'no such strategy'}
    else:
        strategy = Strategy()

    try:
        #保存参数, 注意一些必须参数
        strategy.name = params.get('name', strategy.name)
        strategy.start = datetime.strptime(params.get("start", strategy.start),
                                           "%Y-%m-%d")
        strategy.end = datetime.strptime(params.get("end", strategy.end),
                                         "%Y-%m-%d")
        strategy.capital_base = params.get('capital_base',
                                           strategy.capital_base)
        strategy.freq = 'daily' if params.get('freq',
                                              u'每天') == u'每天' else 'minute'
        strategy.account_id = Account.objects.get(id=account_id)
        strategy.visit_id = params.get('visit_id', strategy.visit_id)