def test_CalendarRangePeriod(self):
		'CalendarRangePeriod instanciation'
		p = period('2002-07-12:2002-07-22')
		cal = Calendar('Test')
		c = CalendarRangePeriod(p, cal)
		self.assertEqual(p.dates, c.dates)
		self.assertEqual(c.calendar, cal)
		self.assertEqual(cal.bizdays(('2002-07-12', '2002-07-22')), c.size())
Exemplo n.º 2
0
def ir(irspec):
	"""
	Return a InterestRate object for a given interest rate specification.
	The interest rate specification is a string like:
	
	'0.06 annual simple actual/365'
	'0.09 annual compounded business/252 calANBIMA'
	'0.06 annual continuous 30/360'
	
	The specification must contain all information required to instanciate a 
	InterestRate object. The InterestRate constructor requires:
	- rate
	- frequency
	- compounding
	- daycount
	and depending on which daycount is used the calendar must be set. Otherwise,
	it defaults to None.
	"""
	calendar = None
	tokens = irspec.split()
	for tok in tokens:
		m = re.match('^(\d+)(\.\d+)?$', tok)
		if m:
			rate = float(m.group())
		elif tok in Compounding.names:
			compounding = Compounding(tok)
		elif tok in DayCount.names:
			daycount = DayCount(tok)
		elif tok in Frequency.names:
			frequency = Frequency(tok)
		elif tok.startswith('cal'):
			calendar = Calendar(tok.replace('cal', ''))
	return InterestRate(rate, frequency, compounding, daycount, calendar)
Exemplo n.º 3
0
def union_cal(cals):
    holidays = []
    for cal in cals:
        holidays = list(set(holidays).union(cal.holidays))
    holidays = sorted(holidays)
    union_cal = Calendar( holidays = holidays, startdate = holidays[0],\
           enddate = holidays[-1], weekdays = ("sat","sun") )
    return (union_cal)
	def test_InterestRate_simple_rate_2(self):
		'InterestRate with DayCount different from business defining Calendar'
		comp = Compounding("simple")
		cal = Calendar('Test')
		freq = Frequency('annual')
		dc = DayCount('actual/365')
		with self.assertRaises(Exception):
			InterestRate(0.1, freq, comp, dc, cal)
	def test_InterestRate(self):
		'InterestRate instanciation'
		ir = InterestRate(0.1, Frequency('annual'), Compounding('simple'), 
			DayCount('actual/360'))
		self.assertEqual(ir.rate, 0.1)
		self.assertEqual(ir.frequency, Frequency('annual'))
		self.assertEqual(ir.compounding, Compounding('simple'))
		self.assertEqual(ir.daycount, DayCount('actual/360'))
		self.assertEqual(ir.calendar, None)
		
		ir = InterestRate(0.1, Frequency('annual'), Compounding('simple'), 
			DayCount('business/252'), Calendar('Test'))
		self.assertEqual(ir.rate, 0.1)
		self.assertEqual(ir.frequency, Frequency('annual'))
		self.assertEqual(ir.compounding, Compounding('simple'))
		self.assertEqual(ir.daycount, DayCount('business/252'))
		self.assertEqual(ir.calendar, Calendar('Test'))
	def test_InterestRate_simple_rate(self):
		'InterestRate simple rate'
		comp = Compounding("simple")
		ir = InterestRate(0.1, Frequency('annual'), comp, 
			DayCount('business/252'), Calendar('Test'))
		smp = Compounding.simple
		comp_val = smp(0.1, 6.0/252)
		
		p = period("2002-7-12:2002-7-22")
		comp = ir.compound(p)
		self.assertEqual(comp, comp_val)
Exemplo n.º 7
0
def init_cal(cal_name):
    if ("|" in cal_name):
        cal_names = cal_name.split("|")
        cals = [init_cal(c) for c in cal_names]
        return (union_cal(cals))

    #----temporary-------------
    if (cal_name not in ["USD", "GBP"]):
        cal_name = "USD"

    cal_file = "Holidays/" + cal_name + ".cal"
    cal = Calendar.load(cal_file)
    return (cal)
	def test_ir(self):
		"""ir function"""
		ir_ = ir('0.06 annual simple actual/365')
		self.assertEqual(ir_.rate, 0.06)
		self.assertEqual(ir_.compounding, Compounding('simple'))
		self.assertEqual(ir_.frequency, Frequency('annual'))
		self.assertEqual(ir_.daycount, DayCount('actual/365'))
		
		ir_ = ir('0.01 semi-annual compounded business/252 calTest')
		self.assertEqual(ir_.rate, 0.01)
		self.assertEqual(ir_.compounding, Compounding('compounded'))
		self.assertEqual(ir_.frequency, Frequency('semi-annual'))
		self.assertEqual(ir_.daycount, DayCount('business/252'))
		self.assertEqual(ir_.calendar, Calendar('Test'))
		
		with self.assertRaises(Exception):
			ir('0.01 semi-annual compounded actual/365 calTest')
