def plot_WW_distr(infile, outdir, out_formats=["pdf", "png"]):
    """ Plot the distribution that is stored in the given file.
  """
    base_name = os.path.basename(infile).replace(".csv", "")

    log.debug("Reading file: {}.csv".format(base_name))
    reader = IOR.Reader(infile)

    # Get the pandas dataframe for the cut histograms
    df = reader["Data"]

    # Get the data
    angles = ("costh_Wminus_star", "costh_l_star", "phi_l_star")
    x = np.array([df["BinCenters:{}".format(angle)] for angle in angles])
    y = np.array(df["Cross sections"])

    xmin = np.array(
        [np.amin(df["BinLow:{}".format(angle)]) for angle in angles])
    xmax = np.array(
        [np.amax(df["BinUp:{}".format(angle)]) for angle in angles])

    # Bin counting assumes that bins are not binned thinner than 1/1000 and that
    # absolute values are of order 0.1-1
    nbins = np.array(
        [len(np.unique((x[d] * 10000.).astype(int))) for d in range(len(x))])

    create_2D_projection_plot(x, y, xmin, xmax, nbins, angles, base_name,
                              outdir, out_formats)

    for i in range(len(angles)):
        create_1D_projection_plot(i, x, y, xmin, xmax, nbins, angles,
                                  base_name, outdir, out_formats)
def plot_mumu_distr(infile, outdir, out_formats=["pdf", "png"]):
    """ Plot the distribution that is stored in the given file.
  """
    base_name = os.path.basename(infile).replace(".csv", "")

    log.debug("Reading file: {}.csv".format(base_name))
    reader = IOR.Reader(infile)

    # Get the pandas dataframe for the cut histograms
    df = reader["Data"]

    # Get the data
    x_name = "costh_f_star"
    x = np.array(df["BinCenters:{}".format(x_name)])
    y = np.array(df["Cross sections"])

    xmin = np.array(np.amin(df["BinLow:{}".format(x_name)]))
    xmax = np.array(np.amax(df["BinUp:{}".format(x_name)]))

    # Bin counting assumes that bins are not binned thinner than 1/1000 and that
    # absolute values are of order 0.1-1
    nbins = len(np.unique((x * 10000.).astype(int)))

    # Create the figure and plot
    fig = plt.figure(figsize=(6.5, 5), tight_layout=True)
    ax = plt.gca()
    ax.hist(x=x,
            weights=y,
            bins=nbins,
            range=(xmin, xmax),
            ls="-",
            lw=3,
            histtype=u'step')

    # Useful limits
    ax.set_xlim(xmin, xmax)
    # ax.set_ylim(0, 1.1*ax.get_ylim()[1])

    # Useful labels
    ax.set_xlabel("${}$".format(PN.observable_str(x_name, "mumu")))
    ax.set_ylabel("$d\\sigma [$fb$]$")

    # Mark which process it is
    chirality = IOFH.find_chirality(base_name)
    Z_direction = IOFH.find_Z_direction(base_name)
    mass_label = IOFH.find_2f_mass_label(base_name)
    process_str = "${}$".format(
        PN.difermion_process_str("mu", chirality, mass_label, Z_direction))
    ax.set_title(process_str)

    # Save the plot in files
    for out_format in out_formats:
        format_dir = "{}/{}".format(outdir, out_format)
        IOSH.create_dir(format_dir)
        fig.savefig("{}/{}_{}.{}".format(format_dir, base_name, x_name,
                                         out_format),
                    transparent=True,
                    bbox_inches='tight')
示例#3
0
                    "swap":[[rates set], NUM]
                    }
    convention = { instruemtns convention }
    Day_Counter = function of year fraction
"""
from IO import Reader as reader
from curve import Day_Counter_func as Day_Counter
from curve import Boot_Strapping as B_S
from curve import Boot_Strap_Tools_Func as BS_TF
import pandas as pd
""" Get raw data
"""
f_name = "Raw_Inputs.xlsx"
s_name = "Data"
c_num, f_num, s_num = 5,7,100
reader = reader.excel_reader(f_name)
ccy, date, Cash, Future, Swap = reader.read_instruments(s_name)
instrument = {}
instrument["cash"]   = [ Cash, c_num ]
instrument["future"] = [ Future, f_num ]
instrument["swap"]   = [ Swap, s_num ]
""" Set up valuation date and currency
    then generate the cure by bootstrapping
