Beispiel #1
0
def add_price(request):
    # TODO: Check user
    user = User.objects.get(id=request.user.id)
    container_id = request.POST['container_id']
    container_type = request.POST['container_type']
    container_class = container_type + '_CLASS'
    
    price_date = datetime.datetime.strptime(request.POST['price_date'], '%Y-%m-%d')
    price_value = float(request.POST['price_value'])
    # 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)
    track = get_track(container, {'track_default': True, 'track_type': 'NUM_TYPE_NAV'})
    if track==None:
        return HttpResponse('{"result": "No valid track", "status_message": "Not saved"}',"json")
    all_tokens = get_track_content(track)
    if all_tokens==None:
        all_tokens = []
    found = False
    for token in all_tokens:
        if token['date']==price_date:
            found = True
            token['value'] = price_value
    if not found:
        all_tokens.append({'date': price_date, 'value': price_value})

    set_track_content(track, all_tokens, True)
    
    return HttpResponse('{"result": "Token added", "status_message": "Saved"}',"json")
def simple_price_report(user, universe, frequency, reference = None, start_date = None, rolling = None):
    # WORKING VARIABLES
    LOGGER.info("Simple price report for " + universe.name)
    today = datetime.date.today()
    nav_value = Attributes.objects.get(identifier='NUM_TYPE_NAV', active=True)
    perf_value = Attributes.objects.get(identifier='NUM_TYPE_PERF', active=True)
    final_status = Attributes.objects.get(identifier='NUM_STATUS_FINAL', active=True)
    official_type = Attributes.objects.get(identifier='PRICE_TYPE_OFFICIAL', active=True)
    monthly = Attributes.objects.get(identifier='FREQ_MONTHLY', active=True)
    
    save_path = os.path.join(WORKING_PATH,universe.name + '_' + str(user.id) + '_PRICES_REPORT_' + str(today) + '.xlsx')
    
    if rolling!=None:
        if start_date==None:
            start_date = dt.combine(dates.AddDay(today, -rolling), dt.min.time())
        else:
            effective_start_date = dt.combine(dates.AddDay(today, -rolling), dt.min.time())
            if effective_start_date>start_date:
                start_date = effective_start_date
        LOGGER.debug("Rolling enabled - Start date = " + str(start_date))        
        
    all_tracks = TrackContainer.objects.filter(effective_container_id__in=[member.id for member in universe.members.all()], type__id=nav_value.id,quality__id=official_type.id, frequency__id=frequency.id, status__id=final_status.id, frequency_reference=reference)
    if start_date==None:
        all_dates = sorted(list(set([token['date'] for track in all_tracks for token in get_track_content(track)])))
    else:
        all_dates = sorted(list(set([token['date'] for track in all_tracks for token in get_track_content(track) if token['date']>=start_date])))
    if len(all_dates)==0:
        LOGGER.warn("Universe members do not have track content")
        return False, None
    LOGGER.info("Will produce " + str(len(all_dates)) + " columns groups")
    
    if start_date==None:
        start_date = all_dates[0]
        LOGGER.info("Full content - Start date = " + str(start_date))
    
    workbook = xlsxwriter.Workbook(save_path)
    formats = define_formats(workbook)
    
    ws = workbook.add_worksheet('Prices')
    ws.set_column(0,0,30)

    col_index = 1
    
    all_data = {}
    first = True
    computing_company = CompanyContainer.objects.get(name='FinaLE Engine')
    
    for day in all_dates:
        row_index = 0
        print_day = day.strftime('%d, %b %Y')
        ws.write(row_index, col_index, 'Closing price on the ' + print_day, formats['main_format_normal'])
        ws.write(row_index, col_index + 1, 'WTD on the ' + print_day, formats['main_format_normal'])
        ws.write(row_index, col_index + 2, 'MTD on the ' + print_day, formats['main_format_normal'])
        ws.write(row_index, col_index + 3, 'YTD on the ' + print_day, formats['main_format_normal'])
        ws.set_column(col_index,col_index+3,15)
        eom = dt.combine(dates.AddDay(dates.GetStartOfMonth(day),-1),dt.min.time())
        eoy = dt.combine(datetime.date(day.year-1,12,31),dt.min.time())
        row_index += 1
        # CONTENT
        for member in universe.members.all():
            print "---------------------->" + str(day)
            LOGGER.info("Working with " + member.name + " as of " + str(day))
            if first:
                ws.write(row_index, 0, member.short_name, formats['main_format_normal'])
            if not all_data.has_key(member.id):
                all_data[member.id] = {}
                monthly_track = TrackContainer.objects.get(effective_container_id=member.id, type__id=nav_value.id,quality__id=official_type.id, source__id=computing_company.id, frequency__id=monthly.id, status__id=final_status.id)
                monthlies = {token['date']:token['value'] for token in get_track_content(monthly_track)}
                values_track = TrackContainer.objects.get(effective_container_id=member.id, type__id=nav_value.id,quality__id=official_type.id, source__id=computing_company.id, frequency__id=frequency.id, status__id=final_status.id, frequency_reference=reference)
                perfs_track = TrackContainer.objects.get(effective_container_id=member.id, type__id=perf_value.id,quality__id=official_type.id, source__id=computing_company.id, frequency__id=frequency.id, status__id=final_status.id, frequency_reference=reference)
                if start_date==None:
                    all_values = {token['date']:token['value'] for token in get_track_content(values_track)}
                    all_performances = {token['date']:token['value'] for token in get_track_content(perfs_track)}
                else:
                    all_values = {token['date']:token['value'] for token in get_track_content(values_track) if token['date']>=start_date}
                    all_performances = {token['date']:token['value'] for token in get_track_content(perfs_track) if token['date']>=start_date}
                all_data[member.id]['VALUES'] = all_values
                all_data[member.id]['PERFORMANCES'] = all_performances
                all_data[member.id]['MONTHLY'] = monthlies
            backdated_day = day
            print all_data[member.id]['VALUES']
            while not all_data[member.id]['VALUES'].has_key(backdated_day):
                backdated_day = dates.AddDay(backdated_day, -1)
            LOGGER.info("Using " + str(backdated_day))
            ws.write(row_index, col_index, all_data[member.id]['VALUES'][backdated_day], formats['main_format_normal'])
            ws.write(row_index, col_index + 1, all_data[member.id]['PERFORMANCES'][backdated_day], formats['main_format_percent'])
            if all_data[member.id]['MONTHLY'].has_key(eom):
                ws.write(row_index, col_index + 2, (all_data[member.id]['VALUES'][backdated_day]/all_data[member.id]['MONTHLY'][eom]) - 1.0, formats['main_format_percent'])
            else:
                ws.write(row_index, col_index + 2, '', formats['main_format_normal'])
            if all_data[member.id]['MONTHLY'].has_key(eoy):
                ws.write(row_index, col_index + 3, (all_data[member.id]['VALUES'][backdated_day]/all_data[member.id]['MONTHLY'][eoy]) - 1.0, formats['main_format_percent'])
            else:
                ws.write(row_index, col_index + 3, '', formats['main_format_normal'])
                    
                    
            row_index += 1
        first = False
        col_index += 4
    workbook.close()
    return True, save_path