Exemplo n.º 9
0
 def post(self):
     nwd = self.request.get("nwd", ('Saturday', 'Sunday'))
     holidays = self.request.get(
         'holidays', '\n'.join([d.isoformat() for d in ANBIMA.holidays]))
     holidays = holidays.split()
     cal = Calendar(holidays, weekdays=nwd)
     dates_from = self.request.get('from')
     dates_from = dates_from.split() if dates_from else None
     dates_to = self.request.get('to')
     dates_to = dates_to.split() if dates_to else None
     if dates_to and dates_to:
         bd = [str(d) for d in cal.vec.bizdays(dates_from, dates_to)]
         logging.info(bd)
     else:
         bd = None
     context = {
         'nwd': nwd,
         'holidays': holidays,
         'weekdays': Calendar._weekdays,
         'from': dates_from,
         'to': dates_to,
         'bd': bd
     }
     self.render_template('bizdays/index', **context)
def get_calendar():
    holidays = load_holidays('ANBIMA.txt')
    return Calendar(holidays, ['Sunday', 'Saturday'])
Exemplo n.º 11
0
"""
Created on Mon Jul 20 18:07:18 2020

@author: massa
"""

import numpy as np
import pandas as pd
import requests
import urllib.request
from bs4 import BeautifulSoup
from tqdm import tqdm
from datetime import datetime
from bizdays import Calendar, load_holidays
holidays = load_holidays('Brazil.txt')
cal = Calendar(holidays, ['Sunday', 'Saturday'], name='Brazil')


def strip_date(date):
    """
    Recebe uma variável string e retorna uma tupla com os valores de dia, mês e
    ano.
    """
    d = datetime.strptime(date, "%Y-%m-%d")
    year = d.year
    month = d.month
    day = d.day
    if month < 10:
        month = '0' + str(month)
    if day < 10:
        day = '0' + str(day)
