Example #1
0
def render_custom_template(request):
    # TODO: Check user
    user = User.objects.get(id=request.user.id)
    container_id = request.POST['container_id'][0] if isinstance(request.POST['container_id'], list) else request.POST['container_id']
    container_type = request.POST['container_type'][0] if isinstance(request.POST['container_type'], list) else request.POST['container_type']
    container_class = container_type + '_CLASS'
    container_template = request.POST['container_template']
    widget_index = request.POST['widget_index'][0] if isinstance(request.POST['widget_index'], list) else request.POST['widget_index']
    widget_title = request.POST['widget_title'][0] if isinstance(request.POST['widget_title'], list) else request.POST['widget_title']
    # TODO: Handle error
    effective_class_name = Attributes.objects.get(identifier=container_class, active=True).name
    effective_class = classes.my_class_import(effective_class_name)

    container = effective_class.objects.get(id=container_id)
    
    
    if container_type=='CONT_MAIL_CAMPAIGN':
        # TODO Assign also application custom data
        custom_data = get_mailgun_data(container.external_id)
        for contact_id in custom_data['persons'].keys() + custom_data['companies'].keys():
            if contact_id!='companies':
                instance = get_effective_instance(Container.objects.get(id=contact_id))
                if instance.type.identifier=='CONT_PERSON':
                    custom_data['persons'][contact_id]['container'] = instance
                else:
                    custom_data['companies'][contact_id]['container'] = instance
    else:
        custom_data = get_security_information(container)
    context = {'title': widget_title, 'index':widget_index, 'container': container, 'custom_data': custom_data, 'labels': {label.identifier: label.field_label for label in FieldLabel.objects.filter(langage='en')}}
    return render(request, container_template, context)
Example #2
0
def compute_account_details(portfolio, operation, spots, accounts_history, current_account_key,
                            previous_date, key_date, is_source, target_used):
    if not accounts_history.has_key(current_account_key):
        accounts_history[current_account_key] = {}
    if previous_date.has_key(current_account_key):
        accounts_history[current_account_key][key_date] = copy.deepcopy(accounts_history[current_account_key][previous_date[current_account_key]])
        if key_date!=previous_date[current_account_key]:
            accounts_history[current_account_key][key_date]['fx_pnl'] = 0.0
            accounts_history[current_account_key][key_date]['mvt_pnl'] = 0.0
            accounts_history[current_account_key][key_date]['mvt_no_pnl'] = 0.0
            accounts_history[current_account_key][key_date]['mvt_pnl_pf'] = 0.0
            accounts_history[current_account_key][key_date]['mvt_no_pnl_pf'] = 0.0
    else:
        accounts_history[current_account_key][key_date] = {'assets': 0.0, 'assets_pf': 0.0,'mvt_pnl': 0.0, 'mvt_no_pnl': 0.0, 'mvt_pnl_pf': 0.0, 'mvt_no_pnl_pf': 0.0}
    spot_pf = 1.0
    if is_source:
        wrk_currency = operation.source.currency.short_name
    else:
        wrk_currency = operation.target.currency.short_name
    if wrk_currency!=portfolio.currency.short_name and not spots.has_key(wrk_currency):
        spot_track = get_exchange_rate(wrk_currency, portfolio.currency.short_name)
        if not spots.has_key(wrk_currency):
            spots[wrk_currency] = {}
        spots[wrk_currency][portfolio.currency.short_name] = spot_track
    if wrk_currency!=portfolio.currency.short_name and spots.has_key(wrk_currency) and spots[wrk_currency].has_key(portfolio.currency.short_name):
        value = get_closest_value(spots[wrk_currency][portfolio.currency.short_name], operation.value_date)
        if value!=None:
            spot_pf = value['value']
    if is_source:
        multiplier = -1.0 if target_used or operation.operation_type.identifier in ['OPE_TYPE_BUY', 'OPE_TYPE_BUY_FOP'] else 1.0
    else:
        multiplier = operation.spot if operation.spot!=None else 1.0
    computed_amount = operation.amount * multiplier
    accounts_history[current_account_key][key_date]['assets'] += computed_amount
    accounts_history[current_account_key][key_date]['assets_pf'] = accounts_history[current_account_key][key_date]['assets'] * spot_pf
    accounts_history[current_account_key][key_date]['spot_pf'] = spot_pf
    if operation.operation_type.identifier not in ['OPE_TYPE_BUY', 'OPE_TYPE_SELL', 'OPE_TYPE_BUY_FOP', 'OPE_TYPE_SELL_FOP']:
        operation.source = get_effective_instance(operation.source)
        operation.target = get_effective_instance(operation.target)
        if (operation.source==None or (operation.source.type.identifier=='CONT_ACCOUNT' and not operation.source.account_type.identifier=='ACC_FORWARD')) and (operation.target==None or (operation.target.type.identifier=='CONT_ACCOUNT' and not operation.target.account_type.identifier=='ACC_FORWARD')):
            accounts_history[current_account_key][key_date]['mvt_pnl' if operation.operation_type.identifier in ['OPE_TYPE_FEES','OPE_TYPE_ACCRUED_PAYMENT','OPE_TYPE_COUPON', 'OPE_TYPE_DIVIDEND'] else 'mvt_no_pnl'] += computed_amount
            accounts_history[current_account_key][key_date]['mvt_pnl_pf' if operation.operation_type.identifier in ['OPE_TYPE_FEES','OPE_TYPE_ACCRUED_PAYMENT','OPE_TYPE_COUPON', 'OPE_TYPE_DIVIDEND'] else 'mvt_no_pnl_pf'] += computed_amount * spot_pf
    previous_date[current_account_key] = key_date
    previous_date[current_account_key] = key_date
