Skip to content

Commit

Permalink
Merge pull request #66 from Julius278/code-cleanup
Browse files Browse the repository at this point in the history
Code cleanup
  • Loading branch information
Julius278 authored May 24, 2024
2 parents 19a29c0 + 881ae7e commit 6aa9c4c
Show file tree
Hide file tree
Showing 29 changed files with 152 additions and 174 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
*/
public class SmartDerivativeContractScheduleGenerator {

private SmartDerivativeContractScheduleGenerator(){}

/**
* Simple POJO implementation of <code>SmartDerivativeContractSchedule.EventTimes</code>.
*
Expand Down
27 changes: 10 additions & 17 deletions src/main/java/net/finmath/smartcontract/demo/VisualiserSDC.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,8 @@
*/
@SuppressWarnings("java:S125")
public class VisualiserSDC {

private static final String COUNTERPART = "Counterpart";
private List<Point2D> seriesMarketValues;

private Plot2DBarFX plotMarginAccounts;
private Plot2DFX plotMarketValue;

Expand All @@ -54,12 +53,10 @@ public static void main(final String[] args) throws Exception {
final LocalDate startDate = LocalDate.of(2008, 1, 1);
final LocalDate maturity = LocalDate.of(2012, 1, 3);
final String fileName = "timeseriesdatamap.json";
//final DateTimeFormatter providedDateFormat = DateTimeFormatter.ofPattern("yyyyMMdd");
final List<CalibrationDataset> scenarioList = CalibrationParserDataItems.getScenariosFromJsonFile(fileName).stream().filter(s -> s.getDate().toLocalDate().isAfter(startDate)).filter(s -> s.getDate().toLocalDate().isBefore(maturity)).toList();
// CSV Method returns same List
// final List<IRMarketDataScenario> scenarioList = IRScenarioGenerator.getScenariosFromCSVFile(fileName,providedDateFormat).stream().filter(S->S.getDate().toLocalDate().isAfter(startDate)).filter(S->S.getDate().toLocalDate().isBefore(maturity)).collect(Collectors.toList());


final double notional = 1.0E7;
final String maturityKey = "5Y";
final String forwardCurveKey = "forward-EUR-6M";
Expand Down Expand Up @@ -126,33 +123,29 @@ public void start() {
frame.setSize(1600, 600);
// frame.setSize(960, 540+22);

Platform.runLater(new Runnable() {
@Override
public void run() {

final FlowPane root = new FlowPane();
root.getChildren().addAll(new Group(plotMarginAccounts.get()), plotMarketValue.get());
Platform.runLater(() -> {
final FlowPane root = new FlowPane();
root.getChildren().addAll(new Group(plotMarginAccounts.get()), plotMarketValue.get());

final Scene scene = new Scene(root, 1600, 600);
scene.getStylesheets().add("barchart.css");
fxPanel.setScene(scene);
}
final Scene scene = new Scene(root, 1600, 600);
scene.getStylesheets().add("barchart.css");
fxPanel.setScene(scene);
});
});
}

void updateWithValue(final LocalDateTime date, final double base, final double x, final Double value, final double increment) throws InterruptedException {
final List<Category2D> marginBase = new ArrayList<>();
marginBase.add(new Category2D("We", base + Math.min(0, +increment)));
marginBase.add(new Category2D("Counterpart", base + Math.min(0, -increment)));
marginBase.add(new Category2D(COUNTERPART, base + Math.min(0, -increment)));

final List<Category2D> marginRemoved = new ArrayList<>();
marginRemoved.add(new Category2D("We", -Math.min(0, +increment)));
marginRemoved.add(new Category2D("Counterpart", -Math.min(0, -increment)));
marginRemoved.add(new Category2D(COUNTERPART, -Math.min(0, -increment)));

final List<Category2D> marginExcessed = new ArrayList<>();
marginExcessed.add(new Category2D("We", Math.max(0, +increment)));
marginExcessed.add(new Category2D("Counterpart", Math.max(0, -increment)));
marginExcessed.add(new Category2D(COUNTERPART, Math.max(0, -increment)));

final List<PlotableCategories> plotables = new ArrayList<>();
plotables.add(new PlotableCategories() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public final class PlainSwapEditorHandler { //TODO: this code needs some cleanin

private static final Logger logger = LoggerFactory.getLogger(PlainSwapEditorHandler.class);
private static final String CONSTANT = "constant";
private static final String FAILED_MODEL_CALIBRATION = "Failed to calibrate model.";
private final Smartderivativecontract smartDerivativeContract;
private final Schema sdcmlSchema;
private final Marshaller marshaller;
Expand Down Expand Up @@ -221,7 +222,7 @@ public PlainSwapEditorHandler(final PlainSwapOperationRequest plainSwapOperation
floatingLeg.paymentDates.paymentFrequency.periodMultiplier = BigInteger.valueOf(plainSwapOperationRequest.getFloatingPaymentFrequency().getPeriodMultiplier().longValue());
logger.info("Reading back floating payment frequency period multiplier: {}", floatingLeg.paymentDates.paymentFrequency.periodMultiplier);
floatingLeg.paymentDates.paymentFrequency.setPeriod(plainSwapOperationRequest.getFloatingPaymentFrequency().getPeriod());
logger.info("Reading back floating payment frequency period: {}", floatingLeg.paymentDates.paymentFrequency.period);
logger.info("Reading back floating payment frequency period: {}", floatingLeg.paymentDates.paymentFrequency.period);
((FloatingRateCalculation) floatingLeg.calculationPeriodAmount.calculation.getRateCalculation().getValue()).floatingRateIndex.value = plainSwapOperationRequest.getFloatingRateIndex();
logger.info("Reading back floating rate index: {}", ((FloatingRateCalculation) floatingLeg.calculationPeriodAmount.calculation.getRateCalculation().getValue()).floatingRateIndex.value);
fixedLeg.calculationPeriodAmount.calculation.dayCountFraction.value = plainSwapOperationRequest.getFixedDayCountFraction();
Expand Down Expand Up @@ -408,9 +409,9 @@ public List<CashflowPeriod> getSchedule(LegSelector legSelector, String marketDa
default -> throw new IllegalArgumentException("Failed to detect leg type");
}
final LocalDate startDate = swapLeg.getCalculationPeriodDates().getEffectiveDate().getUnadjustedDate().getValue().toGregorianCalendar().toZonedDateTime().toLocalDate();
logger.info("Start date detected: {]", startDate.toString());
logger.info("Start date detected: {}", startDate);
final LocalDate maturityDate = swapLeg.getCalculationPeriodDates().getTerminationDate().getUnadjustedDate().getValue().toGregorianCalendar().toZonedDateTime().toLocalDate();
logger.info("Maturity date detected: {}", maturityDate.toString());
logger.info("Maturity date detected: {}", maturityDate);
int fixingOffsetDays = 0;
try {
fixingOffsetDays = swapLeg.getResetDates().getFixingDates().getPeriodMultiplier().intValue();
Expand Down Expand Up @@ -518,9 +519,9 @@ public List<CashflowPeriod> getSchedule(LegSelector legSelector, MarketDataSet m
default -> throw new IllegalArgumentException("Failed to detect leg type");
}
final LocalDate startDate = swapLeg.getCalculationPeriodDates().getEffectiveDate().getUnadjustedDate().getValue().toGregorianCalendar().toZonedDateTime().toLocalDate();
logger.info("Start date detected: {}", startDate.toString());
logger.info("Start date detected: {}", startDate);
final LocalDate maturityDate = swapLeg.getCalculationPeriodDates().getTerminationDate().getUnadjustedDate().getValue().toGregorianCalendar().toZonedDateTime().toLocalDate();
logger.info("Maturity date detected: {}", maturityDate.toString());
logger.info("Maturity date detected: {}", maturityDate);
int fixingOffsetDays = 0;
try {
fixingOffsetDays = swapLeg.getResetDates().getFixingDates().getPeriodMultiplier().intValue();
Expand Down Expand Up @@ -641,13 +642,13 @@ private AnalyticModel getAnalyticModel(String marketData, Schedule schedule, Str
try {
optionalCalibrationResult = calibrator.calibrateModel(allCalibrationItems, new CalibrationContextImpl(referenceDate, 1E-9));
} catch (CloneNotSupportedException e) {
logger.error("Failed to calibrate model.");
logger.error(FAILED_MODEL_CALIBRATION);
throw e;
}
AnalyticModel calibratedModel;
if (optionalCalibrationResult.isPresent())
calibratedModel = optionalCalibrationResult.get().getCalibratedModel();
else throw new IllegalStateException("Failed to calibrate model.");
else throw new IllegalStateException(FAILED_MODEL_CALIBRATION);


Set<CalibrationDataItem> pastFixings = scenario.getFixingDataItems();
Expand Down Expand Up @@ -709,13 +710,13 @@ private AnalyticModel getAnalyticModel(MarketDataSet marketData, Schedule schedu
try {
optionalCalibrationResult = calibrator.calibrateModel(allCalibrationItems, new CalibrationContextImpl(referenceDate, 1E-9));
} catch (CloneNotSupportedException e) {
logger.error("Failed to calibrate model.");
logger.error(FAILED_MODEL_CALIBRATION);
throw e;
}
AnalyticModel calibratedModel;
if (optionalCalibrationResult.isPresent())
calibratedModel = optionalCalibrationResult.get().getCalibratedModel();
else throw new IllegalStateException("Failed to calibrate model.");
else throw new IllegalStateException(FAILED_MODEL_CALIBRATION);
return calibratedModel;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;

/**
* Describes the result of a single settlement as reported by the valuation oracle.
Expand Down Expand Up @@ -67,7 +66,7 @@ public enum SettlementType {

// Custom additional information (e.g. risk figures or szenario values)

private Map<String, String> info;
//private Map<String, String> info;

public String getTradeId() {
return tradeId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import net.finmath.smartcontract.model.MarginRequest;
import net.finmath.smartcontract.model.MarginResult;
import net.finmath.smartcontract.model.MarketDataList;
import net.finmath.smartcontract.product.xml.SDCXMLParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

Expand All @@ -21,33 +21,32 @@
* @author Peter Kohl-Landgraf
* @author Dietmar Schnabel
*/
@SuppressWarnings("java:S125")
public class ValuationClient {
private static final Logger logger = LoggerFactory.getLogger(ValuationClient.class);
private static final String BASIC = "Basic ";

public static void main(String[] args) throws Exception {
String url = "http://localhost:8080";
String authString = "user1:password1";

if (args.length != 2) {
System.out.println("Usage: ValuationClient <url> <user>:<password>");
logger.info("Usage: ValuationClient <url> <user>:<password>");
}

if (args.length == 2) {
authString = args[1];
} else {
System.out.println("Using default credentials " + authString);
logger.info("Using default credentials {}", authString);
}

if (args.length >= 1) {
url = args[0];
} else {
System.out.println("Using default endpoint " + url);
logger.info("Using default endpoint {}", url);
}

final String marketDataStartXml = new String(Objects.requireNonNull(ValuationClient.class.getClassLoader().getResourceAsStream("net/finmath/smartcontract/valuation/client/md_testset1.xml")).readAllBytes(), StandardCharsets.UTF_8);
//final MarketDataList marketDataStart = SDCXMLParser.unmarshalXml(marketDataStartXml, MarketDataList.class);
final String marketDataEndXml = new String(Objects.requireNonNull(ValuationClient.class.getClassLoader().getResourceAsStream("net/finmath/smartcontract/valuation/client/md_testset2.xml")).readAllBytes(), StandardCharsets.UTF_8);
//final MarketDataList marketDataEnd = SDCXMLParser.unmarshalXml(marketDataEndXml, MarketDataList.class);
final String product = new String(Objects.requireNonNull(ValuationClient.class.getClassLoader().getResourceAsStream("net.finmath.smartcontract.product.xml/smartderivativecontract.xml")).readAllBytes(), StandardCharsets.UTF_8);

final MarginRequest marginRequest = new MarginRequest().marketDataStart(marketDataStartXml).marketDataEnd(marketDataEndXml).tradeData(product).valuationDate("");
Expand All @@ -57,14 +56,14 @@ public static void main(String[] args) throws Exception {

// create auth credentials
String base64Creds = Base64.getEncoder().encodeToString(authString.getBytes());
headers.add("Authorization", "Basic " + base64Creds);
headers.add(HttpHeaders.AUTHORIZATION, BASIC + base64Creds);

RequestEntity<MarginRequest> requestEntity = new RequestEntity<MarginRequest>(marginRequest, headers, HttpMethod.POST, new URI(url + "/valuation/margin"), MarginRequest.class);
RequestEntity<MarginRequest> requestEntity = new RequestEntity<>(marginRequest, headers, HttpMethod.POST, new URI(url + "/valuation/margin"), MarginRequest.class);

ResponseEntity<MarginResult> response = new RestTemplate().exchange(requestEntity, MarginResult.class);
MarginResult result = response.getBody();

System.out.println("Received the valuation result:\n" + result);
logger.info("Received the valuation result:\n{}", result);

printInfoGit(url, authString);
printInfoFinmath(url, authString);
Expand All @@ -76,15 +75,14 @@ private static void printInfoGit(String url, String authString) throws URISyntax

// create auth credentials
String base64Creds = Base64.getEncoder().encodeToString(authString.getBytes());
headers.add("Authorization", "Basic " + base64Creds);
headers.add(HttpHeaders.AUTHORIZATION, BASIC + base64Creds);

RequestEntity<String> requestEntity = new RequestEntity<>(null, headers, HttpMethod.GET, new URI(url + "/info/git"), String.class);

ResponseEntity<String> response = new RestTemplate().exchange(requestEntity, String.class);

System.out.println();
System.out.println("git status");
System.out.println(response.getBody());
logger.info("git status");
logger.info(response.getBody());
}

private static void printInfoFinmath(String url, String authString) throws URISyntaxException {
Expand All @@ -93,14 +91,13 @@ private static void printInfoFinmath(String url, String authString) throws URISy

// create auth credentials
String base64Creds = Base64.getEncoder().encodeToString(authString.getBytes());
headers.add("Authorization", "Basic " + base64Creds);
headers.add(HttpHeaders.AUTHORIZATION, BASIC + base64Creds);

RequestEntity<String> requestEntity = new RequestEntity<>(null, headers, HttpMethod.GET, new URI(url + "/info/finmath"), String.class);

ResponseEntity<String> response = new RestTemplate().exchange(requestEntity, String.class);

System.out.println();
System.out.println("finmath-lib version");
System.out.println(response.getBody());
logger.info("finmath-lib version");
logger.info(response.getBody());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
public class CalibrationDataItem {
private static final String REGEX = "((?<=[a-zA-Z])(?=[0-9]))|((?<=[0-9])(?=[a-zA-Z]))";


public static class Spec {
private final String key;
private final String curveName;
Expand All @@ -23,10 +22,8 @@ public Spec(final String key, final String curveName, final String productName,
this.curveName = curveName;
this.productName = productName;
this.maturity = maturity;

}


public String getKey() {return key;}

public String getCurveName() {
Expand Down Expand Up @@ -121,7 +118,6 @@ public String getDateString() {
return this.dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}


public LocalDate getDate() {return dateTime.toLocalDate();}

public LocalDateTime getDateTime(){ return dateTime;}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public CalibrationDataset(final Set<CalibrationDataItem> curveDataPointSet, fina
this.scenarioDate = scenarioDate;
this.fixingDataItems = curveDataPointSet.stream().filter(dataItem -> dataItem.getProductName().equals(FIXING)).sorted(Comparator.comparing(CalibrationDataItem::getDate)).collect(Collectors.toCollection(LinkedHashSet::new));
this.calibrationDataItems = curveDataPointSet.stream().filter(dataItem -> !dataItem.getProductName().equals(FIXING)).sorted(Comparator.comparing(CalibrationDataItem::getDaysToMaturity)).collect(Collectors.toCollection(LinkedHashSet::new));

}

public CalibrationDataset getScaled(double scaleFactor) {
Expand All @@ -36,7 +35,6 @@ public CalibrationDataset getScaled(double scaleFactor) {
return new CalibrationDataset(scaledSet, scenarioDate);
}


public Set<CalibrationDataItem> getFixingDataItems() {
return this.fixingDataItems;
}
Expand All @@ -60,9 +58,9 @@ public CalibrationDataset getClonedFixingsAdded(Set<CalibrationDataItem> newFixi
return new CalibrationDataset(clone, this.scenarioDate);
}

public MarketDataList toMarketDataList(){
List<MarketDataPoint> marketDataPointList = calibrationDataItems.stream().map(item->new MarketDataPoint(item.getSpec().getKey(), item.getQuote(), item.getDateTime())).toList();
List<MarketDataPoint> fixings = fixingDataItems.stream().map(item->new MarketDataPoint(item.getSpec().getKey(), item.getQuote(), item.getDateTime())).toList();
public MarketDataList toMarketDataList() {
List<MarketDataPoint> marketDataPointList = calibrationDataItems.stream().map(item -> new MarketDataPoint(item.getSpec().getKey(), item.getQuote(), item.getDateTime())).toList();
List<MarketDataPoint> fixings = fixingDataItems.stream().map(item -> new MarketDataPoint(item.getSpec().getKey(), item.getQuote(), item.getDateTime())).toList();
MarketDataList marketDataList = new MarketDataList();
marketDataPointList.forEach(marketDataList::add);
fixings.forEach(marketDataList::add);
Expand Down
Loading

0 comments on commit 6aa9c4c

Please sign in to comment.