"""
value_date  = date
currency    = ccy
convention  = convention_book[currency]
Day_Counter = Day_Counter.Day_Counter(convention["LIBOR_day_count"])
curve = B_S.boot_strapping_LIBOR( value_date, 
                                  convention,
                                  instrument, 
log.basicConfig(level=log.INFO) # Set logging level
PDF.set_default_mpl_format()
MCLumi = 5000 # MC Statistics is 5ab^-1

input_dir = "/home/jakob/DESY/MountPoints/DUST/TGCAnalysis/SampleProduction/NewMCProduction/2f_Z_l/PrEWInput/MuAcc_costheta_0.9925"
# input_dir = "/home/jakob/DESY/MountPoints/DUST/TGCAnalysis/SampleProduction/NewMCProduction/2f_Z_l/PrEWInput/MuAcc_costheta_0.9925/TrueAngle"

output_dir = input_dir + "/shape_checks"
IOSH.create_dir(output_dir)

log.info("Looking in dir: {}".format(input_dir))
for file_path in IOSH.find_files(input_dir, ".csv"):
  # Read the input file
  base_name = os.path.basename(file_path).replace(".csv","")
  log.info("Reading file: {}.csv".format(base_name))
  reader = IOR.Reader(file_path)

  # Get the pandas dataframe for the cut histograms
  angle = "costh_f_star_true" if "TrueAngle" in input_dir else "costh_f_star"
  df = reader["Data"]
  bin_vals = np.array(df["Cross sections"])
  bin_middles = np.array(df["BinCenters:{}".format(angle)])
  edges_min = np.array(df["BinLow:{}".format(angle)])
  edges_max = np.array(df["BinUp:{}".format(angle)])
  bin_width = edges_max[0] - edges_min[0]

  # Rescale to MC Lumi
  bin_vals *= MCLumi

  # Perform fits to the distributions
  fit_vals_ha, p_ha, cov_ha = SST.fit_1D(SSF.helicity_amplitudes, bin_vals, edges_min, edges_max, bounds=[[0,0],[np.inf,np.inf]])
示例#5
0
Outputs:
    fixed swap rate on leg2 (in default)
    Can be adjusted and out put all detailed cash flows
    
@author: Shaolun Du
@contacts: [email protected]
"""
import os
import xlwings as xw
from IO import Reader as reader
from Pricing import FX_Pricer as Pricer
""" Set up enviroments
"""
dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
f_name = dir_path + "\\Basic Pricing.xlsm"
reader = reader.excel_reader(f_name)
inputs = reader.read_basic_fx_input("Pricer")

val_date = inputs["cv date"]
npv_date = inputs["value date"]
source = inputs["source"]
""" Choose Pricing Source
"""
fx_name = "FX_Rate"
s_name = "Rate_History"
s_fx_name = "FX_Curve_History"
s_opt_name = "Vol_Surface"

sheet_name = "Pricer"
opt_source = "LIVE"
db_name = "Yield_Curve"
output_dir = input_dir_nocor + "/ISR_shape_checks"
IOSH.create_dir(output_dir)

file_pairs = [
    ["2f_mu_81to101_BZ_250_eLpR.csv", "2f_mu_81to101_BZ_true_250_eLpR.csv"],
    ["2f_mu_81to101_BZ_250_eRpL.csv", "2f_mu_81to101_BZ_true_250_eRpL.csv"],
    ["2f_mu_81to101_FZ_250_eLpR.csv", "2f_mu_81to101_FZ_true_250_eLpR.csv"],
    ["2f_mu_81to101_FZ_250_eRpL.csv", "2f_mu_81to101_FZ_true_250_eRpL.csv"],
]

for file_pair in file_pairs:
    # Read the input file
    base_name = file_pair[0].replace(".csv", "")
    log.info("Processing: {}".format(base_name))
    reader_nocor = IOR.Reader(input_dir_nocor + "/" + file_pair[0])
    reader_sicor = IOR.Reader(input_dir_sicor + "/" + file_pair[1])

    # Get the pandas dataframe for the cut histograms
    df_nocor = reader_nocor["Data"]
    df_sicor = reader_sicor["Data"]
    bin_vals_nocor = MCLumi * np.array(df_nocor["Cross sections"])
    bin_vals_sicor = MCLumi * np.array(df_sicor["Cross sections"])

    angle = "costh_f_star"
    bin_middles = np.array(df_nocor["BinCenters:{}".format(angle)])
    edges_min = np.array(df_nocor["BinLow:{}".format(angle)])
    edges_max = np.array(df_nocor["BinUp:{}".format(angle)])
    bin_width = edges_max[0] - edges_min[0]

    # Perform fits to the distributions