Example #3
0
def import_external_data(data_source, data_type):
    LOGGER.info('Loading working data')
    query = QUERIES[data_source][data_type]['query']
    group_by = QUERIES[data_source][data_type]['group_by']
    external_alias = Attributes.objects.get(identifier='ALIAS_' + data_source.upper())
    
    if data_type=='securities':
        bloomberg_alias = Attributes.objects.get(identifier='ALIAS_BLOOMBERG')
        isin_alias = Attributes.objects.get(identifier='ALIAS_ISIN')
        sec_container_type = Attributes.objects.get(identifier='CONT_SECURITY')
        fund_container_type = Attributes.objects.get(identifier='CONT_FUND')
        bond_container_type = Attributes.objects.get(identifier='CONT_BOND')
        stock_container_type = Attributes.objects.get(identifier='CONT_SECURITY')
        security_type = Attributes.objects.get(identifier='SECTYP_SECURITY')
        fund_type = Attributes.objects.get(identifier='SECTYP_FUND')
        bond_type = Attributes.objects.get(identifier='SECTYP_BOND')
        stock_type = Attributes.objects.get(identifier='SECTYP_STOCK')

        daily = Attributes.objects.get(identifier='FREQ_DAILY', active=True)
        
        bloomberg_provider = get_bloomberg_provider()
        
        universe = get_universe_from_datasource(data_source)
        
        LOGGER.info('Cleaning already imported aliases for ' + data_source)
        securities = SecurityContainer.objects.filter(aliases__alias_type__short_name=data_source.upper()).distinct()
        for security in securities:
            for alias in security.aliases.all():
                if alias.alias_type.short_name==data_source.upper():
                    security.aliases.remove(alias)
            security.save()
        LOGGER.info('\tCleaning done')
    
    LOGGER.info('Importing ' + str(data_type) + ' from ' + str(data_source))
    LOGGER.info('Using query:' + str(query))
    results = dbutils.query_to_dicts(query, data_source)
    database = getattr(client, data_source)
    database[data_type].drop()
    
    all_tickers = []
    
    for result in results:
        # Clean the data        
        new_entry = convert_to_mongo(result)
        # LOGGER.info('Removing entries with name '  + new_entry[QUERIES[data_source][data_type]['name']])
        # SecurityContainer.objects.filter(name=new_entry[QUERIES[data_source][data_type]['name']]).delete()
        for group_id in group_by:
            if new_entry[group_id]!=None and new_entry[group_id]!='':
                # LOADING INTO MONGO
                LOGGER.info('Adding entry [' + group_id + '=' + str(new_entry[group_id]) + "]")
                new_entry['_id'] = new_entry[group_id]
                if QUERIES[data_source][data_type].has_key('joins'):
                    for join_info in QUERIES[data_source][data_type]['joins']:
                        values = [new_entry[identifier] for identifier in join_info['on']]
                        underlying_query = join_info['query']
                        for value in values:
                            underlying_query = underlying_query%value
                        new_entry[join_info['name']] = []
                        under_results = dbutils.query_to_dicts(underlying_query, data_source)
                        for under_result in under_results:
                            LOGGER.info('\tAdding underlying [' + join_info['name'] + ', ' + group_id + '=' + str(new_entry[group_id]) + "]")
                            # Clean the data        
                            under_entry = convert_to_mongo(under_result)
                            new_entry[join_info['name']].append(under_entry)
                try:
                    database[data_type].save(new_entry)
                except DuplicateKeyError:
                    LOGGER.error("The following entry already exists:")
            # CONVERTING TO FINALE
            if group_id==QUERIES[data_source][data_type]['EXTERNAL'] and data_type=='securities':
                name_field = QUERIES[data_source][data_type]['name']
                short_name_field = QUERIES[data_source][data_type]['short_name']
                bloomberg_ticker = result[QUERIES[data_source][data_type]['BLOOMBERG']]
                isin_code = result[QUERIES[data_source][data_type]['ISIN']]
                currency = result[QUERIES[data_source][data_type]['currency']]
                currency = Attributes.objects.filter(type='currency', short_name=currency)
                if currency.exists():
                    currency = currency[0]
                else:
                    currency = None
                
                security = SecurityContainer.objects.filter(aliases__alias_type__short_name=data_source.upper(), aliases__alias_value=result[group_id])
                external_append = False
                additional = ''
                if not security.exists():
                    security = SecurityContainer.objects.filter(aliases__alias_type__id=bloomberg_alias.id, aliases__alias_value=bloomberg_ticker)
                    additional = result[name_field]
                    external_append = True
                if is_fund(data_source, result):
                    container = fund_container_type
                    stype = fund_type
                elif is_bond(data_source, result):
                    container = bond_container_type
                    stype = bond_type
                elif is_stock(data_source, result):
                    container = stock_container_type
                    stype = stock_type
                else:
                    container = sec_container_type
                    stype = security_type
                if not security.exists():
                    LOGGER.info("Creating security with " + data_source + " id [" + str(result[group_id]) + "]")
                    security = SecurityContainer()
                    security.name = result[name_field]
                    security.short_name = result[short_name_field] if result[short_name_field]!=None and result[short_name_field]!='' else result[name_field]
                    security.save()
                    security.associated_companies.add(bloomberg_provider)
                    security.save()
                else:
                    LOGGER.info("Security with " + data_source + " id [" + str(result[group_id]) + "] already exists.")
                    security = security[0]
                    if not security.associated_companies.filter(role__identifier='SCR_DP').exists():
                        security.associated_companies.add(bloomberg_provider)
                        security.save()
                security.update_alias(external_alias, result[group_id], additional, external_append)
                security.currency = currency
                security.frequency = daily
                security.type = container
                security.security_type = stype
                security.save()
                if bloomberg_ticker!=None and bloomberg_ticker!='':
                    all_tickers.append(bloomberg_ticker)
                elif isin_code!=None and isin_code!='':
                    all_tickers.append(isin_code)
                    
                if bloomberg_ticker!=None and bloomberg_ticker!='':
                    security.update_alias(bloomberg_alias, bloomberg_ticker)
                if isin_code!=None and isin_code!='':
                    security.update_alias(isin_alias, isin_code)
                universe.members.add(security)
    if data_type=='securities':
        universe.save()
        
        all_containers = {}
        for member in universe.members.all():
            member = get_effective_instance(member)
            if not all_containers.has_key(member.type.identifier):
                all_containers[member.type.identifier] = []
            try:
                all_containers[member.type.identifier].append(member.aliases.get(alias_type__name='BLOOMBERG').alias_value)
            except:
                try:
                    all_containers[member.type.identifier].append(member.aliases.get(alias_type__name='ISIN').alias_value)
                except:
                    LOGGER.info("There is no Bloomberg nor ISIN code available for this security ["  + member.name + "]")
            
        for key in all_containers.keys():
            fields = BloombergTrackContainerMapping.objects.filter(Q(container__identifier='CONT_SECURITY') | Q(container__identifier=key), Q(active=True)).values_list('short_name__code', flat=True)
            all_containers[key] = [to_bloomberg_code(ticker,True) for ticker in all_containers[key]]
            history_key = uuid.uuid4().get_hex()
            bb_thread = threading.Thread(None, bloomberg_history_query, history_key, (history_key, all_containers[key], fields, True))
            bb_thread.start()
            bb_thread.join()
Example #4
0
def campaign_import(request):
    campaign_id = request.GET['container_id']
    campaign = get_effective_instance(Container.objects.get(id=campaign_id))
    set_mailgun_data(campaign.external_id, mailgun.treat_events(campaign.external_id))
    
    return HttpResponse('{"result": true, "status_message": "Imported"}',"json")
Example #5
0
def mails_import(request):
    campaign_id = request.GET['container_id']
    campaign = get_effective_instance(Container.objects.get(id=campaign_id))
    mailgun.treat_emails(None, campaign.name)