Beispiel #3
0
def get_main_track_content(security, ascending = True,  display = False, divisor = 1.0):
    nav_value = Attributes.objects.get(identifier='NUM_TYPE_NAV', active=True)
    final_status = Attributes.objects.get(identifier='NUM_STATUS_FINAL', active=True)
    official_type = Attributes.objects.get(identifier='PRICE_TYPE_OFFICIAL', active=True)
    provider = security.associated_companies.filter(role__identifier='SCR_DP')
    if provider.exists():
        provider = provider[0]
        try:
            track = TrackContainer.objects.get(
                effective_container_id=security.id,
                type__id=nav_value.id,
                quality__id=official_type.id,
                source__id=provider.company.id,
                frequency__id=security.frequency.id,
                frequency_reference=security.frequency_reference,
                status__id=final_status.id)
            return get_track_content_display(track, ascending, False) if display else get_track_content(track, ascending, divisor)
        except:
            LOGGER.warn("No track found for container [" + str(security.id) + "]")
    return None
Beispiel #4
0
def export(parameters):
    working_date = parameters['workingDate']
    export_type = parameters['exportType']
    
    sequoia_universe = Universe.objects.get(name='Sequoia Products')
    guardian_alias = Attributes.objects.get(type='alias_type', short_name='GUARDIAN')
    bloomberg_alias = Attributes.objects.get(identifier='ALIAS_BLOOMBERG')
    
    nav_value = Attributes.objects.get(identifier='NUM_TYPE_NAV', active=True)
    final_status = Attributes.objects.get(identifier='NUM_STATUS_FINAL', active=True)
    official_type = Attributes.objects.get(identifier='PRICE_TYPE_OFFICIAL', active=True)
    monthly = Attributes.objects.get(identifier='FREQ_MONTHLY', active=True)
    computing_company = CompanyContainer.objects.get(name='FinaLE Engine')
    
    if not isinstance(working_date, basestring):
        working_date = working_date[0]
    end_date = datetime.datetime.strptime(working_date,'%Y-%m-%d')
    begin_date = dates.GetStartOfMonth(end_date)
    all_portfolios = get_positions('guardian', end_date)
    
    all_products = {}
    all_groups = {}
    all_navs = {}
    all_spots = {'CHF': 1.0}
    
    for portfolio_code in all_portfolios['values']:
        portfolio_name = portfolio_code.replace('___','.')
        LOGGER.info("Working on " + portfolio_name)
        
        all_positions = all_portfolios['values'][portfolio_code]
        for position in all_positions:
            group = position['cod_gru']
            printable_name = position['des_tit'].encode(sys.stdout.encoding, errors='replace')
            target_currency = position['cod_div_tit']

            if not all_groups.has_key(group):
                all_groups[group] = {}
                
            if not all_groups[group].has_key(portfolio_name):
                all_groups[group][portfolio_name] = {'AUM': 0.0}
                
            security = SecurityContainer.objects.filter(aliases__alias_type=guardian_alias, aliases__alias_value=position['cod_tit'])
            if security.exists():
                security = security[0]
                if target_currency==None and target_currency.currency!=None:
                    target_currency = security.currency.short_name
            else:
                security = None
            print "SECURITY:" + printable_name               
            if security!=None:
                sequoia = sequoia_universe.members.filter(id=security.id).exists()
                if sequoia:
                    LOGGER.info("\tFound " + printable_name)
                    if not all_groups[group][portfolio_name].has_key('SEQUOIA'):
                        all_groups[group][portfolio_name]['SEQUOIA'] = {}
                    if not all_products.has_key(security.name):
                        all_products[security.name] = {}
                if not all_navs.has_key(position['des_tit']):
                    try:
                        monthly_track = TrackContainer.objects.get(effective_container_id=security.id, type__id=nav_value.id,quality__id=official_type.id, source__id=computing_company.id, frequency__id=monthly.id, status__id=final_status.id)
                        monthlies = {token['date']:token['value'] for token in get_track_content(monthly_track)}
                        backdated_day = end_date
                        while not monthlies.has_key(backdated_day):
                            backdated_day = dates.AddDay(backdated_day, -1)
                        nav = monthlies[backdated_day]
                        all_navs[position['des_tit']] = nav
                    except:
                        LOGGER.warn("\tNo price nor track for " + printable_name)
                        all_navs[position['des_tit']] = 1.0
                if not all_spots.has_key(target_currency):
                    spot_container = SecurityContainer.objects.filter(aliases__alias_type=bloomberg_alias, aliases__alias_value= target_currency + 'CHF Curncy')
                    if spot_container.exists():
                        spot_container = spot_container[0]
                        try:
                            monthly_track = TrackContainer.objects.get(effective_container_id=spot_container.id, type__id=nav_value.id,quality__id=official_type.id, source__id=computing_company.id, frequency__id=monthly.id, status__id=final_status.id)
                            monthlies = {token['date']:token['value'] for token in get_track_content(monthly_track)}
                            backdated_day = end_date
                            while not monthlies.has_key(backdated_day):
                                backdated_day = dates.AddDay(backdated_day, -1)
                            spot = monthlies[backdated_day]
                            all_spots[target_currency] = spot
                        except:
                            traceback.print_exc()
                            LOGGER.warn("\tNo price nor track for " + target_currency + "/CHF SPOT")
                            all_spots[target_currency] = 1.0
                    else:
                        LOGGER.warn("\tNo security for " + target_currency + "/CHF SPOT")
                        all_spots[target_currency] = 1.0
                chf_value = position['qta'] * all_navs[position['des_tit']] * all_spots[target_currency]
                if sequoia:
                    all_products[security.name][portfolio_name] = chf_value
                    all_groups[group][portfolio_name]['SEQUOIA'][position['des_tit']] = chf_value
                all_groups[group][portfolio_name]['AUM'] += chf_value
            else:
                if not all_spots.has_key(target_currency):
                    spot_container = SecurityContainer.objects.filter(aliases__alias_type=bloomberg_alias, aliases__alias_value= target_currency + 'CHF Curncy')
                    if spot_container.exists():
                        spot_container = spot_container[0]
                        try:
                            monthly_track = TrackContainer.objects.get(effective_container_id=spot_container.id, type__id=nav_value.id,quality__id=official_type.id, source__id=computing_company.id, frequency__id=monthly.id, status__id=final_status.id)
                            monthlies = {token['date']:token['value'] for token in get_track_content(monthly_track)}
                            backdated_day = end_date
                            while not monthlies.has_key(backdated_day):
                                backdated_day = dates.AddDay(backdated_day, -1)
                            spot = monthlies[backdated_day]
                            all_spots[target_currency] = spot
                        except:
                            traceback.print_exc()
                            LOGGER.warn("\tNo price nor track for " + target_currency + "/CHF SPOT")
                            all_spots[target_currency] = 1.0
                    else:
                        LOGGER.warn("\tNo security for " + target_currency + "/CHF SPOT")
                        all_spots[target_currency] = 1.0
                chf_value = position['qta'] * all_spots[target_currency]
                all_groups[group][portfolio_name]['AUM'] += chf_value
    # OUTPUT of SWM file
    out_file_name = os.path.join(WORKING_PATH,'_SWM_' + str(working_date) + '.xlsx')
    wb = Workbook()
    ws = wb.get_active_sheet()
    ws.title = "Import"
    headers = [['','','','Allocation',''],['Code Fond / Banque',u'Date d\xe9but','Date fin','Code Client','Montant CHF'],]
    row_index = define_xslx_header(ws, headers)
    for product in sorted(all_products.keys()):
        first = True
        for client in all_products[product].keys():
            if not first:
                ws.cell(row=row_index, column=1).value = ''
            else:
                ws.cell(row=row_index, column=1).value = product
            ws.cell(row=row_index, column=2).value = begin_date
            ws.cell(row=row_index, column=3).value = working_date
            ws.cell(row=row_index, column=4).value = client if client!='NEW FRONTIER' else 'NF'
            ws.cell(row=row_index, column=5).value = all_products[product][client]
            row_index += 1
            first = False
    wb.save(out_file_name)