示例#7
0
@author: Shaolun Du
@contacts: [email protected]
"""
import os
import xlwings as xw

from IO import Reader as reader
from DB import dbExecute as db
""" Set up enviroments
"""
dir_path = os.path.dirname(
            os.path.dirname(
             os.path.realpath(__file__)))
f_name   = dir_path + "\\Basic Pricing.xlsm"
reader   = reader.excel_reader(f_name)

inputs   = reader.read_basic_mkt_input("Pricer")

cv_date  = inputs["curve date"]
val_date = inputs["value date"]
source   = inputs["source"]

schema_name = "Yield_Curve"
# Load libor rates curve
tb_name = "yield_curve"
sqlstring = "Select * from "+tb_name+" where sdate = '"+str(cv_date)+"'"
ans_libor = db.dbExecute( schema_name, sqlstring )

# Load fx rates curve
tb_name = "fx_curve"
from IO import Reader as reader
from Live_Pricing.SW_Pricer import Pricer as Pricer


from curve import Curve_Keeper as C_K
""" Set up enviroments
"""
dir_path = os.path.dirname(os.path.realpath(__file__))
f_name   = dir_path+"\\Live Pricing.xlsm"

fx_name  = "FX_Live"
balance_name = "Schedule"

""" Set up objects
"""
reader  = reader.excel_reader(f_name)

fx_spot = reader.read_FX_rates(fx_name)
source  = reader.read_source("Pricer")
""" Choose Pricing Source
"""
if "H" in source.upper():
    s_name    = "Rate_History"
    s_fx_name = "FX_Curve_History"
elif "L" in source.upper():
    s_name    = "Rate_Live"
    s_fx_name = "FX_Curve_Live"

cv_instrument    = reader.read_instruments(s_name, 8)
cv_fx_instrument = reader.read_instruments(s_fx_name, 8)
import IO.Reader as Reader
import portfolio.Portfolio as Portfolio
from IO import Writer as Writer
start = time.time()
""" Setup reader 
"""
f_name = "Test.xlsx"
s_name = ["Swap"]
#s_name = [ "FX" ]
report_currency = "LCL"
output_fname = "Answer.xlsx"
output_sname = "Result"
writer = Writer.Writer(output_fname)
writer.add_sheet(output_sname)

reader = Reader.excel_reader(f_name)
for sheet in s_name:
    reader.read(sheet)
""" Test on Portfolio Object
"""
curve_date = "2018-11-30"
val_date = "2018-11-30"

Port = Portfolio.Portfolio(curve_date, reader)
Port.analysis(val_date)
fx_usd, sw_usd, bd_usd, sp_usd = Port.translate_to_ccy(report_currency)

usd_bk = {**fx_usd, **sw_usd, **bd_usd, **sp_usd}
future_cf, delta_cf, fx_cf, risks = Port.gen_result_tables(usd_bk)
""" Writting into excel uotput file
"""
示例#10
0
@contact: [email protected]
"""
import DB.dbExecute as dbEx
from IO import Reader as Reader
from Live_Pricing import Vol_Live as Vol
from Live_Pricing import OPT_Pricer as OPT
# Step one load current market vol data
# also load current market rates data
f_name = "Live Pricing.xlsm"
s_name = "Vol_Surface"
sdate  = "2019-03-25" 
schema_name = "Yield_Curve" 
tb_opt = "vcub"
opt_source = "LIVE"
num = 4
Reader = Reader.excel_reader(f_name)
data   = Reader.read_vol( s_name, num )

vol_s = Vol.Val_Surface( sdate,
                         schema_name,
                         tb_opt )
vol_s.get_raw_data( opt_source, data )

# Step two load option/swaption balance schedule
balance_name = "Schedule"
Reader.read( balance_name )
name, raw_data = Reader.get_raw_data()
cv_instrument  = Reader.read_instruments("Rate_Live", 8)
disc_cv_details = { "type" : "LIBOR",
                    "spread" : 0 }
示例#11
0
@Author:   Alan
@Contacts: [email protected]

"""
import os
import xlwings as xw
from IO import Reader as reader
import Live_Pricing.SW_Pricer as Pricer
""" Set up enviroments
"""
dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
f_name = dir_path + "\\Live Pricing.xlsm"
ccy_list = ["USD", "EUR", "COP", "BRL", "JPY", "GBP", "CHF", "CAD"]
""" Set up objects
"""
reader = reader.excel_reader(f_name)

source = reader.read_source("Pricer")
""" Choose Pricing Source
"""
if "H" in source.upper():
    s_name = "Rate_History"
    s_fx_name = "FX_Curve_History"
elif "L" in source.upper():
    s_name = "Rate_Live"
    s_fx_name = "FX_Curve_Live"

cv_instrument = reader.read_instruments(s_name, 8)
cv_fx_instrument = reader.read_instruments(s_fx_name, 8)
""" Start Generating Curves
"""
示例#12
0
@Contacts: [email protected]

"""
import os
import xlwings as xw
from IO import Reader as reader
import Pricing.SWAP_Pricer as Pricer
import Pricing.LP_Tools as Tools
""" Set up enviroments
"""
dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
f_name = dir_path + "\\Basic Pricing.xlsm"
ccy_list = ["USD", "EUR", "COP", "BRL", "JPY", "GBP", "CHF", "CAD"]
""" Set up objects
"""
reader = reader.excel_reader(f_name)

data = reader.read_basic_swap_input("Pricer")
source = data["source"]
freq, isEOM, Margin = reader.read_DFs("Pricer")

if "Y" in isEOM.upper():
    isEOM = True
else:
    isEOM = False
""" Choose Pricing Source
"""
if "H" in source.upper():
    s_name = "Rate_History"
    s_fx_name = "FX_Curve_History"
elif "L" in source.upper():