Exemplo n.º 12
0
@author: buzon
"""

import matplotlib.pyplot as graph
import B3curve as b3
from datetime import datetime
from bizdays import Calendar
import di_derivative as di

FERIADOS = open('C:/Users/buzon/Documents/Python/Arquivos base/Anbima.txt',
                'r')
HOLIDAYS = []
for linha in FERIADOS:
    HOLIDAYS.append(linha.strip())
FERIADOS.close()
cal = Calendar(HOLIDAYS, ['Sunday', 'Saturday'])

PATH = 'C:/Users/buzon/Documents/Curvas/'

SEP = '@'
NEXT_DAY = 1

INDEX = 'pre'
FORMAT = '%d%m%Y'
FORMAT_B3 = '%Y%m%d'


def historic_b3(start, end, maturity_str):
    """Get the historic yield of a vertice. Format ddmmyyyy"""

    start_dt = datetime.strptime(start, FORMAT)
from bizdays import Calendar
from anbima import holidays
cal = Calendar(holidays(), ['Sunday', 'Saturday'])


class Financeira(object):
    def __init__(self):
        self.taxa = 0
        self.capitalizacao = 1
        self.tempo = 1
        self.fator = 1

    def Fator(self, taxa, tempo, capitalizacao=1, trunc=8):
        """
        :param taxa: <float>
        :param tempo: <int>
        :param capitalizacao:<int>
        :param trunc: <int>
        :return:
        """
        self.fator = Financeira.truncate(
            (1 + taxa / capitalizacao)**(capitalizacao * tempo), trunc)
        return self.fator

    def FatorVP(self, taxa, tempo, capitalizacao=1, trunc=8):
        fator = self.Fator(taxa, tempo, capitalizacao, trunc)
        fator_VP = (fator - 1) / (fator * taxa)
        print(fator_VP)
        return fator_VP

    def ValorPresente(self,
Exemplo n.º 14
0
print("*****  This program calculates real ending date of a task  *****")
print("*****  while considaring weekends                          *****")
print("*****                                                      *****")
print("*****   Just enter the date of start                       *****")
print("*****   and how many days it will continue                 *****")
print("*****                                                      *****")
print("*****   and you will get the date when the task will end   *****")
print("*****                                                      *****")
print("*****                                                      *****")
print("*****           Created by:  Amir Dagan                    *****")
print("****************************************************************")
print()
print()

holiday_list = ''
cal = Calendar(holiday_list, ['Friday', 'Saturday'])
again = "y"
while (again.lower() == "y"):
    dd = input("Starting Date (dd-mm-yyyy)")
    ndd = dd[6:] + dd[2:6] + dd[:2]
    bd = int(input("Days to count:"))
    bd -= 1
    new_dd = cal.offset(ndd, bd)
    nice_dd = new_dd.strftime("%d-%m-%Y")
    print()
    print("---------------->", nice_dd)
    print()
    print()
    again = input("Do you want another calc? (Y/N)")
else:
    print("\n\n\n Thanks, see you next time")
Exemplo n.º 15
0
from bizdays import Calendar
import B3curve
import di_derivative as di
import historic as hist

FERIADOS = open('C:/Users/buzon/Documents/Python/Arquivos base/Anbima.txt',
                'r')
HOLIDAYS = []
for linha in FERIADOS:
    HOLIDAYS.append(linha.strip())
FERIADOS.close()

FORMAT = '%Y%m%d'

#Holidays and settlement date.
cal = Calendar(HOLIDAYS, ['Sunday', 'Saturday'])
dt_today = date.today()
dt_stlm = cal.adjust_previous(date.today() + timedelta(-1))
curve_date = datetime.strftime(dt_stlm, FORMAT)
INDEX_B3 = 'pre'

#Yield Curve
curve_list = B3curve.get_curve_b3(curve_date, INDEX_B3)
curve_dic = B3curve.get_dic_curve(curve_list)


def create_cash_flow(maturity_years, pmt_per_year, stlm=dt_stlm):
    """"Create a cash flow given a number of years to maturity and
    how many payments per year. Set pmt_per_year = 0 to bullet cash flow"""
    cash_flow = []
    maturity = cal.adjust_next(
Exemplo n.º 16
0
]  #todos as colunas do arquivo
indexFiltrado = ['dt', 'simbolo', 'preco', 'qnt',
                 'hr']  #primeiro filtro de colunas
indexFiltrado2 = [
    'dt', 'preco', 'hr_int', 'preco_pon', 'qnt_soma', 'max', 'min', 'IND',
    'ISP'
]  #segundo filtro de colunas

vencimento = pd.read_csv(
    pastaCoisas +
    "vencimento.csv")  #le o arquivo contendo os vencimentos do WDO
feriados = pd.read_csv(pastaCoisas +
                       "feriadosBR.csv")  #le o arquivo com os feriados BRs
holidays = feriados['Data']  #pega só as datas
cal = Calendar(holidays=holidays,
               weekdays=['Sunday', 'Saturday'
                         ])  #adiciona no calendario para poder controlar

periodicidade = 5 * 60 * 1000  #define a periodicidade em que o arquivo vai ser filtrado
horarioInicio = '09:05:00.000'  #define horario de inicio para começar a pegar os arquivos
horarioInicioInt = tempoStrToInt(horarioInicio)  #traduz o horario inicial
horarioFim = '17:55:00.000'  #define horario de fim para terminar de pegar os arquivos
horarioFimInt = tempoStrToInt(horarioFim)  #traduz o horario fim
#######################################################################

##############################   FILTRO   #############################
os.chdir(pastaArquivosDescompactados)  #caminho da pasta de importação
qnt_arquivos = len(glob.glob("*.txt"))
arquivo_n = 0
for file in glob.glob("*.txt"):  #pega arquivos com final TXT
Exemplo n.º 17
0
from itertools import izip
from datetime import datetime, date, timedelta

from google.appengine.api import urlfetch
import tablib
from bizdays import Calendar

from scraps import *
from welgae import *
import ANBIMA
import gcs
import tinydf
import textparser as tp

CALENDAR = Calendar(ANBIMA.holidays,
                    weekdays=('Saturday', 'Sunday'),
                    name='ANBIMA')


class asdate(object):
    def __init__(self, d=None, format='%Y-%m-%d'):
        d = d if d else date.today()
        if type(d) in (str, unicode):
            d = datetime.strptime(d, format).date()
        elif type(d) is datetime:
            d = d.date()
        elif type(d) is asdate:
            d = d.date
        elif type(d) is date:
            pass
        else: