id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
159,800
windup/windup
rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java
Artifact.withGroupId
public static Artifact withGroupId(String groupId) { Artifact artifact = new Artifact(); artifact.groupId = new RegexParameterizedPatternParser(groupId); return artifact; }
java
public static Artifact withGroupId(String groupId) { Artifact artifact = new Artifact(); artifact.groupId = new RegexParameterizedPatternParser(groupId); return artifact; }
[ "public", "static", "Artifact", "withGroupId", "(", "String", "groupId", ")", "{", "Artifact", "artifact", "=", "new", "Artifact", "(", ")", ";", "artifact", ".", "groupId", "=", "new", "RegexParameterizedPatternParser", "(", "groupId", ")", ";", "return", "artifact", ";", "}" ]
Start with specifying the groupId
[ "Start", "with", "specifying", "the", "groupId" ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java#L38-L44
159,801
windup/windup
rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java
Artifact.withArtifactId
public static Artifact withArtifactId(String artifactId) { Artifact artifact = new Artifact(); artifact.artifactId = new RegexParameterizedPatternParser(artifactId); return artifact; }
java
public static Artifact withArtifactId(String artifactId) { Artifact artifact = new Artifact(); artifact.artifactId = new RegexParameterizedPatternParser(artifactId); return artifact; }
[ "public", "static", "Artifact", "withArtifactId", "(", "String", "artifactId", ")", "{", "Artifact", "artifact", "=", "new", "Artifact", "(", ")", ";", "artifact", ".", "artifactId", "=", "new", "RegexParameterizedPatternParser", "(", "artifactId", ")", ";", "return", "artifact", ";", "}" ]
Start with specifying the artifactId
[ "Start", "with", "specifying", "the", "artifactId" ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java#L49-L54
159,802
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.setSingletonVariable
public void setSingletonVariable(String name, WindupVertexFrame frame) { setVariable(name, Collections.singletonList(frame)); }
java
public void setSingletonVariable(String name, WindupVertexFrame frame) { setVariable(name, Collections.singletonList(frame)); }
[ "public", "void", "setSingletonVariable", "(", "String", "name", ",", "WindupVertexFrame", "frame", ")", "{", "setVariable", "(", "name", ",", "Collections", ".", "singletonList", "(", "frame", ")", ")", ";", "}" ]
Type-safe wrapper around setVariable which sets only one framed vertex.
[ "Type", "-", "safe", "wrapper", "around", "setVariable", "which", "sets", "only", "one", "framed", "vertex", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L90-L93
159,803
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.setVariable
public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null) { throw new IllegalArgumentException("Variable \"" + name + "\" has already been assigned and cannot be reassigned"); } frame.put(name, frames); }
java
public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null) { throw new IllegalArgumentException("Variable \"" + name + "\" has already been assigned and cannot be reassigned"); } frame.put(name, frames); }
[ "public", "void", "setVariable", "(", "String", "name", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", "frames", ")", "{", "Map", "<", "String", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", ">", "frame", "=", "peek", "(", ")", ";", "if", "(", "!", "Iteration", ".", "DEFAULT_VARIABLE_LIST_STRING", ".", "equals", "(", "name", ")", "&&", "findVariable", "(", "name", ")", "!=", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Variable \\\"\"", "+", "name", "+", "\"\\\" has already been assigned and cannot be reassigned\"", ")", ";", "}", "frame", ".", "put", "(", "name", ",", "frames", ")", ";", "}" ]
Set a variable in the top variables layer to given "collection" of the vertex frames. Can't be reassigned - throws on attempt to reassign.
[ "Set", "a", "variable", "in", "the", "top", "variables", "layer", "to", "given", "collection", "of", "the", "vertex", "frames", ".", "Can", "t", "be", "reassigned", "-", "throws", "on", "attempt", "to", "reassign", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L99-L109
159,804
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.removeVariable
public void removeVariable(String name) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); frame.remove(name); }
java
public void removeVariable(String name) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); frame.remove(name); }
[ "public", "void", "removeVariable", "(", "String", "name", ")", "{", "Map", "<", "String", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", ">", "frame", "=", "peek", "(", ")", ";", "frame", ".", "remove", "(", "name", ")", ";", "}" ]
Remove a variable in the top variables layer.
[ "Remove", "a", "variable", "in", "the", "top", "variables", "layer", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L114-L118
159,805
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.findVariable
public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth) { int currentDepth = 0; Iterable<? extends WindupVertexFrame> result = null; for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque) { result = frame.get(name); if (result != null) { break; } currentDepth++; if (currentDepth >= maxDepth) break; } return result; }
java
public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth) { int currentDepth = 0; Iterable<? extends WindupVertexFrame> result = null; for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque) { result = frame.get(name); if (result != null) { break; } currentDepth++; if (currentDepth >= maxDepth) break; } return result; }
[ "public", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", "findVariable", "(", "String", "name", ",", "int", "maxDepth", ")", "{", "int", "currentDepth", "=", "0", ";", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", "result", "=", "null", ";", "for", "(", "Map", "<", "String", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", ">", "frame", ":", "deque", ")", "{", "result", "=", "frame", ".", "get", "(", "name", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "break", ";", "}", "currentDepth", "++", ";", "if", "(", "currentDepth", ">=", "maxDepth", ")", "break", ";", "}", "return", "result", ";", "}" ]
Searches the variables layers, top to bottom, for given name, and returns if found; null otherwise. If maxDepth is set to {@link Variables#SEARCH_ALL_LAYERS}, then search all layers.
[ "Searches", "the", "variables", "layers", "top", "to", "bottom", "for", "given", "name", "and", "returns", "if", "found", ";", "null", "otherwise", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L180-L196
159,806
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.findVariableOfType
@SuppressWarnings("unchecked") public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type) { for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque) { for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values()) { boolean empty = true; for (WindupVertexFrame frame : frames) { if (!type.isAssignableFrom(frame.getClass())) { break; } else { empty = false; } } // now we know all the frames are of the chosen type if (!empty) return (Iterable<T>) frames; } } return null; }
java
@SuppressWarnings("unchecked") public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type) { for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque) { for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values()) { boolean empty = true; for (WindupVertexFrame frame : frames) { if (!type.isAssignableFrom(frame.getClass())) { break; } else { empty = false; } } // now we know all the frames are of the chosen type if (!empty) return (Iterable<T>) frames; } } return null; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "WindupVertexFrame", ">", "Iterable", "<", "T", ">", "findVariableOfType", "(", "Class", "<", "T", ">", "type", ")", "{", "for", "(", "Map", "<", "String", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", ">", "topOfStack", ":", "deque", ")", "{", "for", "(", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", "frames", ":", "topOfStack", ".", "values", "(", ")", ")", "{", "boolean", "empty", "=", "true", ";", "for", "(", "WindupVertexFrame", "frame", ":", "frames", ")", "{", "if", "(", "!", "type", ".", "isAssignableFrom", "(", "frame", ".", "getClass", "(", ")", ")", ")", "{", "break", ";", "}", "else", "{", "empty", "=", "false", ";", "}", "}", "// now we know all the frames are of the chosen type", "if", "(", "!", "empty", ")", "return", "(", "Iterable", "<", "T", ">", ")", "frames", ";", "}", "}", "return", "null", ";", "}" ]
Searches the variables layers, top to bottom, for the iterable having all of it's items of the given type. Return null if not found.
[ "Searches", "the", "variables", "layers", "top", "to", "bottom", "for", "the", "iterable", "having", "all", "of", "it", "s", "items", "of", "the", "given", "type", ".", "Return", "null", "if", "not", "found", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L202-L227
159,807
windup/windup
config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationFilter.java
AbstractIterationFilter.checkVariableName
protected void checkVariableName(GraphRewrite event, EvaluationContext context) { if (getInputVariablesName() == null) { setInputVariablesName(Iteration.getPayloadVariableName(event, context)); } }
java
protected void checkVariableName(GraphRewrite event, EvaluationContext context) { if (getInputVariablesName() == null) { setInputVariablesName(Iteration.getPayloadVariableName(event, context)); } }
[ "protected", "void", "checkVariableName", "(", "GraphRewrite", "event", ",", "EvaluationContext", "context", ")", "{", "if", "(", "getInputVariablesName", "(", ")", "==", "null", ")", "{", "setInputVariablesName", "(", "Iteration", ".", "getPayloadVariableName", "(", "event", ",", "context", ")", ")", ";", "}", "}" ]
Check the variable name and if not set, set it with the singleton variable being on the top of the stack.
[ "Check", "the", "variable", "name", "and", "if", "not", "set", "set", "it", "with", "the", "singleton", "variable", "being", "on", "the", "top", "of", "the", "stack", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationFilter.java#L43-L49
159,808
windup/windup
bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DiscoverPackagesCommand.java
DiscoverPackagesCommand.findClasses
private static Map<String, Integer> findClasses(Path path) { List<String> paths = findPaths(path, true); Map<String, Integer> results = new HashMap<>(); for (String subPath : paths) { if (subPath.endsWith(".java") || subPath.endsWith(".class")) { String qualifiedName = PathUtil.classFilePathToClassname(subPath); addClassToMap(results, qualifiedName); } } return results; }
java
private static Map<String, Integer> findClasses(Path path) { List<String> paths = findPaths(path, true); Map<String, Integer> results = new HashMap<>(); for (String subPath : paths) { if (subPath.endsWith(".java") || subPath.endsWith(".class")) { String qualifiedName = PathUtil.classFilePathToClassname(subPath); addClassToMap(results, qualifiedName); } } return results; }
[ "private", "static", "Map", "<", "String", ",", "Integer", ">", "findClasses", "(", "Path", "path", ")", "{", "List", "<", "String", ">", "paths", "=", "findPaths", "(", "path", ",", "true", ")", ";", "Map", "<", "String", ",", "Integer", ">", "results", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "subPath", ":", "paths", ")", "{", "if", "(", "subPath", ".", "endsWith", "(", "\".java\"", ")", "||", "subPath", ".", "endsWith", "(", "\".class\"", ")", ")", "{", "String", "qualifiedName", "=", "PathUtil", ".", "classFilePathToClassname", "(", "subPath", ")", ";", "addClassToMap", "(", "results", ",", "qualifiedName", ")", ";", "}", "}", "return", "results", ";", "}" ]
Recursively scan the provided path and return a list of all Java packages contained therein.
[ "Recursively", "scan", "the", "provided", "path", "and", "return", "a", "list", "of", "all", "Java", "packages", "contained", "therein", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DiscoverPackagesCommand.java#L140-L153
159,809
windup/windup
rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/service/XsltTransformationService.java
XsltTransformationService.getTransformedXSLTPath
public Path getTransformedXSLTPath(FileModel payload) { ReportService reportService = new ReportService(getGraphContext()); Path outputPath = reportService.getReportDirectory(); outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload)); if (!Files.isDirectory(outputPath)) { try { Files.createDirectories(outputPath); } catch (IOException e) { throw new WindupException("Failed to create output directory at: " + outputPath + " due to: " + e.getMessage(), e); } } return outputPath; }
java
public Path getTransformedXSLTPath(FileModel payload) { ReportService reportService = new ReportService(getGraphContext()); Path outputPath = reportService.getReportDirectory(); outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload)); if (!Files.isDirectory(outputPath)) { try { Files.createDirectories(outputPath); } catch (IOException e) { throw new WindupException("Failed to create output directory at: " + outputPath + " due to: " + e.getMessage(), e); } } return outputPath; }
[ "public", "Path", "getTransformedXSLTPath", "(", "FileModel", "payload", ")", "{", "ReportService", "reportService", "=", "new", "ReportService", "(", "getGraphContext", "(", ")", ")", ";", "Path", "outputPath", "=", "reportService", ".", "getReportDirectory", "(", ")", ";", "outputPath", "=", "outputPath", ".", "resolve", "(", "this", ".", "getRelativeTransformedXSLTPath", "(", "payload", ")", ")", ";", "if", "(", "!", "Files", ".", "isDirectory", "(", "outputPath", ")", ")", "{", "try", "{", "Files", ".", "createDirectories", "(", "outputPath", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "WindupException", "(", "\"Failed to create output directory at: \"", "+", "outputPath", "+", "\" due to: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "return", "outputPath", ";", "}" ]
Gets the path used for the results of XSLT Transforms.
[ "Gets", "the", "path", "used", "for", "the", "results", "of", "XSLT", "Transforms", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/service/XsltTransformationService.java#L33-L51
159,810
windup/windup
rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/util/HibernateDialectDataSourceTypeResolver.java
HibernateDialectDataSourceTypeResolver.resolveDataSourceTypeFromDialect
public static String resolveDataSourceTypeFromDialect(String dialect) { if (StringUtils.contains(dialect, "Oracle")) { return "Oracle"; } else if (StringUtils.contains(dialect, "MySQL")) { return "MySQL"; } else if (StringUtils.contains(dialect, "DB2390Dialect")) { return "DB2/390"; } else if (StringUtils.contains(dialect, "DB2400Dialect")) { return "DB2/400"; } else if (StringUtils.contains(dialect, "DB2")) { return "DB2"; } else if (StringUtils.contains(dialect, "Ingres")) { return "Ingres"; } else if (StringUtils.contains(dialect, "Derby")) { return "Derby"; } else if (StringUtils.contains(dialect, "Pointbase")) { return "Pointbase"; } else if (StringUtils.contains(dialect, "Postgres")) { return "Postgres"; } else if (StringUtils.contains(dialect, "SQLServer")) { return "SQLServer"; } else if (StringUtils.contains(dialect, "Sybase")) { return "Sybase"; } else if (StringUtils.contains(dialect, "HSQLDialect")) { return "HyperSQL"; } else if (StringUtils.contains(dialect, "H2Dialect")) { return "H2"; } return dialect; }
java
public static String resolveDataSourceTypeFromDialect(String dialect) { if (StringUtils.contains(dialect, "Oracle")) { return "Oracle"; } else if (StringUtils.contains(dialect, "MySQL")) { return "MySQL"; } else if (StringUtils.contains(dialect, "DB2390Dialect")) { return "DB2/390"; } else if (StringUtils.contains(dialect, "DB2400Dialect")) { return "DB2/400"; } else if (StringUtils.contains(dialect, "DB2")) { return "DB2"; } else if (StringUtils.contains(dialect, "Ingres")) { return "Ingres"; } else if (StringUtils.contains(dialect, "Derby")) { return "Derby"; } else if (StringUtils.contains(dialect, "Pointbase")) { return "Pointbase"; } else if (StringUtils.contains(dialect, "Postgres")) { return "Postgres"; } else if (StringUtils.contains(dialect, "SQLServer")) { return "SQLServer"; } else if (StringUtils.contains(dialect, "Sybase")) { return "Sybase"; } else if (StringUtils.contains(dialect, "HSQLDialect")) { return "HyperSQL"; } else if (StringUtils.contains(dialect, "H2Dialect")) { return "H2"; } return dialect; }
[ "public", "static", "String", "resolveDataSourceTypeFromDialect", "(", "String", "dialect", ")", "{", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"Oracle\"", ")", ")", "{", "return", "\"Oracle\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"MySQL\"", ")", ")", "{", "return", "\"MySQL\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"DB2390Dialect\"", ")", ")", "{", "return", "\"DB2/390\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"DB2400Dialect\"", ")", ")", "{", "return", "\"DB2/400\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"DB2\"", ")", ")", "{", "return", "\"DB2\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"Ingres\"", ")", ")", "{", "return", "\"Ingres\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"Derby\"", ")", ")", "{", "return", "\"Derby\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"Pointbase\"", ")", ")", "{", "return", "\"Pointbase\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"Postgres\"", ")", ")", "{", "return", "\"Postgres\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"SQLServer\"", ")", ")", "{", "return", "\"SQLServer\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"Sybase\"", ")", ")", "{", "return", "\"Sybase\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"HSQLDialect\"", ")", ")", "{", "return", "\"HyperSQL\"", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "dialect", ",", "\"H2Dialect\"", ")", ")", "{", "return", "\"H2\"", ";", "}", "return", "dialect", ";", "}" ]
Converts the given dislect to a human-readable datasource type.
[ "Converts", "the", "given", "dislect", "to", "a", "human", "-", "readable", "datasource", "type", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/util/HibernateDialectDataSourceTypeResolver.java#L15-L72
159,811
windup/windup
rules-java-archives/addon/src/main/java/org/jboss/windup/rules/apps/java/archives/ignore/SkippedArchives.java
SkippedArchives.load
public static void load(File file) { try(FileInputStream inputStream = new FileInputStream(file)) { LineIterator it = IOUtils.lineIterator(inputStream, "UTF-8"); while (it.hasNext()) { String line = it.next(); if (!line.startsWith("#") && !line.trim().isEmpty()) { add(line); } } } catch (Exception e) { throw new WindupException("Failed loading archive ignore patterns from [" + file.toString() + "]", e); } }
java
public static void load(File file) { try(FileInputStream inputStream = new FileInputStream(file)) { LineIterator it = IOUtils.lineIterator(inputStream, "UTF-8"); while (it.hasNext()) { String line = it.next(); if (!line.startsWith("#") && !line.trim().isEmpty()) { add(line); } } } catch (Exception e) { throw new WindupException("Failed loading archive ignore patterns from [" + file.toString() + "]", e); } }
[ "public", "static", "void", "load", "(", "File", "file", ")", "{", "try", "(", "FileInputStream", "inputStream", "=", "new", "FileInputStream", "(", "file", ")", ")", "{", "LineIterator", "it", "=", "IOUtils", ".", "lineIterator", "(", "inputStream", ",", "\"UTF-8\"", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "String", "line", "=", "it", ".", "next", "(", ")", ";", "if", "(", "!", "line", ".", "startsWith", "(", "\"#\"", ")", "&&", "!", "line", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "add", "(", "line", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "WindupException", "(", "\"Failed loading archive ignore patterns from [\"", "+", "file", ".", "toString", "(", ")", "+", "\"]\"", ",", "e", ")", ";", "}", "}" ]
Load the given configuration file.
[ "Load", "the", "given", "configuration", "file", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-archives/addon/src/main/java/org/jboss/windup/rules/apps/java/archives/ignore/SkippedArchives.java#L39-L57
159,812
windup/windup
config/api/src/main/java/org/jboss/windup/config/operation/Iteration.java
Iteration.perform
@Override public void perform(Rewrite event, EvaluationContext context) { perform((GraphRewrite) event, context); }
java
@Override public void perform(Rewrite event, EvaluationContext context) { perform((GraphRewrite) event, context); }
[ "@", "Override", "public", "void", "perform", "(", "Rewrite", "event", ",", "EvaluationContext", "context", ")", "{", "perform", "(", "(", "GraphRewrite", ")", "event", ",", "context", ")", ";", "}" ]
Called internally to actually process the Iteration.
[ "Called", "internally", "to", "actually", "process", "the", "Iteration", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/Iteration.java#L249-L253
159,813
windup/windup
config/api/src/main/java/org/jboss/windup/config/metadata/MetadataBuilder.java
MetadataBuilder.join
@SafeVarargs private final <T> Set<T> join(Set<T>... sets) { Set<T> result = new HashSet<>(); if (sets == null) return result; for (Set<T> set : sets) { if (set != null) result.addAll(set); } return result; }
java
@SafeVarargs private final <T> Set<T> join(Set<T>... sets) { Set<T> result = new HashSet<>(); if (sets == null) return result; for (Set<T> set : sets) { if (set != null) result.addAll(set); } return result; }
[ "@", "SafeVarargs", "private", "final", "<", "T", ">", "Set", "<", "T", ">", "join", "(", "Set", "<", "T", ">", "...", "sets", ")", "{", "Set", "<", "T", ">", "result", "=", "new", "HashSet", "<>", "(", ")", ";", "if", "(", "sets", "==", "null", ")", "return", "result", ";", "for", "(", "Set", "<", "T", ">", "set", ":", "sets", ")", "{", "if", "(", "set", "!=", "null", ")", "result", ".", "addAll", "(", "set", ")", ";", "}", "return", "result", ";", "}" ]
Join N sets.
[ "Join", "N", "sets", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/metadata/MetadataBuilder.java#L549-L562
159,814
windup/windup
reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java
IssueCategoryRegistry.getIssueCategories
public List<IssueCategory> getIssueCategories() { return this.issueCategories.values().stream() .sorted((category1, category2) -> category1.getPriority() - category2.getPriority()) .collect(Collectors.toList()); }
java
public List<IssueCategory> getIssueCategories() { return this.issueCategories.values().stream() .sorted((category1, category2) -> category1.getPriority() - category2.getPriority()) .collect(Collectors.toList()); }
[ "public", "List", "<", "IssueCategory", ">", "getIssueCategories", "(", ")", "{", "return", "this", ".", "issueCategories", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "sorted", "(", "(", "category1", ",", "category2", ")", "->", "category1", ".", "getPriority", "(", ")", "-", "category2", ".", "getPriority", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Returns a list ordered from the highest priority to the lowest.
[ "Returns", "a", "list", "ordered", "from", "the", "highest", "priority", "to", "the", "lowest", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java#L154-L159
159,815
windup/windup
reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java
IssueCategoryRegistry.addDefaults
private void addDefaults() { this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true)); this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true)); this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true)); }
java
private void addDefaults() { this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true)); this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true)); this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true)); }
[ "private", "void", "addDefaults", "(", ")", "{", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "MANDATORY", ",", "new", "IssueCategory", "(", "MANDATORY", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Mandatory\"", ",", "MANDATORY", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "OPTIONAL", ",", "new", "IssueCategory", "(", "OPTIONAL", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Optional\"", ",", "OPTIONAL", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "POTENTIAL", ",", "new", "IssueCategory", "(", "POTENTIAL", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Potential Issues\"", ",", "POTENTIAL", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "CLOUD_MANDATORY", ",", "new", "IssueCategory", "(", "CLOUD_MANDATORY", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Cloud Mandatory\"", ",", "CLOUD_MANDATORY", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "INFORMATION", ",", "new", "IssueCategory", "(", "INFORMATION", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Information\"", ",", "INFORMATION", ",", "1000", ",", "true", ")", ")", ";", "}" ]
Make sure that we have some reasonable defaults available. These would typically be provided by the rulesets in the real world.
[ "Make", "sure", "that", "we", "have", "some", "reasonable", "defaults", "available", ".", "These", "would", "typically", "be", "provided", "by", "the", "rulesets", "in", "the", "real", "world", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java#L165-L172
159,816
windup/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenStructureRenderer.java
MavenStructureRenderer.renderFreemarkerTemplate
private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath) throws IOException, TemplateException { if(templatePath == null) throw new WindupException("templatePath is null"); freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); objectWrapperBuilder.setUseAdaptersForContainers(true); objectWrapperBuilder.setIterableSupport(true); freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build()); freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/')); try (FileWriter fw = new FileWriter(outputPath.toFile())) { template.process(vars, fw); } }
java
private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath) throws IOException, TemplateException { if(templatePath == null) throw new WindupException("templatePath is null"); freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); objectWrapperBuilder.setUseAdaptersForContainers(true); objectWrapperBuilder.setIterableSupport(true); freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build()); freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/')); try (FileWriter fw = new FileWriter(outputPath.toFile())) { template.process(vars, fw); } }
[ "private", "static", "void", "renderFreemarkerTemplate", "(", "Path", "templatePath", ",", "Map", "vars", ",", "Path", "outputPath", ")", "throws", "IOException", ",", "TemplateException", "{", "if", "(", "templatePath", "==", "null", ")", "throw", "new", "WindupException", "(", "\"templatePath is null\"", ")", ";", "freemarker", ".", "template", ".", "Configuration", "freemarkerConfig", "=", "new", "freemarker", ".", "template", ".", "Configuration", "(", "freemarker", ".", "template", ".", "Configuration", ".", "VERSION_2_3_26", ")", ";", "DefaultObjectWrapperBuilder", "objectWrapperBuilder", "=", "new", "DefaultObjectWrapperBuilder", "(", "freemarker", ".", "template", ".", "Configuration", ".", "DEFAULT_INCOMPATIBLE_IMPROVEMENTS", ")", ";", "objectWrapperBuilder", ".", "setUseAdaptersForContainers", "(", "true", ")", ";", "objectWrapperBuilder", ".", "setIterableSupport", "(", "true", ")", ";", "freemarkerConfig", ".", "setObjectWrapper", "(", "objectWrapperBuilder", ".", "build", "(", ")", ")", ";", "freemarkerConfig", ".", "setTemplateLoader", "(", "new", "FurnaceFreeMarkerTemplateLoader", "(", ")", ")", ";", "Template", "template", "=", "freemarkerConfig", ".", "getTemplate", "(", "templatePath", ".", "toString", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ")", ";", "try", "(", "FileWriter", "fw", "=", "new", "FileWriter", "(", "outputPath", ".", "toFile", "(", ")", ")", ")", "{", "template", ".", "process", "(", "vars", ",", "fw", ")", ";", "}", "}" ]
Renders the given FreeMarker template to given directory, using given variables.
[ "Renders", "the", "given", "FreeMarker", "template", "to", "given", "directory", "using", "given", "variables", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenStructureRenderer.java#L120-L137
159,817
windup/windup
utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java
ExecutionStatistics.get
public static synchronized ExecutionStatistics get() { Thread currentThread = Thread.currentThread(); if (stats.get(currentThread) == null) { stats.put(currentThread, new ExecutionStatistics()); } return stats.get(currentThread); }
java
public static synchronized ExecutionStatistics get() { Thread currentThread = Thread.currentThread(); if (stats.get(currentThread) == null) { stats.put(currentThread, new ExecutionStatistics()); } return stats.get(currentThread); }
[ "public", "static", "synchronized", "ExecutionStatistics", "get", "(", ")", "{", "Thread", "currentThread", "=", "Thread", ".", "currentThread", "(", ")", ";", "if", "(", "stats", ".", "get", "(", "currentThread", ")", "==", "null", ")", "{", "stats", ".", "put", "(", "currentThread", ",", "new", "ExecutionStatistics", "(", ")", ")", ";", "}", "return", "stats", ".", "get", "(", "currentThread", ")", ";", "}" ]
Gets the instance associated with the current thread.
[ "Gets", "the", "instance", "associated", "with", "the", "current", "thread", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L48-L56
159,818
windup/windup
utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java
ExecutionStatistics.merge
public void merge() { Thread currentThread = Thread.currentThread(); if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) { throw new IllegalArgumentException("Trying to merge executionstatistics from a " + "different thread that is not registered as main thread of application run"); } for (Thread thread : stats.keySet()) { if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) { merge(stats.get(thread)); } } }
java
public void merge() { Thread currentThread = Thread.currentThread(); if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) { throw new IllegalArgumentException("Trying to merge executionstatistics from a " + "different thread that is not registered as main thread of application run"); } for (Thread thread : stats.keySet()) { if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) { merge(stats.get(thread)); } } }
[ "public", "void", "merge", "(", ")", "{", "Thread", "currentThread", "=", "Thread", ".", "currentThread", "(", ")", ";", "if", "(", "!", "stats", ".", "get", "(", "currentThread", ")", ".", "equals", "(", "this", ")", "||", "currentThread", "instanceof", "WindupChildThread", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Trying to merge executionstatistics from a \"", "+", "\"different thread that is not registered as main thread of application run\"", ")", ";", "}", "for", "(", "Thread", "thread", ":", "stats", ".", "keySet", "(", ")", ")", "{", "if", "(", "thread", "instanceof", "WindupChildThread", "&&", "(", "(", "WindupChildThread", ")", "thread", ")", ".", "getParentThread", "(", ")", ".", "equals", "(", "currentThread", ")", ")", "{", "merge", "(", "stats", ".", "get", "(", "thread", ")", ")", ";", "}", "}", "}" ]
Merge this ExecutionStatistics with all the statistics created within the child threads. All the child threads had to be created using Windup-specific ThreadFactory in order to contain a reference to the parent thread.
[ "Merge", "this", "ExecutionStatistics", "with", "all", "the", "statistics", "created", "within", "the", "child", "threads", ".", "All", "the", "child", "threads", "had", "to", "be", "created", "using", "Windup", "-", "specific", "ThreadFactory", "in", "order", "to", "contain", "a", "reference", "to", "the", "parent", "thread", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L66-L79
159,819
windup/windup
utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java
ExecutionStatistics.merge
private void merge(ExecutionStatistics otherStatistics) { for (String s : otherStatistics.executionInfo.keySet()) { TimingData thisStats = this.executionInfo.get(s); TimingData otherStats = otherStatistics.executionInfo.get(s); if(thisStats == null) { this.executionInfo.put(s,otherStats); } else { thisStats.merge(otherStats); } } }
java
private void merge(ExecutionStatistics otherStatistics) { for (String s : otherStatistics.executionInfo.keySet()) { TimingData thisStats = this.executionInfo.get(s); TimingData otherStats = otherStatistics.executionInfo.get(s); if(thisStats == null) { this.executionInfo.put(s,otherStats); } else { thisStats.merge(otherStats); } } }
[ "private", "void", "merge", "(", "ExecutionStatistics", "otherStatistics", ")", "{", "for", "(", "String", "s", ":", "otherStatistics", ".", "executionInfo", ".", "keySet", "(", ")", ")", "{", "TimingData", "thisStats", "=", "this", ".", "executionInfo", ".", "get", "(", "s", ")", ";", "TimingData", "otherStats", "=", "otherStatistics", ".", "executionInfo", ".", "get", "(", "s", ")", ";", "if", "(", "thisStats", "==", "null", ")", "{", "this", ".", "executionInfo", ".", "put", "(", "s", ",", "otherStats", ")", ";", "}", "else", "{", "thisStats", ".", "merge", "(", "otherStats", ")", ";", "}", "}", "}" ]
Merge two ExecutionStatistics into one. This method is private in order not to be synchronized (merging. @param otherStatistics
[ "Merge", "two", "ExecutionStatistics", "into", "one", ".", "This", "method", "is", "private", "in", "order", "not", "to", "be", "synchronized", "(", "merging", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L85-L97
159,820
windup/windup
utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java
ExecutionStatistics.serializeTimingData
public void serializeTimingData(Path outputPath) { //merge subThreads instances into the main instance merge(); try (FileWriter fw = new FileWriter(outputPath.toFile())) { fw.write("Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\n"); for (Map.Entry<String, TimingData> timing : executionInfo.entrySet()) { TimingData data = timing.getValue(); long totalMillis = (data.totalNanos / 1000000); double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions; fw.write(String.format("%6d, %6d, %8.2f, %s\n", data.numberOfExecutions, totalMillis, millisPerExecution, StringEscapeUtils.escapeCsv(timing.getKey()) )); } } catch (Exception e) { e.printStackTrace(); } }
java
public void serializeTimingData(Path outputPath) { //merge subThreads instances into the main instance merge(); try (FileWriter fw = new FileWriter(outputPath.toFile())) { fw.write("Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\n"); for (Map.Entry<String, TimingData> timing : executionInfo.entrySet()) { TimingData data = timing.getValue(); long totalMillis = (data.totalNanos / 1000000); double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions; fw.write(String.format("%6d, %6d, %8.2f, %s\n", data.numberOfExecutions, totalMillis, millisPerExecution, StringEscapeUtils.escapeCsv(timing.getKey()) )); } } catch (Exception e) { e.printStackTrace(); } }
[ "public", "void", "serializeTimingData", "(", "Path", "outputPath", ")", "{", "//merge subThreads instances into the main instance", "merge", "(", ")", ";", "try", "(", "FileWriter", "fw", "=", "new", "FileWriter", "(", "outputPath", ".", "toFile", "(", ")", ")", ")", "{", "fw", ".", "write", "(", "\"Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\\n\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "TimingData", ">", "timing", ":", "executionInfo", ".", "entrySet", "(", ")", ")", "{", "TimingData", "data", "=", "timing", ".", "getValue", "(", ")", ";", "long", "totalMillis", "=", "(", "data", ".", "totalNanos", "/", "1000000", ")", ";", "double", "millisPerExecution", "=", "(", "double", ")", "totalMillis", "/", "(", "double", ")", "data", ".", "numberOfExecutions", ";", "fw", ".", "write", "(", "String", ".", "format", "(", "\"%6d, %6d, %8.2f, %s\\n\"", ",", "data", ".", "numberOfExecutions", ",", "totalMillis", ",", "millisPerExecution", ",", "StringEscapeUtils", ".", "escapeCsv", "(", "timing", ".", "getKey", "(", ")", ")", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Serializes the timing data to a "~" delimited file at outputPath.
[ "Serializes", "the", "timing", "data", "to", "a", "~", "delimited", "file", "at", "outputPath", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L111-L134
159,821
windup/windup
utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java
ExecutionStatistics.begin
public void begin(String key) { if (key == null) { return; } TimingData data = executionInfo.get(key); if (data == null) { data = new TimingData(key); executionInfo.put(key, data); } data.begin(); }
java
public void begin(String key) { if (key == null) { return; } TimingData data = executionInfo.get(key); if (data == null) { data = new TimingData(key); executionInfo.put(key, data); } data.begin(); }
[ "public", "void", "begin", "(", "String", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", ";", "}", "TimingData", "data", "=", "executionInfo", ".", "get", "(", "key", ")", ";", "if", "(", "data", "==", "null", ")", "{", "data", "=", "new", "TimingData", "(", "key", ")", ";", "executionInfo", ".", "put", "(", "key", ",", "data", ")", ";", "}", "data", ".", "begin", "(", ")", ";", "}" ]
Start timing an operation with the given identifier.
[ "Start", "timing", "an", "operation", "with", "the", "given", "identifier", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L153-L166
159,822
windup/windup
utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java
ExecutionStatistics.end
public void end(String key) { if (key == null) { return; } TimingData data = executionInfo.get(key); if (data == null) { LOG.info("Called end with key: " + key + " without ever calling begin"); return; } data.end(); }
java
public void end(String key) { if (key == null) { return; } TimingData data = executionInfo.get(key); if (data == null) { LOG.info("Called end with key: " + key + " without ever calling begin"); return; } data.end(); }
[ "public", "void", "end", "(", "String", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", ";", "}", "TimingData", "data", "=", "executionInfo", ".", "get", "(", "key", ")", ";", "if", "(", "data", "==", "null", ")", "{", "LOG", ".", "info", "(", "\"Called end with key: \"", "+", "key", "+", "\" without ever calling begin\"", ")", ";", "return", ";", "}", "data", ".", "end", "(", ")", ";", "}" ]
Complete timing the operation with the given identifier. If you had not previously started a timing operation with this identifier, then this will effectively be a noop.
[ "Complete", "timing", "the", "operation", "with", "the", "given", "identifier", ".", "If", "you", "had", "not", "previously", "started", "a", "timing", "operation", "with", "this", "identifier", "then", "this", "will", "effectively", "be", "a", "noop", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L172-L185
159,823
windup/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/PackagesToContainingMavenArtifactsIndex.java
PackagesToContainingMavenArtifactsIndex.registerPackageInTypeInterestFactory
private void registerPackageInTypeInterestFactory(String pkg) { TypeInterestFactory.registerInterest(pkg + "_pkg", pkg.replace(".", "\\."), pkg, TypeReferenceLocation.IMPORT); // TODO: Finish the implementation }
java
private void registerPackageInTypeInterestFactory(String pkg) { TypeInterestFactory.registerInterest(pkg + "_pkg", pkg.replace(".", "\\."), pkg, TypeReferenceLocation.IMPORT); // TODO: Finish the implementation }
[ "private", "void", "registerPackageInTypeInterestFactory", "(", "String", "pkg", ")", "{", "TypeInterestFactory", ".", "registerInterest", "(", "pkg", "+", "\"_pkg\"", ",", "pkg", ".", "replace", "(", "\".\"", ",", "\"\\\\.\"", ")", ",", "pkg", ",", "TypeReferenceLocation", ".", "IMPORT", ")", ";", "// TODO: Finish the implementation", "}" ]
So that we get these packages caught Java class analysis.
[ "So", "that", "we", "get", "these", "packages", "caught", "Java", "class", "analysis", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/PackagesToContainingMavenArtifactsIndex.java#L120-L124
159,824
windup/windup
rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java
XMLDocumentCache.cache
public static void cache(XmlFileModel key, Document document) { String cacheKey = getKey(key); map.put(cacheKey, new CacheDocument(false, document)); }
java
public static void cache(XmlFileModel key, Document document) { String cacheKey = getKey(key); map.put(cacheKey, new CacheDocument(false, document)); }
[ "public", "static", "void", "cache", "(", "XmlFileModel", "key", ",", "Document", "document", ")", "{", "String", "cacheKey", "=", "getKey", "(", "key", ")", ";", "map", ".", "put", "(", "cacheKey", ",", "new", "CacheDocument", "(", "false", ",", "document", ")", ")", ";", "}" ]
Add the provided document to the cache.
[ "Add", "the", "provided", "document", "to", "the", "cache", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java#L51-L55
159,825
windup/windup
rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java
XMLDocumentCache.cacheParseFailure
public static void cacheParseFailure(XmlFileModel key) { map.put(getKey(key), new CacheDocument(true, null)); }
java
public static void cacheParseFailure(XmlFileModel key) { map.put(getKey(key), new CacheDocument(true, null)); }
[ "public", "static", "void", "cacheParseFailure", "(", "XmlFileModel", "key", ")", "{", "map", ".", "put", "(", "getKey", "(", "key", ")", ",", "new", "CacheDocument", "(", "true", ",", "null", ")", ")", ";", "}" ]
Cache a parse failure for this document.
[ "Cache", "a", "parse", "failure", "for", "this", "document", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java#L60-L63
159,826
windup/windup
rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java
XMLDocumentCache.get
public static Result get(XmlFileModel key) { String cacheKey = getKey(key); Result result = null; CacheDocument reference = map.get(cacheKey); if (reference == null) return new Result(false, null); if (reference.parseFailure) return new Result(true, null); Document document = reference.getDocument(); if (document == null) LOG.info("Cache miss on XML document: " + cacheKey); return new Result(false, document); }
java
public static Result get(XmlFileModel key) { String cacheKey = getKey(key); Result result = null; CacheDocument reference = map.get(cacheKey); if (reference == null) return new Result(false, null); if (reference.parseFailure) return new Result(true, null); Document document = reference.getDocument(); if (document == null) LOG.info("Cache miss on XML document: " + cacheKey); return new Result(false, document); }
[ "public", "static", "Result", "get", "(", "XmlFileModel", "key", ")", "{", "String", "cacheKey", "=", "getKey", "(", "key", ")", ";", "Result", "result", "=", "null", ";", "CacheDocument", "reference", "=", "map", ".", "get", "(", "cacheKey", ")", ";", "if", "(", "reference", "==", "null", ")", "return", "new", "Result", "(", "false", ",", "null", ")", ";", "if", "(", "reference", ".", "parseFailure", ")", "return", "new", "Result", "(", "true", ",", "null", ")", ";", "Document", "document", "=", "reference", ".", "getDocument", "(", ")", ";", "if", "(", "document", "==", "null", ")", "LOG", ".", "info", "(", "\"Cache miss on XML document: \"", "+", "cacheKey", ")", ";", "return", "new", "Result", "(", "false", ",", "document", ")", ";", "}" ]
Retrieve the currently cached value for the given document.
[ "Retrieve", "the", "currently", "cached", "value", "for", "the", "given", "document", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java#L68-L86
159,827
windup/windup
decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/LineNumberFormatter.java
LineNumberFormatter.reformatFile
public void reformatFile() throws IOException { List<LineNumberPosition> lineBrokenPositions = new ArrayList<>(); List<String> brokenLines = breakLines(lineBrokenPositions); emitFormatted(brokenLines, lineBrokenPositions); }
java
public void reformatFile() throws IOException { List<LineNumberPosition> lineBrokenPositions = new ArrayList<>(); List<String> brokenLines = breakLines(lineBrokenPositions); emitFormatted(brokenLines, lineBrokenPositions); }
[ "public", "void", "reformatFile", "(", ")", "throws", "IOException", "{", "List", "<", "LineNumberPosition", ">", "lineBrokenPositions", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "String", ">", "brokenLines", "=", "breakLines", "(", "lineBrokenPositions", ")", ";", "emitFormatted", "(", "brokenLines", ",", "lineBrokenPositions", ")", ";", "}" ]
Rewrites the file passed to 'this' constructor so that the actual line numbers match the recipe passed to 'this' constructor.
[ "Rewrites", "the", "file", "passed", "to", "this", "constructor", "so", "that", "the", "actual", "line", "numbers", "match", "the", "recipe", "passed", "to", "this", "constructor", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/LineNumberFormatter.java#L59-L64
159,828
windup/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java
PackageNameMapping.fromPackage
public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern) { PackageNameMapping packageNameMapping = new PackageNameMapping(); packageNameMapping.setPackagePattern(packagePattern); return packageNameMapping; }
java
public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern) { PackageNameMapping packageNameMapping = new PackageNameMapping(); packageNameMapping.setPackagePattern(packagePattern); return packageNameMapping; }
[ "public", "static", "PackageNameMappingWithPackagePattern", "fromPackage", "(", "String", "packagePattern", ")", "{", "PackageNameMapping", "packageNameMapping", "=", "new", "PackageNameMapping", "(", ")", ";", "packageNameMapping", ".", "setPackagePattern", "(", "packagePattern", ")", ";", "return", "packageNameMapping", ";", "}" ]
Sets the package pattern to match against.
[ "Sets", "the", "package", "pattern", "to", "match", "against", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java#L61-L66
159,829
windup/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java
PackageNameMapping.isExclusivelyKnownArchive
public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath) { String extension = StringUtils.substringAfterLast(filePath, "."); if (!StringUtils.equalsIgnoreCase(extension, "jar")) return false; ZipFile archive; try { archive = new ZipFile(filePath); } catch (IOException e) { return false; } WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext()); WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext()); // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything) boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext(); // this should only be true if: // 1) the package does not contain *any* customer packages. // 2) the package contains "known" vendor packages. boolean exclusivelyKnown = false; String organization = null; Enumeration<?> e = archive.entries(); // go through all entries... ZipEntry entry; while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); String entryName = entry.getName(); if (entry.isDirectory() || !StringUtils.endsWith(entryName, ".class")) continue; String classname = PathUtil.classFilePathToClassname(entryName); // if the package isn't current "known", try to match against known packages for this entry. if (!exclusivelyKnown) { organization = getOrganizationForPackage(event, classname); if (organization != null) { exclusivelyKnown = true; } else { // we couldn't find a package definitively, so ignore the archive exclusivelyKnown = false; break; } } // If the user specified package names and this is in those package names, then scan it anyway if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname)) { return false; } } if (exclusivelyKnown) LOG.info("Known Package: " + archive.getName() + "; Organization: " + organization); // Return the evaluated exclusively known value. return exclusivelyKnown; }
java
public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath) { String extension = StringUtils.substringAfterLast(filePath, "."); if (!StringUtils.equalsIgnoreCase(extension, "jar")) return false; ZipFile archive; try { archive = new ZipFile(filePath); } catch (IOException e) { return false; } WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext()); WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext()); // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything) boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext(); // this should only be true if: // 1) the package does not contain *any* customer packages. // 2) the package contains "known" vendor packages. boolean exclusivelyKnown = false; String organization = null; Enumeration<?> e = archive.entries(); // go through all entries... ZipEntry entry; while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); String entryName = entry.getName(); if (entry.isDirectory() || !StringUtils.endsWith(entryName, ".class")) continue; String classname = PathUtil.classFilePathToClassname(entryName); // if the package isn't current "known", try to match against known packages for this entry. if (!exclusivelyKnown) { organization = getOrganizationForPackage(event, classname); if (organization != null) { exclusivelyKnown = true; } else { // we couldn't find a package definitively, so ignore the archive exclusivelyKnown = false; break; } } // If the user specified package names and this is in those package names, then scan it anyway if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname)) { return false; } } if (exclusivelyKnown) LOG.info("Known Package: " + archive.getName() + "; Organization: " + organization); // Return the evaluated exclusively known value. return exclusivelyKnown; }
[ "public", "static", "boolean", "isExclusivelyKnownArchive", "(", "GraphRewrite", "event", ",", "String", "filePath", ")", "{", "String", "extension", "=", "StringUtils", ".", "substringAfterLast", "(", "filePath", ",", "\".\"", ")", ";", "if", "(", "!", "StringUtils", ".", "equalsIgnoreCase", "(", "extension", ",", "\"jar\"", ")", ")", "return", "false", ";", "ZipFile", "archive", ";", "try", "{", "archive", "=", "new", "ZipFile", "(", "filePath", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "false", ";", "}", "WindupJavaConfigurationService", "javaConfigurationService", "=", "new", "WindupJavaConfigurationService", "(", "event", ".", "getGraphContext", "(", ")", ")", ";", "WindupJavaConfigurationModel", "javaConfigurationModel", "=", "WindupJavaConfigurationService", ".", "getJavaConfigurationModel", "(", "event", ".", "getGraphContext", "(", ")", ")", ";", "// indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)", "boolean", "customerPackagesSpecified", "=", "javaConfigurationModel", ".", "getScanJavaPackages", "(", ")", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", ";", "// this should only be true if:", "// 1) the package does not contain *any* customer packages.", "// 2) the package contains \"known\" vendor packages.", "boolean", "exclusivelyKnown", "=", "false", ";", "String", "organization", "=", "null", ";", "Enumeration", "<", "?", ">", "e", "=", "archive", ".", "entries", "(", ")", ";", "// go through all entries...", "ZipEntry", "entry", ";", "while", "(", "e", ".", "hasMoreElements", "(", ")", ")", "{", "entry", "=", "(", "ZipEntry", ")", "e", ".", "nextElement", "(", ")", ";", "String", "entryName", "=", "entry", ".", "getName", "(", ")", ";", "if", "(", "entry", ".", "isDirectory", "(", ")", "||", "!", "StringUtils", ".", "endsWith", "(", "entryName", ",", "\".class\"", ")", ")", "continue", ";", "String", "classname", "=", "PathUtil", ".", "classFilePathToClassname", "(", "entryName", ")", ";", "// if the package isn't current \"known\", try to match against known packages for this entry.", "if", "(", "!", "exclusivelyKnown", ")", "{", "organization", "=", "getOrganizationForPackage", "(", "event", ",", "classname", ")", ";", "if", "(", "organization", "!=", "null", ")", "{", "exclusivelyKnown", "=", "true", ";", "}", "else", "{", "// we couldn't find a package definitively, so ignore the archive", "exclusivelyKnown", "=", "false", ";", "break", ";", "}", "}", "// If the user specified package names and this is in those package names, then scan it anyway", "if", "(", "customerPackagesSpecified", "&&", "javaConfigurationService", ".", "shouldScanPackage", "(", "classname", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "exclusivelyKnown", ")", "LOG", ".", "info", "(", "\"Known Package: \"", "+", "archive", ".", "getName", "(", ")", "+", "\"; Organization: \"", "+", "organization", ")", ";", "// Return the evaluated exclusively known value.", "return", "exclusivelyKnown", ";", "}" ]
Indicates that all of the packages within an archive are "known" by the package mapper. Generally this indicates that the archive does not contain customer code.
[ "Indicates", "that", "all", "of", "the", "packages", "within", "an", "archive", "are", "known", "by", "the", "package", "mapper", ".", "Generally", "this", "indicates", "that", "the", "archive", "does", "not", "contain", "customer", "code", "." ]
6668f09e7f012d24a0b4212ada8809417225b2ad
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java#L89-L157
159,830
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java
HullWhiteModel.getShortRate
private RandomVariable getShortRate(int timeIndex) throws CalculationException { double time = getProcess().getTime(timeIndex); double timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time; double timeNext = getProcess().getTime(timeIndex+1); RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time); RandomVariable alpha = getDV(0, time); RandomVariable value = getProcess().getProcessValue(timeIndex, 0); value = value.add(alpha); // value = value.sub(Math.log(value.exp().getAverage())); value = value.add(zeroRate); return value; }
java
private RandomVariable getShortRate(int timeIndex) throws CalculationException { double time = getProcess().getTime(timeIndex); double timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time; double timeNext = getProcess().getTime(timeIndex+1); RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time); RandomVariable alpha = getDV(0, time); RandomVariable value = getProcess().getProcessValue(timeIndex, 0); value = value.add(alpha); // value = value.sub(Math.log(value.exp().getAverage())); value = value.add(zeroRate); return value; }
[ "private", "RandomVariable", "getShortRate", "(", "int", "timeIndex", ")", "throws", "CalculationException", "{", "double", "time", "=", "getProcess", "(", ")", ".", "getTime", "(", "timeIndex", ")", ";", "double", "timePrev", "=", "timeIndex", ">", "0", "?", "getProcess", "(", ")", ".", "getTime", "(", "timeIndex", "-", "1", ")", ":", "time", ";", "double", "timeNext", "=", "getProcess", "(", ")", ".", "getTime", "(", "timeIndex", "+", "1", ")", ";", "RandomVariable", "zeroRate", "=", "getZeroRateFromForwardCurve", "(", "time", ")", ";", "//getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);", "RandomVariable", "alpha", "=", "getDV", "(", "0", ",", "time", ")", ";", "RandomVariable", "value", "=", "getProcess", "(", ")", ".", "getProcessValue", "(", "timeIndex", ",", "0", ")", ";", "value", "=", "value", ".", "add", "(", "alpha", ")", ";", "//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));", "value", "=", "value", ".", "add", "(", "zeroRate", ")", ";", "return", "value", ";", "}" ]
Returns the "short rate" from timeIndex to timeIndex+1. @param timeIndex The time index (corresponding to {@link getTime()). @return The "short rate" from timeIndex to timeIndex+1. @throws CalculationException Thrown if simulation failed.
[ "Returns", "the", "short", "rate", "from", "timeIndex", "to", "timeIndex", "+", "1", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java#L492-L508
159,831
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesATMOptionValue
public static double blackScholesATMOptionValue( double volatility, double optionMaturity, double forward, double payoffUnit) { if(optionMaturity < 0) { return 0.0; } // Calculate analytic value double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity); double dMinus = -dPlus; double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit; return valueAnalytic; }
java
public static double blackScholesATMOptionValue( double volatility, double optionMaturity, double forward, double payoffUnit) { if(optionMaturity < 0) { return 0.0; } // Calculate analytic value double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity); double dMinus = -dPlus; double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit; return valueAnalytic; }
[ "public", "static", "double", "blackScholesATMOptionValue", "(", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "forward", ",", "double", "payoffUnit", ")", "{", "if", "(", "optionMaturity", "<", "0", ")", "{", "return", "0.0", ";", "}", "// Calculate analytic value", "double", "dPlus", "=", "0.5", "*", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ";", "double", "dMinus", "=", "-", "dPlus", ";", "double", "valueAnalytic", "=", "(", "NormalDistribution", ".", "cumulativeDistribution", "(", "dPlus", ")", "-", "NormalDistribution", ".", "cumulativeDistribution", "(", "dMinus", ")", ")", "*", "forward", "*", "payoffUnit", ";", "return", "valueAnalytic", ";", "}" ]
Calculates the Black-Scholes option value of an atm call option. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit. @param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff. @return Returns the value of a European at-the-money call option under the Black-Scholes model
[ "Calculates", "the", "Black", "-", "Scholes", "option", "value", "of", "an", "atm", "call", "option", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L187-L204
159,832
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesOptionRho
public static double blackScholesOptionRho( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate rho double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return rho; } }
java
public static double blackScholesOptionRho( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate rho double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return rho; } }
[ "public", "static", "double", "blackScholesOptionRho", "(", "double", "initialStockValue", ",", "double", "riskFreeRate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "if", "(", "optionStrike", "<=", "0.0", "||", "optionMaturity", "<=", "0.0", ")", "{", "// The Black-Scholes model does not consider it being an option", "return", "0.0", ";", "}", "else", "{", "// Calculate rho", "double", "dMinus", "=", "(", "Math", ".", "log", "(", "initialStockValue", "/", "optionStrike", ")", "+", "(", "riskFreeRate", "-", "0.5", "*", "volatility", "*", "volatility", ")", "*", "optionMaturity", ")", "/", "(", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ")", ";", "double", "rho", "=", "optionStrike", "*", "optionMaturity", "*", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", "*", "NormalDistribution", ".", "cumulativeDistribution", "(", "dMinus", ")", ";", "return", "rho", ";", "}", "}" ]
This static method calculated the rho of a call option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The rho of the option
[ "This", "static", "method", "calculated", "the", "rho", "of", "a", "call", "option", "under", "a", "Black", "-", "Scholes", "model" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L447-L468
159,833
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesDigitalOptionValue
public static double blackScholesDigitalOptionValue( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0) { // The Black-Scholes model does not consider it being an option return 1.0; } else { // Calculate analytic value double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return valueAnalytic; } }
java
public static double blackScholesDigitalOptionValue( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0) { // The Black-Scholes model does not consider it being an option return 1.0; } else { // Calculate analytic value double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return valueAnalytic; } }
[ "public", "static", "double", "blackScholesDigitalOptionValue", "(", "double", "initialStockValue", ",", "double", "riskFreeRate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "if", "(", "optionStrike", "<=", "0.0", ")", "{", "// The Black-Scholes model does not consider it being an option", "return", "1.0", ";", "}", "else", "{", "// Calculate analytic value", "double", "dPlus", "=", "(", "Math", ".", "log", "(", "initialStockValue", "/", "optionStrike", ")", "+", "(", "riskFreeRate", "+", "0.5", "*", "volatility", "*", "volatility", ")", "*", "optionMaturity", ")", "/", "(", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ")", ";", "double", "dMinus", "=", "dPlus", "-", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ";", "double", "valueAnalytic", "=", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", "*", "NormalDistribution", ".", "cumulativeDistribution", "(", "dMinus", ")", ";", "return", "valueAnalytic", ";", "}", "}" ]
Calculates the Black-Scholes option value of a digital call option. @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return Returns the value of a European call option under the Black-Scholes model
[ "Calculates", "the", "Black", "-", "Scholes", "option", "value", "of", "a", "digital", "call", "option", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L543-L565
159,834
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesDigitalOptionDelta
public static double blackScholesDigitalOptionDelta( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate delta double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility); return delta; } }
java
public static double blackScholesDigitalOptionDelta( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate delta double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility); return delta; } }
[ "public", "static", "double", "blackScholesDigitalOptionDelta", "(", "double", "initialStockValue", ",", "double", "riskFreeRate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "if", "(", "optionStrike", "<=", "0.0", "||", "optionMaturity", "<=", "0.0", ")", "{", "// The Black-Scholes model does not consider it being an option", "return", "0.0", ";", "}", "else", "{", "// Calculate delta", "double", "dPlus", "=", "(", "Math", ".", "log", "(", "initialStockValue", "/", "optionStrike", ")", "+", "(", "riskFreeRate", "+", "0.5", "*", "volatility", "*", "volatility", ")", "*", "optionMaturity", ")", "/", "(", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ")", ";", "double", "dMinus", "=", "dPlus", "-", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ";", "double", "delta", "=", "Math", ".", "exp", "(", "-", "0.5", "*", "dMinus", "*", "dMinus", ")", "/", "(", "Math", ".", "sqrt", "(", "2.0", "*", "Math", ".", "PI", "*", "optionMaturity", ")", "*", "initialStockValue", "*", "volatility", ")", ";", "return", "delta", ";", "}", "}" ]
Calculates the delta of a digital option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The delta of the digital option
[ "Calculates", "the", "delta", "of", "a", "digital", "option", "under", "a", "Black", "-", "Scholes", "model" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L577-L599
159,835
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesDigitalOptionVega
public static double blackScholesDigitalOptionVega( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate vega double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility; return vega; } }
java
public static double blackScholesDigitalOptionVega( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate vega double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility; return vega; } }
[ "public", "static", "double", "blackScholesDigitalOptionVega", "(", "double", "initialStockValue", ",", "double", "riskFreeRate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "if", "(", "optionStrike", "<=", "0.0", "||", "optionMaturity", "<=", "0.0", ")", "{", "// The Black-Scholes model does not consider it being an option", "return", "0.0", ";", "}", "else", "{", "// Calculate vega", "double", "dPlus", "=", "(", "Math", ".", "log", "(", "initialStockValue", "/", "optionStrike", ")", "+", "(", "riskFreeRate", "+", "0.5", "*", "volatility", "*", "volatility", ")", "*", "optionMaturity", ")", "/", "(", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ")", ";", "double", "dMinus", "=", "dPlus", "-", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ";", "double", "vega", "=", "-", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", "*", "Math", ".", "exp", "(", "-", "0.5", "*", "dMinus", "*", "dMinus", ")", "/", "Math", ".", "sqrt", "(", "2.0", "*", "Math", ".", "PI", ")", "*", "dPlus", "/", "volatility", ";", "return", "vega", ";", "}", "}" ]
Calculates the vega of a digital option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The vega of the digital option
[ "Calculates", "the", "vega", "of", "a", "digital", "option", "under", "a", "Black", "-", "Scholes", "model" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L611-L633
159,836
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesDigitalOptionRho
public static double blackScholesDigitalOptionRho( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else if(optionStrike <= 0.0) { double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity); return rho; } else { // Calculate rho double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus) + Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI); return rho; } }
java
public static double blackScholesDigitalOptionRho( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else if(optionStrike <= 0.0) { double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity); return rho; } else { // Calculate rho double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus) + Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI); return rho; } }
[ "public", "static", "double", "blackScholesDigitalOptionRho", "(", "double", "initialStockValue", ",", "double", "riskFreeRate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "if", "(", "optionMaturity", "<=", "0.0", ")", "{", "// The Black-Scholes model does not consider it being an option", "return", "0.0", ";", "}", "else", "if", "(", "optionStrike", "<=", "0.0", ")", "{", "double", "rho", "=", "-", "optionMaturity", "*", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", ";", "return", "rho", ";", "}", "else", "{", "// Calculate rho", "double", "dMinus", "=", "(", "Math", ".", "log", "(", "initialStockValue", "/", "optionStrike", ")", "+", "(", "riskFreeRate", "-", "0.5", "*", "volatility", "*", "volatility", ")", "*", "optionMaturity", ")", "/", "(", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ")", ";", "double", "rho", "=", "-", "optionMaturity", "*", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", "*", "NormalDistribution", ".", "cumulativeDistribution", "(", "dMinus", ")", "+", "Math", ".", "sqrt", "(", "optionMaturity", ")", "/", "volatility", "*", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", "*", "Math", ".", "exp", "(", "-", "0.5", "*", "dMinus", "*", "dMinus", ")", "/", "Math", ".", "sqrt", "(", "2.0", "*", "Math", ".", "PI", ")", ";", "return", "rho", ";", "}", "}" ]
Calculates the rho of a digital option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The rho of the digital option
[ "Calculates", "the", "rho", "of", "a", "digital", "option", "under", "a", "Black", "-", "Scholes", "model" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L645-L672
159,837
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackModelCapletValue
public static double blackModelCapletValue( double forward, double volatility, double optionMaturity, double optionStrike, double periodLength, double discountFactor) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor); }
java
public static double blackModelCapletValue( double forward, double volatility, double optionMaturity, double optionStrike, double periodLength, double discountFactor) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor); }
[ "public", "static", "double", "blackModelCapletValue", "(", "double", "forward", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ",", "double", "periodLength", ",", "double", "discountFactor", ")", "{", "// May be interpreted as a special version of the Black-Scholes Formula", "return", "AnalyticFormulas", ".", "blackScholesGeneralizedOptionValue", "(", "forward", ",", "volatility", ",", "optionMaturity", ",", "optionStrike", ",", "periodLength", "*", "discountFactor", ")", ";", "}" ]
Calculate the value of a caplet assuming the Black'76 model. @param forward The forward (spot). @param volatility The Black'76 volatility. @param optionMaturity The option maturity @param optionStrike The option strike. @param periodLength The period length of the underlying forward rate. @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). @return Returns the value of a caplet under the Black'76 model
[ "Calculate", "the", "value", "of", "a", "caplet", "assuming", "the", "Black", "76", "model", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L685-L695
159,838
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackModelDgitialCapletValue
public static double blackModelDgitialCapletValue( double forward, double volatility, double periodLength, double discountFactor, double optionMaturity, double optionStrike) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor; }
java
public static double blackModelDgitialCapletValue( double forward, double volatility, double periodLength, double discountFactor, double optionMaturity, double optionStrike) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor; }
[ "public", "static", "double", "blackModelDgitialCapletValue", "(", "double", "forward", ",", "double", "volatility", ",", "double", "periodLength", ",", "double", "discountFactor", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "// May be interpreted as a special version of the Black-Scholes Formula", "return", "AnalyticFormulas", ".", "blackScholesDigitalOptionValue", "(", "forward", ",", "0.0", ",", "volatility", ",", "optionMaturity", ",", "optionStrike", ")", "*", "periodLength", "*", "discountFactor", ";", "}" ]
Calculate the value of a digital caplet assuming the Black'76 model. @param forward The forward (spot). @param volatility The Black'76 volatility. @param periodLength The period length of the underlying forward rate. @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). @param optionMaturity The option maturity @param optionStrike The option strike. @return Returns the price of a digital caplet under the Black'76 model
[ "Calculate", "the", "value", "of", "a", "digital", "caplet", "assuming", "the", "Black", "76", "model", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L708-L718
159,839
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackModelSwaptionValue
public static double blackModelSwaptionValue( double forwardSwaprate, double volatility, double optionMaturity, double optionStrike, double swapAnnuity) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); }
java
public static double blackModelSwaptionValue( double forwardSwaprate, double volatility, double optionMaturity, double optionStrike, double swapAnnuity) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); }
[ "public", "static", "double", "blackModelSwaptionValue", "(", "double", "forwardSwaprate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ",", "double", "swapAnnuity", ")", "{", "// May be interpreted as a special version of the Black-Scholes Formula", "return", "AnalyticFormulas", ".", "blackScholesGeneralizedOptionValue", "(", "forwardSwaprate", ",", "volatility", ",", "optionMaturity", ",", "optionStrike", ",", "swapAnnuity", ")", ";", "}" ]
Calculate the value of a swaption assuming the Black'76 model. @param forwardSwaprate The forward (spot) @param volatility The Black'76 volatility. @param optionMaturity The option maturity. @param optionStrike The option strike. @param swapAnnuity The swap annuity corresponding to the underlying swap. @return Returns the value of a Swaption under the Black'76 model
[ "Calculate", "the", "value", "of", "a", "swaption", "assuming", "the", "Black", "76", "model", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L730-L739
159,840
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.huntKennedyCMSOptionValue
public static double huntKennedyCMSOptionValue( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit, double optionStrike) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity); return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted; }
java
public static double huntKennedyCMSOptionValue( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit, double optionStrike) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity); return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted; }
[ "public", "static", "double", "huntKennedyCMSOptionValue", "(", "double", "forwardSwaprate", ",", "double", "volatility", ",", "double", "swapAnnuity", ",", "double", "optionMaturity", ",", "double", "swapMaturity", ",", "double", "payoffUnit", ",", "double", "optionStrike", ")", "{", "double", "a", "=", "1.0", "/", "swapMaturity", ";", "double", "b", "=", "(", "payoffUnit", "/", "swapAnnuity", "-", "a", ")", "/", "forwardSwaprate", ";", "double", "convexityAdjustment", "=", "Math", ".", "exp", "(", "volatility", "*", "volatility", "*", "optionMaturity", ")", ";", "double", "valueUnadjusted", "=", "blackModelSwaptionValue", "(", "forwardSwaprate", ",", "volatility", ",", "optionMaturity", ",", "optionStrike", ",", "swapAnnuity", ")", ";", "double", "valueAdjusted", "=", "blackModelSwaptionValue", "(", "forwardSwaprate", "*", "convexityAdjustment", ",", "volatility", ",", "optionMaturity", ",", "optionStrike", ",", "swapAnnuity", ")", ";", "return", "a", "*", "valueUnadjusted", "+", "b", "*", "forwardSwaprate", "*", "valueAdjusted", ";", "}" ]
Calculate the value of a CMS option using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment. @param forwardSwaprate The forward swap rate @param volatility Volatility of the log of the swap rate @param swapAnnuity The swap annuity @param optionMaturity The option maturity @param swapMaturity The swap maturity @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date @param optionStrike The option strike @return Value of the CMS option
[ "Calculate", "the", "value", "of", "a", "CMS", "option", "using", "the", "Black", "-", "Scholes", "model", "for", "the", "swap", "rate", "together", "with", "the", "Hunt", "-", "Kennedy", "convexity", "adjustment", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L908-L925
159,841
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.huntKennedyCMSFloorValue
public static double huntKennedyCMSFloorValue( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit, double optionStrike) { double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike); // A floor is an option plus the strike (max(X,K) = max(X-K,0) + K) return huntKennedyCMSOptionValue + optionStrike * payoffUnit; }
java
public static double huntKennedyCMSFloorValue( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit, double optionStrike) { double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike); // A floor is an option plus the strike (max(X,K) = max(X-K,0) + K) return huntKennedyCMSOptionValue + optionStrike * payoffUnit; }
[ "public", "static", "double", "huntKennedyCMSFloorValue", "(", "double", "forwardSwaprate", ",", "double", "volatility", ",", "double", "swapAnnuity", ",", "double", "optionMaturity", ",", "double", "swapMaturity", ",", "double", "payoffUnit", ",", "double", "optionStrike", ")", "{", "double", "huntKennedyCMSOptionValue", "=", "huntKennedyCMSOptionValue", "(", "forwardSwaprate", ",", "volatility", ",", "swapAnnuity", ",", "optionMaturity", ",", "swapMaturity", ",", "payoffUnit", ",", "optionStrike", ")", ";", "// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)", "return", "huntKennedyCMSOptionValue", "+", "optionStrike", "*", "payoffUnit", ";", "}" ]
Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment. @param forwardSwaprate The forward swap rate @param volatility Volatility of the log of the swap rate @param swapAnnuity The swap annuity @param optionMaturity The option maturity @param swapMaturity The swap maturity @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date @param optionStrike The option strike @return Value of the CMS strike
[ "Calculate", "the", "value", "of", "a", "CMS", "strike", "using", "the", "Black", "-", "Scholes", "model", "for", "the", "swap", "rate", "together", "with", "the", "Hunt", "-", "Kennedy", "convexity", "adjustment", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L940-L953
159,842
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.huntKennedyCMSAdjustedRate
public static double huntKennedyCMSAdjustedRate( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); double rateUnadjusted = forwardSwaprate; double rateAdjusted = forwardSwaprate * convexityAdjustment; return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit; }
java
public static double huntKennedyCMSAdjustedRate( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); double rateUnadjusted = forwardSwaprate; double rateAdjusted = forwardSwaprate * convexityAdjustment; return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit; }
[ "public", "static", "double", "huntKennedyCMSAdjustedRate", "(", "double", "forwardSwaprate", ",", "double", "volatility", ",", "double", "swapAnnuity", ",", "double", "optionMaturity", ",", "double", "swapMaturity", ",", "double", "payoffUnit", ")", "{", "double", "a", "=", "1.0", "/", "swapMaturity", ";", "double", "b", "=", "(", "payoffUnit", "/", "swapAnnuity", "-", "a", ")", "/", "forwardSwaprate", ";", "double", "convexityAdjustment", "=", "Math", ".", "exp", "(", "volatility", "*", "volatility", "*", "optionMaturity", ")", ";", "double", "rateUnadjusted", "=", "forwardSwaprate", ";", "double", "rateAdjusted", "=", "forwardSwaprate", "*", "convexityAdjustment", ";", "return", "(", "a", "*", "rateUnadjusted", "+", "b", "*", "forwardSwaprate", "*", "rateAdjusted", ")", "*", "swapAnnuity", "/", "payoffUnit", ";", "}" ]
Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment. @param forwardSwaprate The forward swap rate @param volatility Volatility of the log of the swap rate @param swapAnnuity The swap annuity @param optionMaturity The option maturity @param swapMaturity The swap maturity @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date @return Convexity adjusted forward rate
[ "Calculate", "the", "adjusted", "forward", "swaprate", "corresponding", "to", "a", "change", "of", "payoff", "unit", "from", "the", "given", "swapAnnuity", "to", "the", "given", "payoffUnit", "using", "the", "Black", "-", "Scholes", "model", "for", "the", "swap", "rate", "together", "with", "the", "Hunt", "-", "Kennedy", "convexity", "adjustment", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L967-L983
159,843
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.volatilityConversionLognormalATMtoNormalATM
public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) { double x = lognormalVolatiltiy * Math.sqrt(maturity / 8); double y = org.apache.commons.math3.special.Erf.erf(x); double normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y; return normalVol; }
java
public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) { double x = lognormalVolatiltiy * Math.sqrt(maturity / 8); double y = org.apache.commons.math3.special.Erf.erf(x); double normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y; return normalVol; }
[ "public", "static", "double", "volatilityConversionLognormalATMtoNormalATM", "(", "double", "forward", ",", "double", "displacement", ",", "double", "maturity", ",", "double", "lognormalVolatiltiy", ")", "{", "double", "x", "=", "lognormalVolatiltiy", "*", "Math", ".", "sqrt", "(", "maturity", "/", "8", ")", ";", "double", "y", "=", "org", ".", "apache", ".", "commons", ".", "math3", ".", "special", ".", "Erf", ".", "erf", "(", "x", ")", ";", "double", "normalVol", "=", "Math", ".", "sqrt", "(", "2", "*", "Math", ".", "PI", "/", "maturity", ")", "*", "(", "forward", "+", "displacement", ")", "*", "y", ";", "return", "normalVol", ";", "}" ]
Exact conversion of displaced lognormal ATM volatiltiy to normal ATM volatility. @param forward The forward @param displacement The displacement (considering a displaced lognormal model, otherwise 0. @param maturity The maturity @param lognormalVolatiltiy The (implied) lognormal volatility. @return The (implied) normal volatility. @see <a href="http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2687742">Dimitroff, Fries, Lichtner and Rodi: Lognormal vs Normal Volatilities and Sensitivities in Practice</a>
[ "Exact", "conversion", "of", "displaced", "lognormal", "ATM", "volatiltiy", "to", "normal", "ATM", "volatility", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L1301-L1307
159,844
finmath/finmath-lib
src/main/java/net/finmath/modelling/descriptor/xmlparser/FIPXMLParser.java
FIPXMLParser.getSwapLegProductDescriptor
private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName, DayCountConvention daycountConvention) { boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX"); ArrayList<Period> periods = new ArrayList<>(); ArrayList<Double> notionalsList = new ArrayList<>(); ArrayList<Double> rates = new ArrayList<>(); //extracting data for each period NodeList periodsXML = leg.getElementsByTagName("incomePayment"); for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) { Element periodXML = (Element) periodsXML.item(periodIndex); LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent()); LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent()); LocalDate fixingDate = startDate; LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent()); if(! isFixed) { fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent()); } periods.add(new Period(fixingDate, paymentDate, startDate, endDate)); double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent()); notionalsList.add(new Double(notional)); if(isFixed) { double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent()); rates.add(new Double(fixedRate)); } else { rates.add(new Double(0)); } } ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention); double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray(); double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray(); return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false); }
java
private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName, DayCountConvention daycountConvention) { boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX"); ArrayList<Period> periods = new ArrayList<>(); ArrayList<Double> notionalsList = new ArrayList<>(); ArrayList<Double> rates = new ArrayList<>(); //extracting data for each period NodeList periodsXML = leg.getElementsByTagName("incomePayment"); for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) { Element periodXML = (Element) periodsXML.item(periodIndex); LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent()); LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent()); LocalDate fixingDate = startDate; LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent()); if(! isFixed) { fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent()); } periods.add(new Period(fixingDate, paymentDate, startDate, endDate)); double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent()); notionalsList.add(new Double(notional)); if(isFixed) { double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent()); rates.add(new Double(fixedRate)); } else { rates.add(new Double(0)); } } ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention); double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray(); double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray(); return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false); }
[ "private", "static", "InterestRateSwapLegProductDescriptor", "getSwapLegProductDescriptor", "(", "Element", "leg", ",", "String", "forwardCurveName", ",", "String", "discountCurveName", ",", "DayCountConvention", "daycountConvention", ")", "{", "boolean", "isFixed", "=", "leg", ".", "getElementsByTagName", "(", "\"interestType\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ".", "equalsIgnoreCase", "(", "\"FIX\"", ")", ";", "ArrayList", "<", "Period", ">", "periods", "=", "new", "ArrayList", "<>", "(", ")", ";", "ArrayList", "<", "Double", ">", "notionalsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "ArrayList", "<", "Double", ">", "rates", "=", "new", "ArrayList", "<>", "(", ")", ";", "//extracting data for each period\r", "NodeList", "periodsXML", "=", "leg", ".", "getElementsByTagName", "(", "\"incomePayment\"", ")", ";", "for", "(", "int", "periodIndex", "=", "0", ";", "periodIndex", "<", "periodsXML", ".", "getLength", "(", ")", ";", "periodIndex", "++", ")", "{", "Element", "periodXML", "=", "(", "Element", ")", "periodsXML", ".", "item", "(", "periodIndex", ")", ";", "LocalDate", "startDate", "=", "LocalDate", ".", "parse", "(", "periodXML", ".", "getElementsByTagName", "(", "\"startDate\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ")", ";", "LocalDate", "endDate", "=", "LocalDate", ".", "parse", "(", "periodXML", ".", "getElementsByTagName", "(", "\"endDate\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ")", ";", "LocalDate", "fixingDate", "=", "startDate", ";", "LocalDate", "paymentDate", "=", "LocalDate", ".", "parse", "(", "periodXML", ".", "getElementsByTagName", "(", "\"payDate\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ")", ";", "if", "(", "!", "isFixed", ")", "{", "fixingDate", "=", "LocalDate", ".", "parse", "(", "periodXML", ".", "getElementsByTagName", "(", "\"fixingDate\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ")", ";", "}", "periods", ".", "add", "(", "new", "Period", "(", "fixingDate", ",", "paymentDate", ",", "startDate", ",", "endDate", ")", ")", ";", "double", "notional", "=", "Double", ".", "parseDouble", "(", "periodXML", ".", "getElementsByTagName", "(", "\"nominal\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ")", ";", "notionalsList", ".", "add", "(", "new", "Double", "(", "notional", ")", ")", ";", "if", "(", "isFixed", ")", "{", "double", "fixedRate", "=", "Double", ".", "parseDouble", "(", "periodXML", ".", "getElementsByTagName", "(", "\"fixedRate\"", ")", ".", "item", "(", "0", ")", ".", "getTextContent", "(", ")", ")", ";", "rates", ".", "add", "(", "new", "Double", "(", "fixedRate", ")", ")", ";", "}", "else", "{", "rates", ".", "add", "(", "new", "Double", "(", "0", ")", ")", ";", "}", "}", "ScheduleDescriptor", "schedule", "=", "new", "ScheduleDescriptor", "(", "periods", ",", "daycountConvention", ")", ";", "double", "[", "]", "notionals", "=", "notionalsList", ".", "stream", "(", ")", ".", "mapToDouble", "(", "Double", "::", "doubleValue", ")", ".", "toArray", "(", ")", ";", "double", "[", "]", "spreads", "=", "rates", ".", "stream", "(", ")", ".", "mapToDouble", "(", "Double", "::", "doubleValue", ")", ".", "toArray", "(", ")", ";", "return", "new", "InterestRateSwapLegProductDescriptor", "(", "forwardCurveName", ",", "discountCurveName", ",", "schedule", ",", "notionals", ",", "spreads", ",", "false", ")", ";", "}" ]
Construct an InterestRateSwapLegProductDescriptor from a node in a FIPXML file. @param leg The node containing the leg. @param forwardCurveName Forward curve name form outside the node. @param discountCurveName Discount curve name form outside the node. @param daycountConvention Daycount convention from outside the node. @return Descriptor of the swap leg.
[ "Construct", "an", "InterestRateSwapLegProductDescriptor", "from", "a", "node", "in", "a", "FIPXML", "file", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/descriptor/xmlparser/FIPXMLParser.java#L152-L196
159,845
finmath/finmath-lib
src/main/java/net/finmath/modelling/productfactory/InterestRateMonteCarloProductFactory.java
InterestRateMonteCarloProductFactory.constructLiborIndex
private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) { if(forwardCurveName != null) { //determine average fixing offset and period length double fixingOffset = 0; double periodLength = 0; for(int i = 0; i < schedule.getNumberOfPeriods(); i++) { fixingOffset *= ((double) i) / (i+1); fixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1); periodLength *= ((double) i) / (i+1); periodLength += schedule.getPeriodLength(i) / (i+1); } return new LIBORIndex(forwardCurveName, fixingOffset, periodLength); } else { return null; } }
java
private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) { if(forwardCurveName != null) { //determine average fixing offset and period length double fixingOffset = 0; double periodLength = 0; for(int i = 0; i < schedule.getNumberOfPeriods(); i++) { fixingOffset *= ((double) i) / (i+1); fixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1); periodLength *= ((double) i) / (i+1); periodLength += schedule.getPeriodLength(i) / (i+1); } return new LIBORIndex(forwardCurveName, fixingOffset, periodLength); } else { return null; } }
[ "private", "static", "AbstractIndex", "constructLiborIndex", "(", "String", "forwardCurveName", ",", "Schedule", "schedule", ")", "{", "if", "(", "forwardCurveName", "!=", "null", ")", "{", "//determine average fixing offset and period length", "double", "fixingOffset", "=", "0", ";", "double", "periodLength", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "schedule", ".", "getNumberOfPeriods", "(", ")", ";", "i", "++", ")", "{", "fixingOffset", "*=", "(", "(", "double", ")", "i", ")", "/", "(", "i", "+", "1", ")", ";", "fixingOffset", "+=", "(", "schedule", ".", "getPeriodStart", "(", "i", ")", "-", "schedule", ".", "getFixing", "(", "i", ")", ")", "/", "(", "i", "+", "1", ")", ";", "periodLength", "*=", "(", "(", "double", ")", "i", ")", "/", "(", "i", "+", "1", ")", ";", "periodLength", "+=", "schedule", ".", "getPeriodLength", "(", "i", ")", "/", "(", "i", "+", "1", ")", ";", "}", "return", "new", "LIBORIndex", "(", "forwardCurveName", ",", "fixingOffset", ",", "periodLength", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Construct a Libor index for a given curve and schedule. @param forwardCurveName @param schedule @return The Libor index or null, if forwardCurveName is null.
[ "Construct", "a", "Libor", "index", "for", "a", "given", "curve", "and", "schedule", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/productfactory/InterestRateMonteCarloProductFactory.java#L88-L108
159,846
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionATM.java
SwaptionATM.getImpliedBachelierATMOptionVolatility
public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){ return optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity); }
java
public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){ return optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity); }
[ "public", "RandomVariable", "getImpliedBachelierATMOptionVolatility", "(", "RandomVariable", "optionValue", ",", "double", "optionMaturity", ",", "double", "swapAnnuity", ")", "{", "return", "optionValue", ".", "average", "(", ")", ".", "mult", "(", "Math", ".", "sqrt", "(", "2.0", "*", "Math", ".", "PI", "/", "optionMaturity", ")", "/", "swapAnnuity", ")", ";", "}" ]
Calculates ATM Bachelier implied volatilities. @see net.finmath.functions.AnalyticFormulas#bachelierOptionImpliedVolatility(double, double, double, double, double) @param optionValue RandomVarable representing the value of the option @param optionMaturity Time to maturity. @param swapAnnuity The swap annuity as seen on valuation time. @return The Bachelier implied volatility.
[ "Calculates", "ATM", "Bachelier", "implied", "volatilities", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionATM.java#L73-L75
159,847
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java
BermudanSwaption.getBasisFunctions
public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException { ArrayList<RandomVariable> basisFunctions = new ArrayList<>(); // Constant RandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0); basisFunctions.add(basisFunction); int fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate); if(fixingDateIndex < 0) { fixingDateIndex = -fixingDateIndex; } if(fixingDateIndex >= fixingDates.length) { fixingDateIndex = fixingDates.length-1; } // forward rate to the next period RandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]); RandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert(); basisFunctions.add(discountShort); basisFunctions.add(discountShort.pow(2.0)); // basisFunctions.add(rateShort.pow(3.0)); // forward rate to the end of the product RandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]); RandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert(); basisFunctions.add(discountLong); basisFunctions.add(discountLong.pow(2.0)); // basisFunctions.add(rateLong.pow(3.0)); // Numeraire RandomVariable numeraire = model.getNumeraire(fixingDate).invert(); basisFunctions.add(numeraire); // basisFunctions.add(numeraire.pow(2.0)); // basisFunctions.add(numeraire.pow(3.0)); return basisFunctions.toArray(new RandomVariable[basisFunctions.size()]); }
java
public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException { ArrayList<RandomVariable> basisFunctions = new ArrayList<>(); // Constant RandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0); basisFunctions.add(basisFunction); int fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate); if(fixingDateIndex < 0) { fixingDateIndex = -fixingDateIndex; } if(fixingDateIndex >= fixingDates.length) { fixingDateIndex = fixingDates.length-1; } // forward rate to the next period RandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]); RandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert(); basisFunctions.add(discountShort); basisFunctions.add(discountShort.pow(2.0)); // basisFunctions.add(rateShort.pow(3.0)); // forward rate to the end of the product RandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]); RandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert(); basisFunctions.add(discountLong); basisFunctions.add(discountLong.pow(2.0)); // basisFunctions.add(rateLong.pow(3.0)); // Numeraire RandomVariable numeraire = model.getNumeraire(fixingDate).invert(); basisFunctions.add(numeraire); // basisFunctions.add(numeraire.pow(2.0)); // basisFunctions.add(numeraire.pow(3.0)); return basisFunctions.toArray(new RandomVariable[basisFunctions.size()]); }
[ "public", "RandomVariable", "[", "]", "getBasisFunctions", "(", "double", "fixingDate", ",", "LIBORModelMonteCarloSimulationModel", "model", ")", "throws", "CalculationException", "{", "ArrayList", "<", "RandomVariable", ">", "basisFunctions", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Constant", "RandomVariable", "basisFunction", "=", "new", "RandomVariableFromDoubleArray", "(", "1.0", ")", ";", "//.getRandomVariableForConstant(1.0);", "basisFunctions", ".", "add", "(", "basisFunction", ")", ";", "int", "fixingDateIndex", "=", "Arrays", ".", "binarySearch", "(", "fixingDates", ",", "fixingDate", ")", ";", "if", "(", "fixingDateIndex", "<", "0", ")", "{", "fixingDateIndex", "=", "-", "fixingDateIndex", ";", "}", "if", "(", "fixingDateIndex", ">=", "fixingDates", ".", "length", ")", "{", "fixingDateIndex", "=", "fixingDates", ".", "length", "-", "1", ";", "}", "// forward rate to the next period", "RandomVariable", "rateShort", "=", "model", ".", "getLIBOR", "(", "fixingDate", ",", "fixingDate", ",", "paymentDates", "[", "fixingDateIndex", "]", ")", ";", "RandomVariable", "discountShort", "=", "rateShort", ".", "mult", "(", "paymentDates", "[", "fixingDateIndex", "]", "-", "fixingDate", ")", ".", "add", "(", "1.0", ")", ".", "invert", "(", ")", ";", "basisFunctions", ".", "add", "(", "discountShort", ")", ";", "basisFunctions", ".", "add", "(", "discountShort", ".", "pow", "(", "2.0", ")", ")", ";", "//\t\tbasisFunctions.add(rateShort.pow(3.0));", "// forward rate to the end of the product", "RandomVariable", "rateLong", "=", "model", ".", "getLIBOR", "(", "fixingDate", ",", "fixingDates", "[", "fixingDateIndex", "]", ",", "paymentDates", "[", "paymentDates", ".", "length", "-", "1", "]", ")", ";", "RandomVariable", "discountLong", "=", "rateLong", ".", "mult", "(", "paymentDates", "[", "paymentDates", ".", "length", "-", "1", "]", "-", "fixingDates", "[", "fixingDateIndex", "]", ")", ".", "add", "(", "1.0", ")", ".", "invert", "(", ")", ";", "basisFunctions", ".", "add", "(", "discountLong", ")", ";", "basisFunctions", ".", "add", "(", "discountLong", ".", "pow", "(", "2.0", ")", ")", ";", "//\t\tbasisFunctions.add(rateLong.pow(3.0));", "// Numeraire", "RandomVariable", "numeraire", "=", "model", ".", "getNumeraire", "(", "fixingDate", ")", ".", "invert", "(", ")", ";", "basisFunctions", ".", "add", "(", "numeraire", ")", ";", "//\t\tbasisFunctions.add(numeraire.pow(2.0));", "//\t\tbasisFunctions.add(numeraire.pow(3.0));", "return", "basisFunctions", ".", "toArray", "(", "new", "RandomVariable", "[", "basisFunctions", ".", "size", "(", ")", "]", ")", ";", "}" ]
Return the basis functions for the regression suitable for this product. @param fixingDate The condition time. @param model The model @return The basis functions for the regression suitable for this product. @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "Return", "the", "basis", "functions", "for", "the", "regression", "suitable", "for", "this", "product", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java#L214-L251
159,848
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/interestrate/LIBORMarketModelStandard.java
LIBORMarketModelStandard.getDrift
private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) { // Check if this LIBOR is already fixed if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) { return null; } /* * We implemented several different methods to calculate the drift */ if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) { RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex); RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor); drift = drift.add(driftEulerWithPredictor).div(2.0); return drift; } else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) { return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor); } else { return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex); } }
java
private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) { // Check if this LIBOR is already fixed if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) { return null; } /* * We implemented several different methods to calculate the drift */ if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) { RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex); RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor); drift = drift.add(driftEulerWithPredictor).div(2.0); return drift; } else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) { return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor); } else { return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex); } }
[ "private", "RandomVariableInterface", "getDrift", "(", "int", "timeIndex", ",", "int", "componentIndex", ",", "RandomVariableInterface", "[", "]", "realizationAtTimeIndex", ",", "RandomVariableInterface", "[", "]", "realizationPredictor", ")", "{", "// Check if this LIBOR is already fixed", "if", "(", "getTime", "(", "timeIndex", ")", ">=", "this", ".", "getLiborPeriod", "(", "componentIndex", ")", ")", "{", "return", "null", ";", "}", "/*\n\t\t * We implemented several different methods to calculate the drift\n\t\t */", "if", "(", "driftApproximationMethod", "==", "Driftapproximation", ".", "PREDICTOR_CORRECTOR", "&&", "realizationPredictor", "!=", "null", ")", "{", "RandomVariableInterface", "drift", "=", "getDriftEuler", "(", "timeIndex", ",", "componentIndex", ",", "realizationAtTimeIndex", ")", ";", "RandomVariableInterface", "driftEulerWithPredictor", "=", "getDriftEuler", "(", "timeIndex", ",", "componentIndex", ",", "realizationPredictor", ")", ";", "drift", "=", "drift", ".", "add", "(", "driftEulerWithPredictor", ")", ".", "div", "(", "2.0", ")", ";", "return", "drift", ";", "}", "else", "if", "(", "driftApproximationMethod", "==", "Driftapproximation", ".", "LINE_INTEGRAL", "&&", "realizationPredictor", "!=", "null", ")", "{", "return", "getDriftLineIntegral", "(", "timeIndex", ",", "componentIndex", ",", "realizationAtTimeIndex", ",", "realizationPredictor", ")", ";", "}", "else", "{", "return", "getDriftEuler", "(", "timeIndex", ",", "componentIndex", ",", "realizationAtTimeIndex", ")", ";", "}", "}" ]
Alternative implementation for the drift. For experimental purposes. @param timeIndex @param componentIndex @param realizationAtTimeIndex @param realizationPredictor @return
[ "Alternative", "implementation", "for", "the", "drift", ".", "For", "experimental", "purposes", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/LIBORMarketModelStandard.java#L638-L661
159,849
finmath/finmath-lib
src/main/java6/net/finmath/randomnumbers/HaltonSequence.java
HaltonSequence.getHaltonNumberForGivenBase
public static double getHaltonNumberForGivenBase(long index, int base) { index += 1; double x = 0.0; double factor = 1.0 / base; while(index > 0) { x += (index % base) * factor; factor /= base; index /= base; } return x; }
java
public static double getHaltonNumberForGivenBase(long index, int base) { index += 1; double x = 0.0; double factor = 1.0 / base; while(index > 0) { x += (index % base) * factor; factor /= base; index /= base; } return x; }
[ "public", "static", "double", "getHaltonNumberForGivenBase", "(", "long", "index", ",", "int", "base", ")", "{", "index", "+=", "1", ";", "double", "x", "=", "0.0", ";", "double", "factor", "=", "1.0", "/", "base", ";", "while", "(", "index", ">", "0", ")", "{", "x", "+=", "(", "index", "%", "base", ")", "*", "factor", ";", "factor", "/=", "base", ";", "index", "/=", "base", ";", "}", "return", "x", ";", "}" ]
Return a Halton number, sequence starting at index = 0, base &gt; 1. @param index The index of the sequence. @param base The base of the sequence. Has to be greater than one (this is not checked). @return The Halton number.
[ "Return", "a", "Halton", "number", "sequence", "starting", "at", "index", "=", "0", "base", "&gt", ";", "1", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/randomnumbers/HaltonSequence.java#L66-L78
159,850
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableAAD.java
RandomVariableAAD.getGradient
public Map<Integer, RandomVariable> getGradient(){ int numberOfCalculationSteps = getFunctionList().size(); RandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps]; omegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0); for(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){ omegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0); ArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices(); for(int functionIndex:childrenList){ RandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex); omegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]); } } ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables(); Map<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>(); for(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){ gradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]); } return gradient; }
java
public Map<Integer, RandomVariable> getGradient(){ int numberOfCalculationSteps = getFunctionList().size(); RandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps]; omegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0); for(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){ omegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0); ArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices(); for(int functionIndex:childrenList){ RandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex); omegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]); } } ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables(); Map<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>(); for(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){ gradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]); } return gradient; }
[ "public", "Map", "<", "Integer", ",", "RandomVariable", ">", "getGradient", "(", ")", "{", "int", "numberOfCalculationSteps", "=", "getFunctionList", "(", ")", ".", "size", "(", ")", ";", "RandomVariable", "[", "]", "omegaHat", "=", "new", "RandomVariable", "[", "numberOfCalculationSteps", "]", ";", "omegaHat", "[", "numberOfCalculationSteps", "-", "1", "]", "=", "new", "RandomVariableFromDoubleArray", "(", "1.0", ")", ";", "for", "(", "int", "variableIndex", "=", "numberOfCalculationSteps", "-", "2", ";", "variableIndex", ">=", "0", ";", "variableIndex", "--", ")", "{", "omegaHat", "[", "variableIndex", "]", "=", "new", "RandomVariableFromDoubleArray", "(", "0.0", ")", ";", "ArrayList", "<", "Integer", ">", "childrenList", "=", "getAADRandomVariableFromList", "(", "variableIndex", ")", ".", "getChildrenIndices", "(", ")", ";", "for", "(", "int", "functionIndex", ":", "childrenList", ")", "{", "RandomVariable", "D_i_j", "=", "getPartialDerivative", "(", "functionIndex", ",", "variableIndex", ")", ";", "omegaHat", "[", "variableIndex", "]", "=", "omegaHat", "[", "variableIndex", "]", ".", "addProduct", "(", "D_i_j", ",", "omegaHat", "[", "functionIndex", "]", ")", ";", "}", "}", "ArrayList", "<", "Integer", ">", "arrayListOfAllIndicesOfDependentRandomVariables", "=", "getArrayListOfAllIndicesOfDependentRandomVariables", "(", ")", ";", "Map", "<", "Integer", ",", "RandomVariable", ">", "gradient", "=", "new", "HashMap", "<", "Integer", ",", "RandomVariable", ">", "(", ")", ";", "for", "(", "Integer", "indexOfDependentRandomVariable", ":", "arrayListOfAllIndicesOfDependentRandomVariables", ")", "{", "gradient", ".", "put", "(", "indexOfDependentRandomVariable", ",", "omegaHat", "[", "arrayListOfAllIndicesOfDependentRandomVariables", ".", "get", "(", "indexOfDependentRandomVariable", ")", "]", ")", ";", "}", "return", "gradient", ";", "}" ]
Implements the AAD Algorithm @return HashMap where the key is the internal index of the random variable with respect to which the partial derivative was computed. This key then gives access to the actual derivative.
[ "Implements", "the", "AAD", "Algorithm" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableAAD.java#L529-L558
159,851
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/curves/DiscountCurveInterpolation.java
DiscountCurveInterpolation.getZeroRates
public double[] getZeroRates(double[] maturities) { double[] values = new double[maturities.length]; for(int i=0; i<maturities.length; i++) { values[i] = getZeroRate(maturities[i]); } return values; }
java
public double[] getZeroRates(double[] maturities) { double[] values = new double[maturities.length]; for(int i=0; i<maturities.length; i++) { values[i] = getZeroRate(maturities[i]); } return values; }
[ "public", "double", "[", "]", "getZeroRates", "(", "double", "[", "]", "maturities", ")", "{", "double", "[", "]", "values", "=", "new", "double", "[", "maturities", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maturities", ".", "length", ";", "i", "++", ")", "{", "values", "[", "i", "]", "=", "getZeroRate", "(", "maturities", "[", "i", "]", ")", ";", "}", "return", "values", ";", "}" ]
Returns the zero rates for a given vector maturities. @param maturities The given maturities. @return The zero rates.
[ "Returns", "the", "zero", "rates", "for", "a", "given", "vector", "maturities", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/curves/DiscountCurveInterpolation.java#L427-L436
159,852
finmath/finmath-lib
src/main/java/net/finmath/functions/LinearAlgebra.java
LinearAlgebra.invert
public static double[][] invert(double[][] matrix) { if(isSolverUseApacheCommonsMath) { // Use LU from common math LUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = lu.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } }
java
public static double[][] invert(double[][] matrix) { if(isSolverUseApacheCommonsMath) { // Use LU from common math LUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = lu.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } }
[ "public", "static", "double", "[", "]", "[", "]", "invert", "(", "double", "[", "]", "[", "]", "matrix", ")", "{", "if", "(", "isSolverUseApacheCommonsMath", ")", "{", "// Use LU from common math", "LUDecomposition", "lu", "=", "new", "LUDecomposition", "(", "new", "Array2DRowRealMatrix", "(", "matrix", ")", ")", ";", "double", "[", "]", "[", "]", "matrixInverse", "=", "lu", ".", "getSolver", "(", ")", ".", "getInverse", "(", ")", ".", "getData", "(", ")", ";", "return", "matrixInverse", ";", "}", "else", "{", "return", "org", ".", "jblas", ".", "Solve", ".", "pinv", "(", "new", "org", ".", "jblas", ".", "DoubleMatrix", "(", "matrix", ")", ")", ".", "toArray2", "(", ")", ";", "}", "}" ]
Returns the inverse of a given matrix. @param matrix A matrix given as double[n][n]. @return The inverse of the given matrix.
[ "Returns", "the", "inverse", "of", "a", "given", "matrix", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/LinearAlgebra.java#L267-L279
159,853
finmath/finmath-lib
src/main/java/net/finmath/functions/LinearAlgebra.java
LinearAlgebra.factorReductionUsingCommonsMath
public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); }
java
public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); }
[ "public", "static", "double", "[", "]", "[", "]", "factorReductionUsingCommonsMath", "(", "double", "[", "]", "[", "]", "correlationMatrix", ",", "int", "numberOfFactors", ")", "{", "// Extract factors corresponding to the largest eigenvalues", "double", "[", "]", "[", "]", "factorMatrix", "=", "getFactorMatrix", "(", "correlationMatrix", ",", "numberOfFactors", ")", ";", "// Renormalize rows", "for", "(", "int", "row", "=", "0", ";", "row", "<", "correlationMatrix", ".", "length", ";", "row", "++", ")", "{", "double", "sumSquared", "=", "0", ";", "for", "(", "int", "factor", "=", "0", ";", "factor", "<", "numberOfFactors", ";", "factor", "++", ")", "{", "sumSquared", "+=", "factorMatrix", "[", "row", "]", "[", "factor", "]", "*", "factorMatrix", "[", "row", "]", "[", "factor", "]", ";", "}", "if", "(", "sumSquared", "!=", "0", ")", "{", "for", "(", "int", "factor", "=", "0", ";", "factor", "<", "numberOfFactors", ";", "factor", "++", ")", "{", "factorMatrix", "[", "row", "]", "[", "factor", "]", "=", "factorMatrix", "[", "row", "]", "[", "factor", "]", "/", "Math", ".", "sqrt", "(", "sumSquared", ")", ";", "}", "}", "else", "{", "// This is a rare case: The factor reduction of a completely decorrelated system to 1 factor", "for", "(", "int", "factor", "=", "0", ";", "factor", "<", "numberOfFactors", ";", "factor", "++", ")", "{", "factorMatrix", "[", "row", "]", "[", "factor", "]", "=", "1.0", ";", "}", "}", "}", "// Orthogonalized again", "double", "[", "]", "[", "]", "reducedCorrelationMatrix", "=", "(", "new", "Array2DRowRealMatrix", "(", "factorMatrix", ")", ".", "multiply", "(", "new", "Array2DRowRealMatrix", "(", "factorMatrix", ")", ".", "transpose", "(", ")", ")", ")", ".", "getData", "(", ")", ";", "return", "getFactorMatrix", "(", "reducedCorrelationMatrix", ",", "numberOfFactors", ")", ";", "}" ]
Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. @param correlationMatrix The given correlation matrix. @param numberOfFactors The requested number of factors (Eigenvectors). @return Factor reduced correlation matrix.
[ "Returns", "a", "correlation", "matrix", "which", "has", "rank", "&lt", ";", "n", "and", "for", "which", "the", "first", "n", "factors", "agree", "with", "the", "factors", "of", "correlationMatrix", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/LinearAlgebra.java#L438-L466
159,854
finmath/finmath-lib
src/main/java/net/finmath/functions/LinearAlgebra.java
LinearAlgebra.pseudoInverse
public static double[][] pseudoInverse(double[][] matrix){ if(isSolverUseApacheCommonsMath) { // Use LU from common math SingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = svd.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } }
java
public static double[][] pseudoInverse(double[][] matrix){ if(isSolverUseApacheCommonsMath) { // Use LU from common math SingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = svd.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } }
[ "public", "static", "double", "[", "]", "[", "]", "pseudoInverse", "(", "double", "[", "]", "[", "]", "matrix", ")", "{", "if", "(", "isSolverUseApacheCommonsMath", ")", "{", "// Use LU from common math", "SingularValueDecomposition", "svd", "=", "new", "SingularValueDecomposition", "(", "new", "Array2DRowRealMatrix", "(", "matrix", ")", ")", ";", "double", "[", "]", "[", "]", "matrixInverse", "=", "svd", ".", "getSolver", "(", ")", ".", "getInverse", "(", ")", ".", "getData", "(", ")", ";", "return", "matrixInverse", ";", "}", "else", "{", "return", "org", ".", "jblas", ".", "Solve", ".", "pinv", "(", "new", "org", ".", "jblas", ".", "DoubleMatrix", "(", "matrix", ")", ")", ".", "toArray2", "(", ")", ";", "}", "}" ]
Pseudo-Inverse of a matrix calculated in the least square sense. @param matrix The given matrix A. @return pseudoInverse The pseudo-inverse matrix P, such that A*P*A = A and P*A*P = P
[ "Pseudo", "-", "Inverse", "of", "a", "matrix", "calculated", "in", "the", "least", "square", "sense", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/LinearAlgebra.java#L524-L535
159,855
finmath/finmath-lib
src/main/java/net/finmath/functions/LinearAlgebra.java
LinearAlgebra.diag
public static double[][] diag(double[] vector){ // Note: According to the Java Language spec, an array is initialized with the default value, here 0. double[][] diagonalMatrix = new double[vector.length][vector.length]; for(int index = 0; index < vector.length; index++) { diagonalMatrix[index][index] = vector[index]; } return diagonalMatrix; }
java
public static double[][] diag(double[] vector){ // Note: According to the Java Language spec, an array is initialized with the default value, here 0. double[][] diagonalMatrix = new double[vector.length][vector.length]; for(int index = 0; index < vector.length; index++) { diagonalMatrix[index][index] = vector[index]; } return diagonalMatrix; }
[ "public", "static", "double", "[", "]", "[", "]", "diag", "(", "double", "[", "]", "vector", ")", "{", "// Note: According to the Java Language spec, an array is initialized with the default value, here 0.", "double", "[", "]", "[", "]", "diagonalMatrix", "=", "new", "double", "[", "vector", ".", "length", "]", "[", "vector", ".", "length", "]", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "vector", ".", "length", ";", "index", "++", ")", "{", "diagonalMatrix", "[", "index", "]", "[", "index", "]", "=", "vector", "[", "index", "]", ";", "}", "return", "diagonalMatrix", ";", "}" ]
Generates a diagonal matrix with the input vector on its diagonal @param vector The given matrix A. @return diagonalMatrix The matrix with the vectors entries on its diagonal
[ "Generates", "a", "diagonal", "matrix", "with", "the", "input", "vector", "on", "its", "diagonal" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/LinearAlgebra.java#L543-L553
159,856
finmath/finmath-lib
src/main/java/net/finmath/fouriermethod/calibration/CalibratedModel.java
CalibratedModel.formatTargetValuesForOptimizer
private double[] formatTargetValuesForOptimizer() { //Put all values in an array for the optimizer. int numberOfMaturities = surface.getMaturities().length; double mats[] = surface.getMaturities(); ArrayList<Double> vals = new ArrayList<Double>(); for(int t = 0; t<numberOfMaturities; t++) { double mat = mats[t]; double[] myStrikes = surface.getSurface().get(mat).getStrikes(); OptionSmileData smileOfInterest = surface.getSurface().get(mat); for(int k = 0; k < myStrikes.length; k++) { vals.add(smileOfInterest.getSmile().get(myStrikes[k]).getValue()); } } Double[] targetVals = new Double[vals.size()]; return ArrayUtils.toPrimitive(vals.toArray(targetVals)); }
java
private double[] formatTargetValuesForOptimizer() { //Put all values in an array for the optimizer. int numberOfMaturities = surface.getMaturities().length; double mats[] = surface.getMaturities(); ArrayList<Double> vals = new ArrayList<Double>(); for(int t = 0; t<numberOfMaturities; t++) { double mat = mats[t]; double[] myStrikes = surface.getSurface().get(mat).getStrikes(); OptionSmileData smileOfInterest = surface.getSurface().get(mat); for(int k = 0; k < myStrikes.length; k++) { vals.add(smileOfInterest.getSmile().get(myStrikes[k]).getValue()); } } Double[] targetVals = new Double[vals.size()]; return ArrayUtils.toPrimitive(vals.toArray(targetVals)); }
[ "private", "double", "[", "]", "formatTargetValuesForOptimizer", "(", ")", "{", "//Put all values in an array for the optimizer.", "int", "numberOfMaturities", "=", "surface", ".", "getMaturities", "(", ")", ".", "length", ";", "double", "mats", "[", "]", "=", "surface", ".", "getMaturities", "(", ")", ";", "ArrayList", "<", "Double", ">", "vals", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "for", "(", "int", "t", "=", "0", ";", "t", "<", "numberOfMaturities", ";", "t", "++", ")", "{", "double", "mat", "=", "mats", "[", "t", "]", ";", "double", "[", "]", "myStrikes", "=", "surface", ".", "getSurface", "(", ")", ".", "get", "(", "mat", ")", ".", "getStrikes", "(", ")", ";", "OptionSmileData", "smileOfInterest", "=", "surface", ".", "getSurface", "(", ")", ".", "get", "(", "mat", ")", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "myStrikes", ".", "length", ";", "k", "++", ")", "{", "vals", ".", "add", "(", "smileOfInterest", ".", "getSmile", "(", ")", ".", "get", "(", "myStrikes", "[", "k", "]", ")", ".", "getValue", "(", ")", ")", ";", "}", "}", "Double", "[", "]", "targetVals", "=", "new", "Double", "[", "vals", ".", "size", "(", ")", "]", ";", "return", "ArrayUtils", ".", "toPrimitive", "(", "vals", ".", "toArray", "(", "targetVals", ")", ")", ";", "}" ]
This is a service method that takes care of putting al the target values in a single array. @return
[ "This", "is", "a", "service", "method", "that", "takes", "care", "of", "putting", "al", "the", "target", "values", "in", "a", "single", "array", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/fouriermethod/calibration/CalibratedModel.java#L157-L177
159,857
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java
ForwardCurveInterpolation.createForwardCurveFromDiscountFactors
public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors(String name, double[] times, RandomVariable[] givenDiscountFactors, double paymentOffset) { ForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, paymentOffset, InterpolationEntityForward.FORWARD, null); if(times.length == 0) { throw new IllegalArgumentException("Vector of times must not be empty."); } if(times[0] > 0) { // Add first forward RandomVariable forward = givenDiscountFactors[0].sub(1.0).pow(-1.0).div(times[0]); forwardCurveInterpolation.addForward(null, 0.0, forward, true); } for(int timeIndex=0; timeIndex<times.length-1;timeIndex++) { RandomVariable forward = givenDiscountFactors[timeIndex].div(givenDiscountFactors[timeIndex+1].sub(1.0)).div(times[timeIndex+1] - times[timeIndex]); double fixingTime = times[timeIndex]; boolean isParameter = (fixingTime > 0); forwardCurveInterpolation.addForward(null, fixingTime, forward, isParameter); } return forwardCurveInterpolation; }
java
public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors(String name, double[] times, RandomVariable[] givenDiscountFactors, double paymentOffset) { ForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, paymentOffset, InterpolationEntityForward.FORWARD, null); if(times.length == 0) { throw new IllegalArgumentException("Vector of times must not be empty."); } if(times[0] > 0) { // Add first forward RandomVariable forward = givenDiscountFactors[0].sub(1.0).pow(-1.0).div(times[0]); forwardCurveInterpolation.addForward(null, 0.0, forward, true); } for(int timeIndex=0; timeIndex<times.length-1;timeIndex++) { RandomVariable forward = givenDiscountFactors[timeIndex].div(givenDiscountFactors[timeIndex+1].sub(1.0)).div(times[timeIndex+1] - times[timeIndex]); double fixingTime = times[timeIndex]; boolean isParameter = (fixingTime > 0); forwardCurveInterpolation.addForward(null, fixingTime, forward, isParameter); } return forwardCurveInterpolation; }
[ "public", "static", "ForwardCurveInterpolation", "createForwardCurveFromDiscountFactors", "(", "String", "name", ",", "double", "[", "]", "times", ",", "RandomVariable", "[", "]", "givenDiscountFactors", ",", "double", "paymentOffset", ")", "{", "ForwardCurveInterpolation", "forwardCurveInterpolation", "=", "new", "ForwardCurveInterpolation", "(", "name", ",", "paymentOffset", ",", "InterpolationEntityForward", ".", "FORWARD", ",", "null", ")", ";", "if", "(", "times", ".", "length", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Vector of times must not be empty.\"", ")", ";", "}", "if", "(", "times", "[", "0", "]", ">", "0", ")", "{", "// Add first forward", "RandomVariable", "forward", "=", "givenDiscountFactors", "[", "0", "]", ".", "sub", "(", "1.0", ")", ".", "pow", "(", "-", "1.0", ")", ".", "div", "(", "times", "[", "0", "]", ")", ";", "forwardCurveInterpolation", ".", "addForward", "(", "null", ",", "0.0", ",", "forward", ",", "true", ")", ";", "}", "for", "(", "int", "timeIndex", "=", "0", ";", "timeIndex", "<", "times", ".", "length", "-", "1", ";", "timeIndex", "++", ")", "{", "RandomVariable", "forward", "=", "givenDiscountFactors", "[", "timeIndex", "]", ".", "div", "(", "givenDiscountFactors", "[", "timeIndex", "+", "1", "]", ".", "sub", "(", "1.0", ")", ")", ".", "div", "(", "times", "[", "timeIndex", "+", "1", "]", "-", "times", "[", "timeIndex", "]", ")", ";", "double", "fixingTime", "=", "times", "[", "timeIndex", "]", ";", "boolean", "isParameter", "=", "(", "fixingTime", ">", "0", ")", ";", "forwardCurveInterpolation", ".", "addForward", "(", "null", ",", "fixingTime", ",", "forward", ",", "isParameter", ")", ";", "}", "return", "forwardCurveInterpolation", ";", "}" ]
Create a forward curve from given times and discount factors. The forward curve will have times.length-1 fixing times from times[0] to times[times.length-2] <code> forward[timeIndex] = (givenDiscountFactors[timeIndex]/givenDiscountFactors[timeIndex+1]-1.0) / (times[timeIndex+1] - times[timeIndex]); </code> Note: If time[0] &gt; 0, then the discount factor 1.0 will inserted at time 0.0 @param name The name of this curve. @param times A vector of given time points. @param givenDiscountFactors A vector of given discount factors (corresponding to the given time points). @param paymentOffset The maturity of the underlying index modeled by this curve. @return A new ForwardCurve object.
[ "Create", "a", "forward", "curve", "from", "given", "times", "and", "discount", "factors", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java#L261-L282
159,858
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java
ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel
public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{ int timeIndex = model.getTimeIndex(startTime); // Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves ArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>(); int firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime); double firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex); if(firstLiborTime>startTime) { liborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime)); } // Vector of times for the forward curve double[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)]; times[0]=0; int indexOffset = firstLiborTime==startTime ? 0 : 1; for(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) { liborsAtTimeIndex.add(model.getLIBOR(timeIndex,i)); times[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime; } RandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]); return ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex)); }
java
public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{ int timeIndex = model.getTimeIndex(startTime); // Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves ArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>(); int firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime); double firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex); if(firstLiborTime>startTime) { liborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime)); } // Vector of times for the forward curve double[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)]; times[0]=0; int indexOffset = firstLiborTime==startTime ? 0 : 1; for(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) { liborsAtTimeIndex.add(model.getLIBOR(timeIndex,i)); times[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime; } RandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]); return ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex)); }
[ "public", "static", "ForwardCurveInterpolation", "createForwardCurveFromMonteCarloLiborModel", "(", "String", "name", ",", "LIBORModelMonteCarloSimulationModel", "model", ",", "double", "startTime", ")", "throws", "CalculationException", "{", "int", "timeIndex", "=", "model", ".", "getTimeIndex", "(", "startTime", ")", ";", "// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves", "ArrayList", "<", "RandomVariable", ">", "liborsAtTimeIndex", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "firstLiborIndex", "=", "model", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getTimeIndexNearestGreaterOrEqual", "(", "startTime", ")", ";", "double", "firstLiborTime", "=", "model", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getTime", "(", "firstLiborIndex", ")", ";", "if", "(", "firstLiborTime", ">", "startTime", ")", "{", "liborsAtTimeIndex", ".", "add", "(", "model", ".", "getLIBOR", "(", "startTime", ",", "startTime", ",", "firstLiborTime", ")", ")", ";", "}", "// Vector of times for the forward curve", "double", "[", "]", "times", "=", "new", "double", "[", "firstLiborTime", "==", "startTime", "?", "(", "model", ".", "getNumberOfLibors", "(", ")", "-", "firstLiborIndex", ")", ":", "(", "model", ".", "getNumberOfLibors", "(", ")", "-", "firstLiborIndex", "+", "1", ")", "]", ";", "times", "[", "0", "]", "=", "0", ";", "int", "indexOffset", "=", "firstLiborTime", "==", "startTime", "?", "0", ":", "1", ";", "for", "(", "int", "i", "=", "firstLiborIndex", ";", "i", "<", "model", ".", "getNumberOfLibors", "(", ")", ";", "i", "++", ")", "{", "liborsAtTimeIndex", ".", "add", "(", "model", ".", "getLIBOR", "(", "timeIndex", ",", "i", ")", ")", ";", "times", "[", "i", "-", "firstLiborIndex", "+", "indexOffset", "]", "=", "model", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getTime", "(", "i", ")", "-", "startTime", ";", "}", "RandomVariable", "[", "]", "libors", "=", "liborsAtTimeIndex", ".", "toArray", "(", "new", "RandomVariable", "[", "liborsAtTimeIndex", ".", "size", "(", ")", "]", ")", ";", "return", "ForwardCurveInterpolation", ".", "createForwardCurveFromForwards", "(", "name", ",", "times", ",", "libors", ",", "model", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getTimeStep", "(", "firstLiborIndex", ")", ")", ";", "}" ]
Create a forward curve from forwards given by a LIBORMonteCarloModel. @param name name of the forward curve. @param model Monte Carlo model providing the forwards. @param startTime time at which the curve starts, i.e. zero time for the curve @return a forward curve from forwards given by a LIBORMonteCarloModel. @throws CalculationException Thrown if the model failed to provide the forward rates.
[ "Create", "a", "forward", "curve", "from", "forwards", "given", "by", "a", "LIBORMonteCarloModel", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java#L334-L356
159,859
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java
ForwardCurveInterpolation.addForward
private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) { double interpolationEntitiyTime; RandomVariable interpolationEntityForwardValue; switch(interpolationEntityForward) { case FORWARD: default: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward; break; case FORWARD_TIMES_DISCOUNTFACTOR: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime))); break; case ZERO: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset); break; } case DISCOUNTFACTOR: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0)); break; } } super.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter); }
java
private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) { double interpolationEntitiyTime; RandomVariable interpolationEntityForwardValue; switch(interpolationEntityForward) { case FORWARD: default: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward; break; case FORWARD_TIMES_DISCOUNTFACTOR: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime))); break; case ZERO: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset); break; } case DISCOUNTFACTOR: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0)); break; } } super.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter); }
[ "private", "void", "addForward", "(", "AnalyticModel", "model", ",", "double", "fixingTime", ",", "RandomVariable", "forward", ",", "boolean", "isParameter", ")", "{", "double", "interpolationEntitiyTime", ";", "RandomVariable", "interpolationEntityForwardValue", ";", "switch", "(", "interpolationEntityForward", ")", "{", "case", "FORWARD", ":", "default", ":", "interpolationEntitiyTime", "=", "fixingTime", ";", "interpolationEntityForwardValue", "=", "forward", ";", "break", ";", "case", "FORWARD_TIMES_DISCOUNTFACTOR", ":", "interpolationEntitiyTime", "=", "fixingTime", ";", "interpolationEntityForwardValue", "=", "forward", ".", "mult", "(", "model", ".", "getDiscountCurve", "(", "getDiscountCurveName", "(", ")", ")", ".", "getValue", "(", "model", ",", "fixingTime", "+", "getPaymentOffset", "(", "fixingTime", ")", ")", ")", ";", "break", ";", "case", "ZERO", ":", "{", "double", "paymentOffset", "=", "getPaymentOffset", "(", "fixingTime", ")", ";", "interpolationEntitiyTime", "=", "fixingTime", "+", "paymentOffset", ";", "interpolationEntityForwardValue", "=", "forward", ".", "mult", "(", "paymentOffset", ")", ".", "add", "(", "1.0", ")", ".", "log", "(", ")", ".", "div", "(", "paymentOffset", ")", ";", "break", ";", "}", "case", "DISCOUNTFACTOR", ":", "{", "double", "paymentOffset", "=", "getPaymentOffset", "(", "fixingTime", ")", ";", "interpolationEntitiyTime", "=", "fixingTime", "+", "paymentOffset", ";", "interpolationEntityForwardValue", "=", "getValue", "(", "fixingTime", ")", ".", "div", "(", "forward", ".", "mult", "(", "paymentOffset", ")", ".", "add", "(", "1.0", ")", ")", ";", "break", ";", "}", "}", "super", ".", "addPoint", "(", "interpolationEntitiyTime", ",", "interpolationEntityForwardValue", ",", "isParameter", ")", ";", "}" ]
Add a forward to this curve. @param model An analytic model providing a context. The discount curve (if needed) is obtained from this model. @param fixingTime The given fixing time. @param forward The given forward. @param isParameter If true, then this point is server via {@link #getParameter()} and changed via {@link #setParameter(RandomVariable[])} and {@link #getCloneForParameter(RandomVariable[])}, i.e., it can be calibrated.
[ "Add", "a", "forward", "to", "this", "curve", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java#L416-L445
159,860
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/process/LinearInterpolatedTimeDiscreteProcess.java
LinearInterpolatedTimeDiscreteProcess.add
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException { Map<Double, RandomVariable> sum = new HashMap<>(); for(double time: timeDiscretization) { sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0))); } return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum); }
java
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException { Map<Double, RandomVariable> sum = new HashMap<>(); for(double time: timeDiscretization) { sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0))); } return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum); }
[ "public", "LinearInterpolatedTimeDiscreteProcess", "add", "(", "LinearInterpolatedTimeDiscreteProcess", "process", ")", "throws", "CalculationException", "{", "Map", "<", "Double", ",", "RandomVariable", ">", "sum", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "double", "time", ":", "timeDiscretization", ")", "{", "sum", ".", "put", "(", "time", ",", "realizations", ".", "get", "(", "time", ")", ".", "add", "(", "process", ".", "getProcessValue", "(", "time", ",", "0", ")", ")", ")", ";", "}", "return", "new", "LinearInterpolatedTimeDiscreteProcess", "(", "timeDiscretization", ",", "sum", ")", ";", "}" ]
Create a new linear interpolated time discrete process by using the time discretization of this process and the sum of this process and the given one as its values. @param process A given process. @return A new process representing the of this and the given process. @throws CalculationException Thrown if the given process fails to evaluate at a certain time point.
[ "Create", "a", "new", "linear", "interpolated", "time", "discrete", "process", "by", "using", "the", "time", "discretization", "of", "this", "process", "and", "the", "sum", "of", "this", "process", "and", "the", "given", "one", "as", "its", "values", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/process/LinearInterpolatedTimeDiscreteProcess.java#L70-L78
159,861
finmath/finmath-lib
src/main/java/net/finmath/optimizer/StochasticPathwiseLevenbergMarquardt.java
StochasticPathwiseLevenbergMarquardt.getCloneWithModifiedTargetValues
public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException { StochasticPathwiseLevenbergMarquardt clonedOptimizer = clone(); clonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues); clonedOptimizer.weights = numberListToDoubleArray(newWeights); if(isUseBestParametersAsInitialParameters && this.done()) { clonedOptimizer.initialParameters = this.getBestFitParameters(); } return clonedOptimizer; }
java
public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException { StochasticPathwiseLevenbergMarquardt clonedOptimizer = clone(); clonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues); clonedOptimizer.weights = numberListToDoubleArray(newWeights); if(isUseBestParametersAsInitialParameters && this.done()) { clonedOptimizer.initialParameters = this.getBestFitParameters(); } return clonedOptimizer; }
[ "public", "StochasticPathwiseLevenbergMarquardt", "getCloneWithModifiedTargetValues", "(", "List", "<", "RandomVariable", ">", "newTargetVaues", ",", "List", "<", "RandomVariable", ">", "newWeights", ",", "boolean", "isUseBestParametersAsInitialParameters", ")", "throws", "CloneNotSupportedException", "{", "StochasticPathwiseLevenbergMarquardt", "clonedOptimizer", "=", "clone", "(", ")", ";", "clonedOptimizer", ".", "targetValues", "=", "numberListToDoubleArray", "(", "newTargetVaues", ")", ";", "clonedOptimizer", ".", "weights", "=", "numberListToDoubleArray", "(", "newWeights", ")", ";", "if", "(", "isUseBestParametersAsInitialParameters", "&&", "this", ".", "done", "(", ")", ")", "{", "clonedOptimizer", ".", "initialParameters", "=", "this", ".", "getBestFitParameters", "(", ")", ";", "}", "return", "clonedOptimizer", ";", "}" ]
Create a clone of this LevenbergMarquardt optimizer with a new vector for the target values and weights. The clone will use the same objective function than this implementation, i.e., the implementation of {@link #setValues(RandomVariable[], RandomVariable[])} and that of {@link #setDerivatives(RandomVariable[], RandomVariable[][])} is reused. The initial values of the cloned optimizer will either be the original initial values of this object or the best parameters obtained by this optimizer, the latter is used only if this optimized signals a {@link #done()}. @param newTargetVaues New list of target values. @param newWeights New list of weights. @param isUseBestParametersAsInitialParameters If true and this optimizer is done(), then the clone will use this.{@link #getBestFitParameters()} as initial parameters. @return A new LevenbergMarquardt optimizer, cloning this one except modified target values and weights. @throws CloneNotSupportedException Thrown if this optimizer cannot be cloned.
[ "Create", "a", "clone", "of", "this", "LevenbergMarquardt", "optimizer", "with", "a", "new", "vector", "for", "the", "target", "values", "and", "weights", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/optimizer/StochasticPathwiseLevenbergMarquardt.java#L718-L728
159,862
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/interestrate/products/components/Option.java
Option.getBasisFunctions
public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException { ArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>(); RandomVariableInterface basisFunction; // Constant basisFunction = model.getRandomVariableForConstant(1.0); basisFunctions.add(basisFunction); // LIBORs int liborPeriodIndex, liborPeriodIndexEnd; RandomVariableInterface rate; // 1 Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = liborPeriodIndex+1; double periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength1); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength1); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); // n/2 Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2; double periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); if(periodLength2 != periodLength1) { rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength2); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength2); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength2); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); } // n Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = model.getNumberOfLibors(); double periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); if(periodLength3 != periodLength1 && periodLength3 != periodLength2) { rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength3); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength3); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); } return basisFunctions.toArray(new RandomVariableInterface[0]); }
java
public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException { ArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>(); RandomVariableInterface basisFunction; // Constant basisFunction = model.getRandomVariableForConstant(1.0); basisFunctions.add(basisFunction); // LIBORs int liborPeriodIndex, liborPeriodIndexEnd; RandomVariableInterface rate; // 1 Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = liborPeriodIndex+1; double periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength1); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength1); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); // n/2 Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2; double periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); if(periodLength2 != periodLength1) { rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength2); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength2); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength2); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); } // n Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = model.getNumberOfLibors(); double periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); if(periodLength3 != periodLength1 && periodLength3 != periodLength2) { rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength3); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength3); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); } return basisFunctions.toArray(new RandomVariableInterface[0]); }
[ "public", "RandomVariableInterface", "[", "]", "getBasisFunctions", "(", "double", "exerciseDate", ",", "LIBORModelMonteCarloSimulationInterface", "model", ")", "throws", "CalculationException", "{", "ArrayList", "<", "RandomVariableInterface", ">", "basisFunctions", "=", "new", "ArrayList", "<", "RandomVariableInterface", ">", "(", ")", ";", "RandomVariableInterface", "basisFunction", ";", "// Constant", "basisFunction", "=", "model", ".", "getRandomVariableForConstant", "(", "1.0", ")", ";", "basisFunctions", ".", "add", "(", "basisFunction", ")", ";", "// LIBORs", "int", "liborPeriodIndex", ",", "liborPeriodIndexEnd", ";", "RandomVariableInterface", "rate", ";", "// 1 Period", "basisFunction", "=", "model", ".", "getRandomVariableForConstant", "(", "1.0", ")", ";", "liborPeriodIndex", "=", "model", ".", "getLiborPeriodIndex", "(", "exerciseDate", ")", ";", "if", "(", "liborPeriodIndex", "<", "0", ")", "{", "liborPeriodIndex", "=", "-", "liborPeriodIndex", "-", "1", ";", "}", "liborPeriodIndexEnd", "=", "liborPeriodIndex", "+", "1", ";", "double", "periodLength1", "=", "model", ".", "getLiborPeriod", "(", "liborPeriodIndexEnd", ")", "-", "model", ".", "getLiborPeriod", "(", "liborPeriodIndex", ")", ";", "rate", "=", "model", ".", "getLIBOR", "(", "exerciseDate", ",", "model", ".", "getLiborPeriod", "(", "liborPeriodIndex", ")", ",", "model", ".", "getLiborPeriod", "(", "liborPeriodIndexEnd", ")", ")", ";", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength1", ")", ";", "basisFunctions", ".", "add", "(", "basisFunction", ")", ";", "//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength1", ")", ";", "basisFunctions", ".", "add", "(", "basisFunction", ")", ";", "//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "// n/2 Period", "basisFunction", "=", "model", ".", "getRandomVariableForConstant", "(", "1.0", ")", ";", "liborPeriodIndex", "=", "model", ".", "getLiborPeriodIndex", "(", "exerciseDate", ")", ";", "if", "(", "liborPeriodIndex", "<", "0", ")", "{", "liborPeriodIndex", "=", "-", "liborPeriodIndex", "-", "1", ";", "}", "liborPeriodIndexEnd", "=", "(", "liborPeriodIndex", "+", "model", ".", "getNumberOfLibors", "(", ")", ")", "/", "2", ";", "double", "periodLength2", "=", "model", ".", "getLiborPeriod", "(", "liborPeriodIndexEnd", ")", "-", "model", ".", "getLiborPeriod", "(", "liborPeriodIndex", ")", ";", "if", "(", "periodLength2", "!=", "periodLength1", ")", "{", "rate", "=", "model", ".", "getLIBOR", "(", "exerciseDate", ",", "model", ".", "getLiborPeriod", "(", "liborPeriodIndex", ")", ",", "model", ".", "getLiborPeriod", "(", "liborPeriodIndexEnd", ")", ")", ";", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength2", ")", ";", "basisFunctions", ".", "add", "(", "basisFunction", ")", ";", "//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength2", ")", ";", "//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength2", ")", ";", "//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "}", "// n Period", "basisFunction", "=", "model", ".", "getRandomVariableForConstant", "(", "1.0", ")", ";", "liborPeriodIndex", "=", "model", ".", "getLiborPeriodIndex", "(", "exerciseDate", ")", ";", "if", "(", "liborPeriodIndex", "<", "0", ")", "{", "liborPeriodIndex", "=", "-", "liborPeriodIndex", "-", "1", ";", "}", "liborPeriodIndexEnd", "=", "model", ".", "getNumberOfLibors", "(", ")", ";", "double", "periodLength3", "=", "model", ".", "getLiborPeriod", "(", "liborPeriodIndexEnd", ")", "-", "model", ".", "getLiborPeriod", "(", "liborPeriodIndex", ")", ";", "if", "(", "periodLength3", "!=", "periodLength1", "&&", "periodLength3", "!=", "periodLength2", ")", "{", "rate", "=", "model", ".", "getLIBOR", "(", "exerciseDate", ",", "model", ".", "getLiborPeriod", "(", "liborPeriodIndex", ")", ",", "model", ".", "getLiborPeriod", "(", "liborPeriodIndexEnd", ")", ")", ";", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength3", ")", ";", "basisFunctions", ".", "add", "(", "basisFunction", ")", ";", "//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "basisFunction", "=", "basisFunction", ".", "discount", "(", "rate", ",", "periodLength3", ")", ";", "//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));", "}", "return", "basisFunctions", ".", "toArray", "(", "new", "RandomVariableInterface", "[", "0", "]", ")", ";", "}" ]
Return the regression basis functions. @param exerciseDate The date w.r.t. which the basis functions should be measurable. @param model The model. @return Array of random variables. @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "Return", "the", "regression", "basis", "functions", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/products/components/Option.java#L267-L339
159,863
finmath/finmath-lib
src/main/java/net/finmath/marketdata/calibration/CalibratedCurves.java
CalibratedCurves.createDiscountCurve
private DiscountCurve createDiscountCurve(String discountCurveName) { DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName); if(discountCurve == null) { discountCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(discountCurveName, new double[] { 0.0 }, new double[] { 1.0 }); model = model.addCurves(discountCurve); } return discountCurve; }
java
private DiscountCurve createDiscountCurve(String discountCurveName) { DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName); if(discountCurve == null) { discountCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(discountCurveName, new double[] { 0.0 }, new double[] { 1.0 }); model = model.addCurves(discountCurve); } return discountCurve; }
[ "private", "DiscountCurve", "createDiscountCurve", "(", "String", "discountCurveName", ")", "{", "DiscountCurve", "discountCurve", "=", "model", ".", "getDiscountCurve", "(", "discountCurveName", ")", ";", "if", "(", "discountCurve", "==", "null", ")", "{", "discountCurve", "=", "DiscountCurveInterpolation", ".", "createDiscountCurveFromDiscountFactors", "(", "discountCurveName", ",", "new", "double", "[", "]", "{", "0.0", "}", ",", "new", "double", "[", "]", "{", "1.0", "}", ")", ";", "model", "=", "model", ".", "addCurves", "(", "discountCurve", ")", ";", "}", "return", "discountCurve", ";", "}" ]
Get a discount curve from the model, if not existing create a discount curve. @param discountCurveName The name of the discount curve to create. @return The discount factor curve associated with the given name.
[ "Get", "a", "discount", "curve", "from", "the", "model", "if", "not", "existing", "create", "a", "discount", "curve", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/calibration/CalibratedCurves.java#L760-L768
159,864
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/curves/locallinearregression/Partition.java
Partition.d
public double d(double x){ int intervalNumber =getIntervalNumber(x); if (intervalNumber==0 || intervalNumber==points.length) { return x; } return getIntervalReferencePoint(intervalNumber-1); }
java
public double d(double x){ int intervalNumber =getIntervalNumber(x); if (intervalNumber==0 || intervalNumber==points.length) { return x; } return getIntervalReferencePoint(intervalNumber-1); }
[ "public", "double", "d", "(", "double", "x", ")", "{", "int", "intervalNumber", "=", "getIntervalNumber", "(", "x", ")", ";", "if", "(", "intervalNumber", "==", "0", "||", "intervalNumber", "==", "points", ".", "length", ")", "{", "return", "x", ";", "}", "return", "getIntervalReferencePoint", "(", "intervalNumber", "-", "1", ")", ";", "}" ]
If a given x is into an interval of the partition, this method returns the reference point of the corresponding interval. If the given x is not contained in any interval of the partition, this method returns x. @param x The point of interest. @return The discretized value.
[ "If", "a", "given", "x", "is", "into", "an", "interval", "of", "the", "partition", "this", "method", "returns", "the", "reference", "point", "of", "the", "corresponding", "interval", ".", "If", "the", "given", "x", "is", "not", "contained", "in", "any", "interval", "of", "the", "partition", "this", "method", "returns", "x", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/curves/locallinearregression/Partition.java#L84-L90
159,865
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/interestrate/products/Swaption.java
Swaption.getValue
public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) { double swaprate = swaprates[0]; for (double swaprate1 : swaprates) { if (swaprate1 != swaprate) { throw new RuntimeException("Uneven swaprates not allows for analytical pricing."); } } double[] swapTenor = new double[fixingDates.length+1]; System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length); swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1]; double forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve); double swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve); return AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity); }
java
public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) { double swaprate = swaprates[0]; for (double swaprate1 : swaprates) { if (swaprate1 != swaprate) { throw new RuntimeException("Uneven swaprates not allows for analytical pricing."); } } double[] swapTenor = new double[fixingDates.length+1]; System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length); swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1]; double forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve); double swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve); return AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity); }
[ "public", "double", "getValue", "(", "ForwardCurveInterface", "forwardCurve", ",", "double", "swaprateVolatility", ")", "{", "double", "swaprate", "=", "swaprates", "[", "0", "]", ";", "for", "(", "double", "swaprate1", ":", "swaprates", ")", "{", "if", "(", "swaprate1", "!=", "swaprate", ")", "{", "throw", "new", "RuntimeException", "(", "\"Uneven swaprates not allows for analytical pricing.\"", ")", ";", "}", "}", "double", "[", "]", "swapTenor", "=", "new", "double", "[", "fixingDates", ".", "length", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "fixingDates", ",", "0", ",", "swapTenor", ",", "0", ",", "fixingDates", ".", "length", ")", ";", "swapTenor", "[", "swapTenor", ".", "length", "-", "1", "]", "=", "paymentDates", "[", "paymentDates", ".", "length", "-", "1", "]", ";", "double", "forwardSwapRate", "=", "Swap", ".", "getForwardSwapRate", "(", "new", "TimeDiscretization", "(", "swapTenor", ")", ",", "new", "TimeDiscretization", "(", "swapTenor", ")", ",", "forwardCurve", ")", ";", "double", "swapAnnuity", "=", "SwapAnnuity", ".", "getSwapAnnuity", "(", "new", "TimeDiscretization", "(", "swapTenor", ")", ",", "forwardCurve", ")", ";", "return", "AnalyticFormulas", ".", "blackModelSwaptionValue", "(", "forwardSwapRate", ",", "swaprateVolatility", ",", "exerciseDate", ",", "swaprate", ",", "swapAnnuity", ")", ";", "}" ]
This method returns the value of the product using a Black-Scholes model for the swap rate The model is determined by a discount factor curve and a swap rate volatility. @param forwardCurve The forward curve on which to value the swap. @param swaprateVolatility The Black volatility. @return Value of this product
[ "This", "method", "returns", "the", "value", "of", "the", "product", "using", "a", "Black", "-", "Scholes", "model", "for", "the", "swap", "rate", "The", "model", "is", "determined", "by", "a", "discount", "factor", "curve", "and", "a", "swap", "rate", "volatility", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/products/Swaption.java#L189-L205
159,866
finmath/finmath-lib
src/main/java/net/finmath/marketdata/products/ForwardRateAgreement.java
ForwardRateAgreement.getRate
public double getRate(AnalyticModel model) { if(model==null) { throw new IllegalArgumentException("model==null"); } ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); if(forwardCurve==null) { throw new IllegalArgumentException("No forward curve of name '" + forwardCurveName + "' found in given model:\n" + model.toString()); } double fixingDate = schedule.getFixing(0); return forwardCurve.getForward(model,fixingDate); }
java
public double getRate(AnalyticModel model) { if(model==null) { throw new IllegalArgumentException("model==null"); } ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); if(forwardCurve==null) { throw new IllegalArgumentException("No forward curve of name '" + forwardCurveName + "' found in given model:\n" + model.toString()); } double fixingDate = schedule.getFixing(0); return forwardCurve.getForward(model,fixingDate); }
[ "public", "double", "getRate", "(", "AnalyticModel", "model", ")", "{", "if", "(", "model", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"model==null\"", ")", ";", "}", "ForwardCurve", "forwardCurve", "=", "model", ".", "getForwardCurve", "(", "forwardCurveName", ")", ";", "if", "(", "forwardCurve", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No forward curve of name '\"", "+", "forwardCurveName", "+", "\"' found in given model:\\n\"", "+", "model", ".", "toString", "(", ")", ")", ";", "}", "double", "fixingDate", "=", "schedule", ".", "getFixing", "(", "0", ")", ";", "return", "forwardCurve", ".", "getForward", "(", "model", ",", "fixingDate", ")", ";", "}" ]
Return the par FRA rate for a given curve. @param model A given model. @return The par FRA rate.
[ "Return", "the", "par", "FRA", "rate", "for", "a", "given", "curve", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/products/ForwardRateAgreement.java#L103-L115
159,867
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/models/covariance/AbstractLIBORCovarianceModelParametric.java
AbstractLIBORCovarianceModelParametric.getParameter
public RandomVariable[] getParameter() { double[] parameterAsDouble = this.getParameterAsDouble(); RandomVariable[] parameter = new RandomVariable[parameterAsDouble.length]; for(int i=0; i<parameter.length; i++) { parameter[i] = new Scalar(parameterAsDouble[i]); } return parameter; }
java
public RandomVariable[] getParameter() { double[] parameterAsDouble = this.getParameterAsDouble(); RandomVariable[] parameter = new RandomVariable[parameterAsDouble.length]; for(int i=0; i<parameter.length; i++) { parameter[i] = new Scalar(parameterAsDouble[i]); } return parameter; }
[ "public", "RandomVariable", "[", "]", "getParameter", "(", ")", "{", "double", "[", "]", "parameterAsDouble", "=", "this", ".", "getParameterAsDouble", "(", ")", ";", "RandomVariable", "[", "]", "parameter", "=", "new", "RandomVariable", "[", "parameterAsDouble", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parameter", ".", "length", ";", "i", "++", ")", "{", "parameter", "[", "i", "]", "=", "new", "Scalar", "(", "parameterAsDouble", "[", "i", "]", ")", ";", "}", "return", "parameter", ";", "}" ]
Get the parameters of determining this parametric covariance model. The parameters are usually free parameters which may be used in calibration. @return Parameter vector.
[ "Get", "the", "parameters", "of", "determining", "this", "parametric", "covariance", "model", ".", "The", "parameters", "are", "usually", "free", "parameters", "which", "may", "be", "used", "in", "calibration", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/covariance/AbstractLIBORCovarianceModelParametric.java#L89-L96
159,868
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java
DiscountCurveInterpolation.createDiscountCurveFromMonteCarloLiborModel
public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{ // Check if the LMM uses a discount curve which is created from a forward curve if(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains("DiscountCurveFromForwardCurve".toLowerCase())){ return new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime)); } else { // i.e. forward curve of Libor Model not OIS. In this case return the OIS curve. // Only at startTime 0! return (DiscountCurveInterface) model.getModel().getDiscountCurve(); } }
java
public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{ // Check if the LMM uses a discount curve which is created from a forward curve if(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains("DiscountCurveFromForwardCurve".toLowerCase())){ return new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime)); } else { // i.e. forward curve of Libor Model not OIS. In this case return the OIS curve. // Only at startTime 0! return (DiscountCurveInterface) model.getModel().getDiscountCurve(); } }
[ "public", "static", "DiscountCurveInterface", "createDiscountCurveFromMonteCarloLiborModel", "(", "String", "forwardCurveName", ",", "LIBORModelMonteCarloSimulationModel", "model", ",", "double", "startTime", ")", "throws", "CalculationException", "{", "// Check if the LMM uses a discount curve which is created from a forward curve", "if", "(", "model", ".", "getModel", "(", ")", ".", "getDiscountCurve", "(", ")", "==", "null", "||", "model", ".", "getModel", "(", ")", ".", "getDiscountCurve", "(", ")", ".", "getName", "(", ")", ".", "toLowerCase", "(", ")", ".", "contains", "(", "\"DiscountCurveFromForwardCurve\"", ".", "toLowerCase", "(", ")", ")", ")", "{", "return", "new", "DiscountCurveFromForwardCurve", "(", "ForwardCurveInterpolation", ".", "createForwardCurveFromMonteCarloLiborModel", "(", "forwardCurveName", ",", "model", ",", "startTime", ")", ")", ";", "}", "else", "{", "// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.", "// Only at startTime 0!", "return", "(", "DiscountCurveInterface", ")", "model", ".", "getModel", "(", ")", ".", "getDiscountCurve", "(", ")", ";", "}", "}" ]
Create a discount curve from forwards given by a LIBORMonteCarloModel. If the model uses multiple curves, return its discount curve. @param forwardCurveName name of the forward curve. @param model Monte Carlo model providing the forwards. @param startTime time at which the curve starts, i.e. zero time for the curve @return a discount curve from forwards given by a LIBORMonteCarloModel. @throws CalculationException Thrown if the model failed to provide the forward rates.
[ "Create", "a", "discount", "curve", "from", "forwards", "given", "by", "a", "LIBORMonteCarloModel", ".", "If", "the", "model", "uses", "multiple", "curves", "return", "its", "discount", "curve", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java#L401-L412
159,869
finmath/finmath-lib
src/main/java6/net/finmath/time/businessdaycalendar/BusinessdayCalendarExcludingTARGETHolidays.java
BusinessdayCalendarExcludingTARGETHolidays.isEasterSunday
public static boolean isEasterSunday(LocalDate date) { int y = date.getYear(); int a = y % 19; int b = y / 100; int c = y % 100; int d = b / 4; int e = b % 4; int f = (b + 8) / 25; int g = (b - f + 1) / 3; int h = (19 * a + b - d - g + 15) % 30; int i = c / 4; int k = c % 4; int l = (32 + 2 * e + 2 * i - h - k) % 7; int m = (a + 11 * h + 22 * l) / 451; int easterSundayMonth = (h + l - 7 * m + 114) / 31; int easterSundayDay = ((h + l - 7 * m + 114) % 31) + 1; int month = date.getMonthValue(); int day = date.getDayOfMonth(); return (easterSundayMonth == month) && (easterSundayDay == day); }
java
public static boolean isEasterSunday(LocalDate date) { int y = date.getYear(); int a = y % 19; int b = y / 100; int c = y % 100; int d = b / 4; int e = b % 4; int f = (b + 8) / 25; int g = (b - f + 1) / 3; int h = (19 * a + b - d - g + 15) % 30; int i = c / 4; int k = c % 4; int l = (32 + 2 * e + 2 * i - h - k) % 7; int m = (a + 11 * h + 22 * l) / 451; int easterSundayMonth = (h + l - 7 * m + 114) / 31; int easterSundayDay = ((h + l - 7 * m + 114) % 31) + 1; int month = date.getMonthValue(); int day = date.getDayOfMonth(); return (easterSundayMonth == month) && (easterSundayDay == day); }
[ "public", "static", "boolean", "isEasterSunday", "(", "LocalDate", "date", ")", "{", "int", "y", "=", "date", ".", "getYear", "(", ")", ";", "int", "a", "=", "y", "%", "19", ";", "int", "b", "=", "y", "/", "100", ";", "int", "c", "=", "y", "%", "100", ";", "int", "d", "=", "b", "/", "4", ";", "int", "e", "=", "b", "%", "4", ";", "int", "f", "=", "(", "b", "+", "8", ")", "/", "25", ";", "int", "g", "=", "(", "b", "-", "f", "+", "1", ")", "/", "3", ";", "int", "h", "=", "(", "19", "*", "a", "+", "b", "-", "d", "-", "g", "+", "15", ")", "%", "30", ";", "int", "i", "=", "c", "/", "4", ";", "int", "k", "=", "c", "%", "4", ";", "int", "l", "=", "(", "32", "+", "2", "*", "e", "+", "2", "*", "i", "-", "h", "-", "k", ")", "%", "7", ";", "int", "m", "=", "(", "a", "+", "11", "*", "h", "+", "22", "*", "l", ")", "/", "451", ";", "int", "easterSundayMonth", "=", "(", "h", "+", "l", "-", "7", "*", "m", "+", "114", ")", "/", "31", ";", "int", "easterSundayDay", "=", "(", "(", "h", "+", "l", "-", "7", "*", "m", "+", "114", ")", "%", "31", ")", "+", "1", ";", "int", "month", "=", "date", ".", "getMonthValue", "(", ")", ";", "int", "day", "=", "date", ".", "getDayOfMonth", "(", ")", ";", "return", "(", "easterSundayMonth", "==", "month", ")", "&&", "(", "easterSundayDay", "==", "day", ")", ";", "}" ]
Test a given date for being easter sunday. The method uses the algorithms sometimes cited as Meeus,Jones, Butcher Gregorian algorithm. Taken from http://en.wikipedia.org/wiki/Computus @param date The date to check. @return True, if date is easter sunday.
[ "Test", "a", "given", "date", "for", "being", "easter", "sunday", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/time/businessdaycalendar/BusinessdayCalendarExcludingTARGETHolidays.java#L67-L88
159,870
finmath/finmath-lib
src/main/java/net/finmath/time/FloatingpointDate.java
FloatingpointDate.getDateFromFloatingPointDate
public static LocalDateTime getDateFromFloatingPointDate(LocalDateTime referenceDate, double floatingPointDate) { if(referenceDate == null) { return null; } Duration duration = Duration.ofSeconds(Math.round(floatingPointDate * SECONDS_PER_DAY)); return referenceDate.plus(duration); }
java
public static LocalDateTime getDateFromFloatingPointDate(LocalDateTime referenceDate, double floatingPointDate) { if(referenceDate == null) { return null; } Duration duration = Duration.ofSeconds(Math.round(floatingPointDate * SECONDS_PER_DAY)); return referenceDate.plus(duration); }
[ "public", "static", "LocalDateTime", "getDateFromFloatingPointDate", "(", "LocalDateTime", "referenceDate", ",", "double", "floatingPointDate", ")", "{", "if", "(", "referenceDate", "==", "null", ")", "{", "return", "null", ";", "}", "Duration", "duration", "=", "Duration", ".", "ofSeconds", "(", "Math", ".", "round", "(", "floatingPointDate", "*", "SECONDS_PER_DAY", ")", ")", ";", "return", "referenceDate", ".", "plus", "(", "duration", ")", ";", "}" ]
Convert a floating point date to a LocalDateTime. Note: This method currently performs a rounding to the next second. If referenceDate is null, the method returns null. @param referenceDate The reference date associated with \( t=0 \). @param floatingPointDate The value to the time offset \( t \). @return The date resulting from adding Math.round(fixingTime*SECONDS_PER_DAY) seconds to referenceDate, where one day has SECONDS_PER_DAY seconds and SECONDS_PER_DAY is a constant 365*24*60*60
[ "Convert", "a", "floating", "point", "date", "to", "a", "LocalDateTime", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/FloatingpointDate.java#L67-L74
159,871
finmath/finmath-lib
src/main/java/net/finmath/time/FloatingpointDate.java
FloatingpointDate.getFloatingPointDateFromDate
public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) { Duration duration = Duration.between(referenceDate, date); return ((double)duration.getSeconds()) / SECONDS_PER_DAY; }
java
public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) { Duration duration = Duration.between(referenceDate, date); return ((double)duration.getSeconds()) / SECONDS_PER_DAY; }
[ "public", "static", "double", "getFloatingPointDateFromDate", "(", "LocalDateTime", "referenceDate", ",", "LocalDateTime", "date", ")", "{", "Duration", "duration", "=", "Duration", ".", "between", "(", "referenceDate", ",", "date", ")", ";", "return", "(", "(", "double", ")", "duration", ".", "getSeconds", "(", ")", ")", "/", "SECONDS_PER_DAY", ";", "}" ]
Convert a given date to a floating point date using a given reference date. @param referenceDate The reference date associated with \( t=0 \). @param date The given date to be associated with the return value \( T \). @return The value T measuring the distance of reference date and date by ACT/365 with SECONDS_PER_DAY seconds used as the smallest time unit and SECONDS_PER_DAY is a constant 365*24*60*60.
[ "Convert", "a", "given", "date", "to", "a", "floating", "point", "date", "using", "a", "given", "reference", "date", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/FloatingpointDate.java#L83-L86
159,872
finmath/finmath-lib
src/main/java/net/finmath/time/FloatingpointDate.java
FloatingpointDate.getDateFromFloatingPointDate
public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) { if(referenceDate == null) { return null; } return referenceDate.plusDays((int)Math.round(floatingPointDate*365.0)); }
java
public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) { if(referenceDate == null) { return null; } return referenceDate.plusDays((int)Math.round(floatingPointDate*365.0)); }
[ "public", "static", "LocalDate", "getDateFromFloatingPointDate", "(", "LocalDate", "referenceDate", ",", "double", "floatingPointDate", ")", "{", "if", "(", "referenceDate", "==", "null", ")", "{", "return", "null", ";", "}", "return", "referenceDate", ".", "plusDays", "(", "(", "int", ")", "Math", ".", "round", "(", "floatingPointDate", "*", "365.0", ")", ")", ";", "}" ]
Convert a floating point date to a LocalDate. Note: This method currently performs a rounding to the next day. In a future extension intra-day time offsets may be considered. If referenceDate is null, the method returns null. @param referenceDate The reference date associated with \( t=0 \). @param floatingPointDate The value to the time offset \( t \). @return The date resulting from adding Math.round(fixingTime*365.0) days to referenceDate.
[ "Convert", "a", "floating", "point", "date", "to", "a", "LocalDate", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/FloatingpointDate.java#L100-L105
159,873
finmath/finmath-lib
src/main/java6/net/finmath/functions/PoissonDistribution.java
PoissonDistribution.inverseCumulativeDistribution
public double inverseCumulativeDistribution(double x) { double p = Math.exp(-lambda); double dp = p; int k = 0; while(x > p) { k++; dp *= lambda / k; p += dp; } return k; }
java
public double inverseCumulativeDistribution(double x) { double p = Math.exp(-lambda); double dp = p; int k = 0; while(x > p) { k++; dp *= lambda / k; p += dp; } return k; }
[ "public", "double", "inverseCumulativeDistribution", "(", "double", "x", ")", "{", "double", "p", "=", "Math", ".", "exp", "(", "-", "lambda", ")", ";", "double", "dp", "=", "p", ";", "int", "k", "=", "0", ";", "while", "(", "x", ">", "p", ")", "{", "k", "++", ";", "dp", "*=", "lambda", "/", "k", ";", "p", "+=", "dp", ";", "}", "return", "k", ";", "}" ]
Return the inverse cumulative distribution function at x. @param x Argument @return Inverse cumulative distribution function at x.
[ "Return", "the", "inverse", "cumulative", "distribution", "function", "at", "x", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/PoissonDistribution.java#L27-L37
159,874
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/CurveInterpolation.java
CurveInterpolation.addPoint
protected void addPoint(double time, RandomVariable value, boolean isParameter) { synchronized (rationalFunctionInterpolationLazyInitLock) { if(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) { boolean containsOne = false; int index=0; for(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}} if(containsOne && isParameter == false) { return; } else { throw new IllegalArgumentException("The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index" + index + ")."); } } RandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time); int index = getTimeIndex(time); if(index >= 0) { if(points.get(index).value == interpolationEntityValue) { return; // Already in list } else if(isParameter) { return; } else { throw new RuntimeException("Trying to add a value for a time for which another value already exists."); } } else { // Insert the new point, retain ordering. Point point = new Point(time, interpolationEntityValue, isParameter); points.add(-index-1, point); if(isParameter) { // Add this point also to the list of parameters int parameterIndex = getParameterIndex(time); if(parameterIndex >= 0) { new RuntimeException("CurveFromInterpolationPoints inconsistent."); } pointsBeingParameters.add(-parameterIndex-1, point); } } rationalFunctionInterpolation = null; curveCacheReference = null; } }
java
protected void addPoint(double time, RandomVariable value, boolean isParameter) { synchronized (rationalFunctionInterpolationLazyInitLock) { if(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) { boolean containsOne = false; int index=0; for(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}} if(containsOne && isParameter == false) { return; } else { throw new IllegalArgumentException("The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index" + index + ")."); } } RandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time); int index = getTimeIndex(time); if(index >= 0) { if(points.get(index).value == interpolationEntityValue) { return; // Already in list } else if(isParameter) { return; } else { throw new RuntimeException("Trying to add a value for a time for which another value already exists."); } } else { // Insert the new point, retain ordering. Point point = new Point(time, interpolationEntityValue, isParameter); points.add(-index-1, point); if(isParameter) { // Add this point also to the list of parameters int parameterIndex = getParameterIndex(time); if(parameterIndex >= 0) { new RuntimeException("CurveFromInterpolationPoints inconsistent."); } pointsBeingParameters.add(-parameterIndex-1, point); } } rationalFunctionInterpolation = null; curveCacheReference = null; } }
[ "protected", "void", "addPoint", "(", "double", "time", ",", "RandomVariable", "value", ",", "boolean", "isParameter", ")", "{", "synchronized", "(", "rationalFunctionInterpolationLazyInitLock", ")", "{", "if", "(", "interpolationEntity", "==", "InterpolationEntity", ".", "LOG_OF_VALUE_PER_TIME", "&&", "time", "==", "0", ")", "{", "boolean", "containsOne", "=", "false", ";", "int", "index", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "value", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "value", ".", "get", "(", "i", ")", "==", "1.0", ")", "{", "containsOne", "=", "true", ";", "index", "=", "i", ";", "break", ";", "}", "}", "if", "(", "containsOne", "&&", "isParameter", "==", "false", ")", "{", "return", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\"", "+", "index", "+", "\").\"", ")", ";", "}", "}", "RandomVariable", "interpolationEntityValue", "=", "interpolationEntityFromValue", "(", "value", ",", "time", ")", ";", "int", "index", "=", "getTimeIndex", "(", "time", ")", ";", "if", "(", "index", ">=", "0", ")", "{", "if", "(", "points", ".", "get", "(", "index", ")", ".", "value", "==", "interpolationEntityValue", ")", "{", "return", ";", "// Already in list", "}", "else", "if", "(", "isParameter", ")", "{", "return", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Trying to add a value for a time for which another value already exists.\"", ")", ";", "}", "}", "else", "{", "// Insert the new point, retain ordering.", "Point", "point", "=", "new", "Point", "(", "time", ",", "interpolationEntityValue", ",", "isParameter", ")", ";", "points", ".", "add", "(", "-", "index", "-", "1", ",", "point", ")", ";", "if", "(", "isParameter", ")", "{", "// Add this point also to the list of parameters", "int", "parameterIndex", "=", "getParameterIndex", "(", "time", ")", ";", "if", "(", "parameterIndex", ">=", "0", ")", "{", "new", "RuntimeException", "(", "\"CurveFromInterpolationPoints inconsistent.\"", ")", ";", "}", "pointsBeingParameters", ".", "add", "(", "-", "parameterIndex", "-", "1", ",", "point", ")", ";", "}", "}", "rationalFunctionInterpolation", "=", "null", ";", "curveCacheReference", "=", "null", ";", "}", "}" ]
Add a point to this curveFromInterpolationPoints. The method will throw an exception if the point is already part of the curveFromInterpolationPoints. @param time The x<sub>i</sub> in <sub>i</sub> = f(x<sub>i</sub>). @param value The y<sub>i</sub> in <sub>i</sub> = f(x<sub>i</sub>). @param isParameter If true, then this point is served via {@link #getParameter()} and changed via {@link #getCloneForParameter(RandomVariable[])}, i.e., it can be calibrated.
[ "Add", "a", "point", "to", "this", "curveFromInterpolationPoints", ".", "The", "method", "will", "throw", "an", "exception", "if", "the", "point", "is", "already", "part", "of", "the", "curveFromInterpolationPoints", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/CurveInterpolation.java#L372-L413
159,875
finmath/finmath-lib
src/main/java/net/finmath/time/SchedulePrototype.java
SchedulePrototype.getOffsetCodeFromSchedule
public static String getOffsetCodeFromSchedule(Schedule schedule) { double doubleLength = 0; for(int i = 0; i < schedule.getNumberOfPeriods(); i ++) { doubleLength += schedule.getPeriodLength(i); } doubleLength /= schedule.getNumberOfPeriods(); doubleLength *= 12; int periodLength = (int) Math.round(doubleLength); String offsetCode = periodLength + "M"; return offsetCode; }
java
public static String getOffsetCodeFromSchedule(Schedule schedule) { double doubleLength = 0; for(int i = 0; i < schedule.getNumberOfPeriods(); i ++) { doubleLength += schedule.getPeriodLength(i); } doubleLength /= schedule.getNumberOfPeriods(); doubleLength *= 12; int periodLength = (int) Math.round(doubleLength); String offsetCode = periodLength + "M"; return offsetCode; }
[ "public", "static", "String", "getOffsetCodeFromSchedule", "(", "Schedule", "schedule", ")", "{", "double", "doubleLength", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "schedule", ".", "getNumberOfPeriods", "(", ")", ";", "i", "++", ")", "{", "doubleLength", "+=", "schedule", ".", "getPeriodLength", "(", "i", ")", ";", "}", "doubleLength", "/=", "schedule", ".", "getNumberOfPeriods", "(", ")", ";", "doubleLength", "*=", "12", ";", "int", "periodLength", "=", "(", "int", ")", "Math", ".", "round", "(", "doubleLength", ")", ";", "String", "offsetCode", "=", "periodLength", "+", "\"M\"", ";", "return", "offsetCode", ";", "}" ]
Determines the offset code of a forward contract from a schedule. Rounds the average period length to full months. @param schedule The schedule. @return The offset code as String
[ "Determines", "the", "offset", "code", "of", "a", "forward", "contract", "from", "a", "schedule", ".", "Rounds", "the", "average", "period", "length", "to", "full", "months", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/SchedulePrototype.java#L52-L66
159,876
finmath/finmath-lib
src/main/java/net/finmath/time/SchedulePrototype.java
SchedulePrototype.getOffsetCodeFromCurveName
public static String getOffsetCodeFromCurveName(String curveName) { if(curveName == null || curveName.length() == 0) { return null; } String[] splits = curveName.split("(?<=\\D)(?=\\d)"); String offsetCode = splits[splits.length-1]; if(!Character.isDigit(offsetCode.charAt(0))) { return null; } offsetCode = offsetCode.split("(?<=[A-Za-z])(?=.)", 2)[0]; offsetCode = offsetCode.replaceAll( "[\\W_]", "" ); return offsetCode; }
java
public static String getOffsetCodeFromCurveName(String curveName) { if(curveName == null || curveName.length() == 0) { return null; } String[] splits = curveName.split("(?<=\\D)(?=\\d)"); String offsetCode = splits[splits.length-1]; if(!Character.isDigit(offsetCode.charAt(0))) { return null; } offsetCode = offsetCode.split("(?<=[A-Za-z])(?=.)", 2)[0]; offsetCode = offsetCode.replaceAll( "[\\W_]", "" ); return offsetCode; }
[ "public", "static", "String", "getOffsetCodeFromCurveName", "(", "String", "curveName", ")", "{", "if", "(", "curveName", "==", "null", "||", "curveName", ".", "length", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "String", "[", "]", "splits", "=", "curveName", ".", "split", "(", "\"(?<=\\\\D)(?=\\\\d)\"", ")", ";", "String", "offsetCode", "=", "splits", "[", "splits", ".", "length", "-", "1", "]", ";", "if", "(", "!", "Character", ".", "isDigit", "(", "offsetCode", ".", "charAt", "(", "0", ")", ")", ")", "{", "return", "null", ";", "}", "offsetCode", "=", "offsetCode", ".", "split", "(", "\"(?<=[A-Za-z])(?=.)\"", ",", "2", ")", "[", "0", "]", ";", "offsetCode", "=", "offsetCode", ".", "replaceAll", "(", "\"[\\\\W_]\"", ",", "\"\"", ")", ";", "return", "offsetCode", ";", "}" ]
Determines the offset code of a forward contract from the name of a forward curve. This method will extract a group of one or more digits together with the first letter behind them, if any. If there are multiple groups of digits in the name, this method will extract the last. If there is no number in the string, this method will return null. @param curveName The name of the curve. @return The offset code as String
[ "Determines", "the", "offset", "code", "of", "a", "forward", "contract", "from", "the", "name", "of", "a", "forward", "curve", ".", "This", "method", "will", "extract", "a", "group", "of", "one", "or", "more", "digits", "together", "with", "the", "first", "letter", "behind", "them", "if", "any", ".", "If", "there", "are", "multiple", "groups", "of", "digits", "in", "the", "name", "this", "method", "will", "extract", "the", "last", ".", "If", "there", "is", "no", "number", "in", "the", "string", "this", "method", "will", "return", "null", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/SchedulePrototype.java#L77-L90
159,877
finmath/finmath-lib
src/main/java/net/finmath/time/SchedulePrototype.java
SchedulePrototype.generateScheduleDescriptor
public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) { return new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth()); }
java
public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) { return new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth()); }
[ "public", "ScheduleDescriptor", "generateScheduleDescriptor", "(", "LocalDate", "startDate", ",", "LocalDate", "endDate", ")", "{", "return", "new", "ScheduleDescriptor", "(", "startDate", ",", "endDate", ",", "getFrequency", "(", ")", ",", "getDaycountConvention", "(", ")", ",", "getShortPeriodConvention", "(", ")", ",", "getDateRollConvention", "(", ")", ",", "getBusinessdayCalendar", "(", ")", ",", "getFixingOffsetDays", "(", ")", ",", "getPaymentOffsetDays", "(", ")", ",", "isUseEndOfMonth", "(", ")", ")", ";", "}" ]
Generate a schedule descriptor for the given start and end date. @param startDate The start date. @param endDate The end date. @return The schedule descriptor
[ "Generate", "a", "schedule", "descriptor", "for", "the", "given", "start", "and", "end", "date", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/SchedulePrototype.java#L126-L129
159,878
finmath/finmath-lib
src/main/java/net/finmath/time/SchedulePrototype.java
SchedulePrototype.generateSchedule
public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) { return ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth()); }
java
public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) { return ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth()); }
[ "public", "Schedule", "generateSchedule", "(", "LocalDate", "referenceDate", ",", "LocalDate", "startDate", ",", "LocalDate", "endDate", ")", "{", "return", "ScheduleGenerator", ".", "createScheduleFromConventions", "(", "referenceDate", ",", "startDate", ",", "endDate", ",", "getFrequency", "(", ")", ",", "getDaycountConvention", "(", ")", ",", "getShortPeriodConvention", "(", ")", ",", "getDateRollConvention", "(", ")", ",", "getBusinessdayCalendar", "(", ")", ",", "getFixingOffsetDays", "(", ")", ",", "getPaymentOffsetDays", "(", ")", ",", "isUseEndOfMonth", "(", ")", ")", ";", "}" ]
Generate a schedule for the given start and end date. @param referenceDate The reference date (corresponds to \( t = 0 \). @param startDate The start date. @param endDate The end date. @return The schedule
[ "Generate", "a", "schedule", "for", "the", "given", "start", "and", "end", "date", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/SchedulePrototype.java#L139-L142
159,879
finmath/finmath-lib
src/main/java6/net/finmath/time/ScheduleGenerator.java
ScheduleGenerator.createScheduleFromConventions
@Deprecated public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, String frequency, double maturity, String daycountConvention, String shortPeriodConvention ) { return createScheduleFromConventions( referenceDate, startDate, frequency, maturity, daycountConvention, shortPeriodConvention, "UNADJUSTED", new BusinessdayCalendarAny(), 0, 0); }
java
@Deprecated public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, String frequency, double maturity, String daycountConvention, String shortPeriodConvention ) { return createScheduleFromConventions( referenceDate, startDate, frequency, maturity, daycountConvention, shortPeriodConvention, "UNADJUSTED", new BusinessdayCalendarAny(), 0, 0); }
[ "@", "Deprecated", "public", "static", "ScheduleInterface", "createScheduleFromConventions", "(", "LocalDate", "referenceDate", ",", "LocalDate", "startDate", ",", "String", "frequency", ",", "double", "maturity", ",", "String", "daycountConvention", ",", "String", "shortPeriodConvention", ")", "{", "return", "createScheduleFromConventions", "(", "referenceDate", ",", "startDate", ",", "frequency", ",", "maturity", ",", "daycountConvention", ",", "shortPeriodConvention", ",", "\"UNADJUSTED\"", ",", "new", "BusinessdayCalendarAny", "(", ")", ",", "0", ",", "0", ")", ";", "}" ]
Generates a schedule based on some meta data. The schedule generation considers short periods. Date rolling is ignored. @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. @param startDate The start date of the first period. @param frequency The frequency. @param maturity The end date of the last period. @param daycountConvention The daycount convention. @param shortPeriodConvention If short period exists, have it first or last. @return The corresponding schedule @deprecated Will be removed in version 2.3
[ "Generates", "a", "schedule", "based", "on", "some", "meta", "data", ".", "The", "schedule", "generation", "considers", "short", "periods", ".", "Date", "rolling", "is", "ignored", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/time/ScheduleGenerator.java#L790-L810
159,880
finmath/finmath-lib
src/main/java6/net/finmath/marketdata/calibration/CalibratedCurves.java
CalibratedCurves.getCalibrationProductForSymbol
public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) { /* * The internal data structure is not optimal here (a map would make more sense here), * if the user does not require access to the products, we would allow non-unique symbols. * Hence we store both in two side by side vectors. */ for(int i=0; i<calibrationProductsSymbols.size(); i++) { String calibrationProductSymbol = calibrationProductsSymbols.get(i); if(calibrationProductSymbol.equals(symbol)) { return calibrationProducts.get(i); } } return null; }
java
public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) { /* * The internal data structure is not optimal here (a map would make more sense here), * if the user does not require access to the products, we would allow non-unique symbols. * Hence we store both in two side by side vectors. */ for(int i=0; i<calibrationProductsSymbols.size(); i++) { String calibrationProductSymbol = calibrationProductsSymbols.get(i); if(calibrationProductSymbol.equals(symbol)) { return calibrationProducts.get(i); } } return null; }
[ "public", "AnalyticProductInterface", "getCalibrationProductForSymbol", "(", "String", "symbol", ")", "{", "/*\n\t\t * The internal data structure is not optimal here (a map would make more sense here),\n\t\t * if the user does not require access to the products, we would allow non-unique symbols.\n\t\t * Hence we store both in two side by side vectors.\n\t\t */", "for", "(", "int", "i", "=", "0", ";", "i", "<", "calibrationProductsSymbols", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "calibrationProductSymbol", "=", "calibrationProductsSymbols", ".", "get", "(", "i", ")", ";", "if", "(", "calibrationProductSymbol", ".", "equals", "(", "symbol", ")", ")", "{", "return", "calibrationProducts", ".", "get", "(", "i", ")", ";", "}", "}", "return", "null", ";", "}" ]
Returns the first product found in the vector of calibration products which matches the given symbol, where symbol is the String set in the calibrationSpecs. @param symbol A given symbol string. @return The product associated with that symbol.
[ "Returns", "the", "first", "product", "found", "in", "the", "vector", "of", "calibration", "products", "which", "matches", "the", "given", "symbol", "where", "symbol", "is", "the", "String", "set", "in", "the", "calibrationSpecs", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/calibration/CalibratedCurves.java#L649-L664
159,881
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/assetderivativevaluation/products/BermudanDigitalOption.java
BermudanDigitalOption.getValue
@Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { if(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) { // Find optimal lambda GoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0); while(!optimizer.isDone()) { double lambda = optimizer.getNextPoint(); double value = this.getValues(evaluationTime, model, lambda).getAverage(); optimizer.setValue(value); } return getValues(evaluationTime, model, optimizer.getBestPoint()); } else { return getValues(evaluationTime, model, 0.0); } }
java
@Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { if(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) { // Find optimal lambda GoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0); while(!optimizer.isDone()) { double lambda = optimizer.getNextPoint(); double value = this.getValues(evaluationTime, model, lambda).getAverage(); optimizer.setValue(value); } return getValues(evaluationTime, model, optimizer.getBestPoint()); } else { return getValues(evaluationTime, model, 0.0); } }
[ "@", "Override", "public", "RandomVariable", "getValue", "(", "double", "evaluationTime", ",", "AssetModelMonteCarloSimulationModel", "model", ")", "throws", "CalculationException", "{", "if", "(", "exerciseMethod", "==", "ExerciseMethod", ".", "UPPER_BOUND_METHOD", ")", "{", "// Find optimal lambda", "GoldenSectionSearch", "optimizer", "=", "new", "GoldenSectionSearch", "(", "-", "1.0", ",", "1.0", ")", ";", "while", "(", "!", "optimizer", ".", "isDone", "(", ")", ")", "{", "double", "lambda", "=", "optimizer", ".", "getNextPoint", "(", ")", ";", "double", "value", "=", "this", ".", "getValues", "(", "evaluationTime", ",", "model", ",", "lambda", ")", ".", "getAverage", "(", ")", ";", "optimizer", ".", "setValue", "(", "value", ")", ";", "}", "return", "getValues", "(", "evaluationTime", ",", "model", ",", "optimizer", ".", "getBestPoint", "(", ")", ")", ";", "}", "else", "{", "return", "getValues", "(", "evaluationTime", ",", "model", ",", "0.0", ")", ";", "}", "}" ]
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Cash-flows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time. @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "This", "method", "returns", "the", "value", "random", "variable", "of", "the", "product", "within", "the", "specified", "model", "evaluated", "at", "a", "given", "evalutationTime", ".", "Cash", "-", "flows", "prior", "evaluationTime", "are", "not", "considered", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/assetderivativevaluation/products/BermudanDigitalOption.java#L96-L111
159,882
finmath/finmath-lib
src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java
HazardCurve.createHazardCurveFromSurvivalProbabilities
public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){ HazardCurve survivalProbabilities = new HazardCurve(name); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { survivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0); } return survivalProbabilities; }
java
public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){ HazardCurve survivalProbabilities = new HazardCurve(name); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { survivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0); } return survivalProbabilities; }
[ "public", "static", "HazardCurve", "createHazardCurveFromSurvivalProbabilities", "(", "String", "name", ",", "double", "[", "]", "times", ",", "double", "[", "]", "givenSurvivalProbabilities", ")", "{", "HazardCurve", "survivalProbabilities", "=", "new", "HazardCurve", "(", "name", ")", ";", "for", "(", "int", "timeIndex", "=", "0", ";", "timeIndex", "<", "times", ".", "length", ";", "timeIndex", "++", ")", "{", "survivalProbabilities", ".", "addSurvivalProbability", "(", "times", "[", "timeIndex", "]", ",", "givenSurvivalProbabilities", "[", "timeIndex", "]", ",", "times", "[", "timeIndex", "]", ">", "0", ")", ";", "}", "return", "survivalProbabilities", ";", "}" ]
Create a hazard curve from given times and given discount factors using default interpolation and extrapolation methods. @param name The name of this hazard curve. @param times Array of times as doubles. @param givenSurvivalProbabilities Array of corresponding survival probabilities. @return A new discount factor object.
[ "Create", "a", "hazard", "curve", "from", "given", "times", "and", "given", "discount", "factors", "using", "default", "interpolation", "and", "extrapolation", "methods", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java#L152-L160
159,883
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.convertLattice
public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) { if(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) { throw new IllegalArgumentException("SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL."); } //Reverse sign of moneyness, if switching between payer and receiver convention. int reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1; List<Integer> maturities = new ArrayList<>(); List<Integer> tenors = new ArrayList<>(); List<Integer> moneynesss = new ArrayList<>(); List<Double> values = new ArrayList<>(); for(DataKey key : entryMap.keySet()) { maturities.add(key.maturity); tenors.add(key.tenor); moneynesss.add(key.moneyness * reverse); values.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model)); } return new SwaptionDataLattice(referenceDate, targetConvention, displacement, forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule, maturities.stream().mapToInt(Integer::intValue).toArray(), tenors.stream().mapToInt(Integer::intValue).toArray(), moneynesss.stream().mapToInt(Integer::intValue).toArray(), values.stream().mapToDouble(Double::doubleValue).toArray()); }
java
public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) { if(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) { throw new IllegalArgumentException("SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL."); } //Reverse sign of moneyness, if switching between payer and receiver convention. int reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1; List<Integer> maturities = new ArrayList<>(); List<Integer> tenors = new ArrayList<>(); List<Integer> moneynesss = new ArrayList<>(); List<Double> values = new ArrayList<>(); for(DataKey key : entryMap.keySet()) { maturities.add(key.maturity); tenors.add(key.tenor); moneynesss.add(key.moneyness * reverse); values.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model)); } return new SwaptionDataLattice(referenceDate, targetConvention, displacement, forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule, maturities.stream().mapToInt(Integer::intValue).toArray(), tenors.stream().mapToInt(Integer::intValue).toArray(), moneynesss.stream().mapToInt(Integer::intValue).toArray(), values.stream().mapToDouble(Double::doubleValue).toArray()); }
[ "public", "SwaptionDataLattice", "convertLattice", "(", "QuotingConvention", "targetConvention", ",", "double", "displacement", ",", "AnalyticModel", "model", ")", "{", "if", "(", "displacement", "!=", "0", "&&", "targetConvention", "!=", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL.\"", ")", ";", "}", "//Reverse sign of moneyness, if switching between payer and receiver convention.\r", "int", "reverse", "=", "(", "(", "targetConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", ")", "^", "(", "quotingConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", ")", ")", "?", "-", "1", ":", "1", ";", "List", "<", "Integer", ">", "maturities", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Integer", ">", "tenors", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Integer", ">", "moneynesss", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Double", ">", "values", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "DataKey", "key", ":", "entryMap", ".", "keySet", "(", ")", ")", "{", "maturities", ".", "add", "(", "key", ".", "maturity", ")", ";", "tenors", ".", "add", "(", "key", ".", "tenor", ")", ";", "moneynesss", ".", "add", "(", "key", ".", "moneyness", "*", "reverse", ")", ";", "values", ".", "add", "(", "getValue", "(", "key", ".", "maturity", ",", "key", ".", "tenor", ",", "key", ".", "moneyness", ",", "targetConvention", ",", "displacement", ",", "model", ")", ")", ";", "}", "return", "new", "SwaptionDataLattice", "(", "referenceDate", ",", "targetConvention", ",", "displacement", ",", "forwardCurveName", ",", "discountCurveName", ",", "floatMetaSchedule", ",", "fixMetaSchedule", ",", "maturities", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ",", "tenors", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ",", "moneynesss", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ",", "values", ".", "stream", "(", ")", ".", "mapToDouble", "(", "Double", "::", "doubleValue", ")", ".", "toArray", "(", ")", ")", ";", "}" ]
Convert this lattice to store data in the given convention. Conversion involving receiver premium assumes zero wide collar. @param targetConvention The convention to store the data in. @param displacement The displacement to use, if applicable. @param model The model for context. @return The converted lattice.
[ "Convert", "this", "lattice", "to", "store", "data", "in", "the", "given", "convention", ".", "Conversion", "involving", "receiver", "premium", "assumes", "zero", "wide", "collar", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L260-L287
159,884
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.append
public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) { SwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement, forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule); combined.entryMap.putAll(entryMap); if(quotingConvention == other.quotingConvention && displacement == other.displacement) { combined.entryMap.putAll(other.entryMap); } else { SwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model); combined.entryMap.putAll(converted.entryMap); } return combined; }
java
public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) { SwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement, forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule); combined.entryMap.putAll(entryMap); if(quotingConvention == other.quotingConvention && displacement == other.displacement) { combined.entryMap.putAll(other.entryMap); } else { SwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model); combined.entryMap.putAll(converted.entryMap); } return combined; }
[ "public", "SwaptionDataLattice", "append", "(", "SwaptionDataLattice", "other", ",", "AnalyticModel", "model", ")", "{", "SwaptionDataLattice", "combined", "=", "new", "SwaptionDataLattice", "(", "referenceDate", ",", "quotingConvention", ",", "displacement", ",", "forwardCurveName", ",", "discountCurveName", ",", "floatMetaSchedule", ",", "fixMetaSchedule", ")", ";", "combined", ".", "entryMap", ".", "putAll", "(", "entryMap", ")", ";", "if", "(", "quotingConvention", "==", "other", ".", "quotingConvention", "&&", "displacement", "==", "other", ".", "displacement", ")", "{", "combined", ".", "entryMap", ".", "putAll", "(", "other", ".", "entryMap", ")", ";", "}", "else", "{", "SwaptionDataLattice", "converted", "=", "other", ".", "convertLattice", "(", "quotingConvention", ",", "displacement", ",", "model", ")", ";", "combined", ".", "entryMap", ".", "putAll", "(", "converted", ".", "entryMap", ")", ";", "}", "return", "combined", ";", "}" ]
Append the data of another lattice to this lattice. If the other lattice follows a different quoting convention, it is automatically converted. However, this method does not check, whether the two lattices are aligned in terms of reference date, curve names and meta schedules. If the two lattices have shared data points, the data from this lattice will be overwritten. @param other The lattice containing the data to be appended. @param model The model to use for context, in case the other lattice follows a different convention. @return The lattice with the combined swaption entries.
[ "Append", "the", "data", "of", "another", "lattice", "to", "this", "lattice", ".", "If", "the", "other", "lattice", "follows", "a", "different", "quoting", "convention", "it", "is", "automatically", "converted", ".", "However", "this", "method", "does", "not", "check", "whether", "the", "two", "lattices", "are", "aligned", "in", "terms", "of", "reference", "date", "curve", "names", "and", "meta", "schedules", ".", "If", "the", "two", "lattices", "have", "shared", "data", "points", "the", "data", "from", "this", "lattice", "will", "be", "overwritten", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L299-L313
159,885
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.getMoneynessAsOffsets
public double[] getMoneynessAsOffsets() { DoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue); if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) { moneyness = moneyness.map(new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return x * 0.01; } }); } else if(quotingConvention == QuotingConvention.RECEIVERPRICE) { moneyness = moneyness.map(new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return - x * 0.0001; } }); } else { moneyness = moneyness.map(new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return x * 0.0001; } }); } return moneyness.toArray(); }
java
public double[] getMoneynessAsOffsets() { DoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue); if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) { moneyness = moneyness.map(new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return x * 0.01; } }); } else if(quotingConvention == QuotingConvention.RECEIVERPRICE) { moneyness = moneyness.map(new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return - x * 0.0001; } }); } else { moneyness = moneyness.map(new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return x * 0.0001; } }); } return moneyness.toArray(); }
[ "public", "double", "[", "]", "getMoneynessAsOffsets", "(", ")", "{", "DoubleStream", "moneyness", "=", "getGridNodesPerMoneyness", "(", ")", ".", "keySet", "(", ")", ".", "stream", "(", ")", ".", "mapToDouble", "(", "Integer", "::", "doubleValue", ")", ";", "if", "(", "quotingConvention", "==", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", "{", "moneyness", "=", "moneyness", ".", "map", "(", "new", "DoubleUnaryOperator", "(", ")", "{", "@", "Override", "public", "double", "applyAsDouble", "(", "double", "x", ")", "{", "return", "x", "*", "0.01", ";", "}", "}", ")", ";", "}", "else", "if", "(", "quotingConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", ")", "{", "moneyness", "=", "moneyness", ".", "map", "(", "new", "DoubleUnaryOperator", "(", ")", "{", "@", "Override", "public", "double", "applyAsDouble", "(", "double", "x", ")", "{", "return", "-", "x", "*", "0.0001", ";", "}", "}", ")", ";", "}", "else", "{", "moneyness", "=", "moneyness", ".", "map", "(", "new", "DoubleUnaryOperator", "(", ")", "{", "@", "Override", "public", "double", "applyAsDouble", "(", "double", "x", ")", "{", "return", "x", "*", "0.0001", ";", "}", "}", ")", ";", "}", "return", "moneyness", ".", "toArray", "(", ")", ";", "}" ]
Return all levels of moneyness for which data exists. Moneyness is returned as actual difference strike - par swap rate. @return The levels of moneyness as difference of strike to par swap rate.
[ "Return", "all", "levels", "of", "moneyness", "for", "which", "data", "exists", ".", "Moneyness", "is", "returned", "as", "actual", "difference", "strike", "-", "par", "swap", "rate", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L372-L397
159,886
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.getMaturities
public double[] getMaturities(double moneyness) { int[] maturitiesInMonths = getMaturities(convertMoneyness(moneyness)); double[] maturities = new double[maturitiesInMonths.length]; for(int index = 0; index < maturities.length; index++) { maturities[index] = convertMaturity(maturitiesInMonths[index]); } return maturities; }
java
public double[] getMaturities(double moneyness) { int[] maturitiesInMonths = getMaturities(convertMoneyness(moneyness)); double[] maturities = new double[maturitiesInMonths.length]; for(int index = 0; index < maturities.length; index++) { maturities[index] = convertMaturity(maturitiesInMonths[index]); } return maturities; }
[ "public", "double", "[", "]", "getMaturities", "(", "double", "moneyness", ")", "{", "int", "[", "]", "maturitiesInMonths", "=", "getMaturities", "(", "convertMoneyness", "(", "moneyness", ")", ")", ";", "double", "[", "]", "maturities", "=", "new", "double", "[", "maturitiesInMonths", ".", "length", "]", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "maturities", ".", "length", ";", "index", "++", ")", "{", "maturities", "[", "index", "]", "=", "convertMaturity", "(", "maturitiesInMonths", "[", "index", "]", ")", ";", "}", "return", "maturities", ";", "}" ]
Return all valid maturities for a given moneyness. Uses the fixing times of the fix schedule to determine fractions. @param moneyness The moneyness as actual offset from par swap rate for which to get the maturities. @return The maturities as year fraction from reference date.
[ "Return", "all", "valid", "maturities", "for", "a", "given", "moneyness", ".", "Uses", "the", "fixing", "times", "of", "the", "fix", "schedule", "to", "determine", "fractions", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L434-L442
159,887
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.getTenors
public int[] getTenors() { Set<Integer> setTenors = new HashSet<>(); for(int moneyness : getGridNodesPerMoneyness().keySet()) { setTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new)))); } return setTenors.stream().sorted().mapToInt(Integer::intValue).toArray(); }
java
public int[] getTenors() { Set<Integer> setTenors = new HashSet<>(); for(int moneyness : getGridNodesPerMoneyness().keySet()) { setTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new)))); } return setTenors.stream().sorted().mapToInt(Integer::intValue).toArray(); }
[ "public", "int", "[", "]", "getTenors", "(", ")", "{", "Set", "<", "Integer", ">", "setTenors", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "int", "moneyness", ":", "getGridNodesPerMoneyness", "(", ")", ".", "keySet", "(", ")", ")", "{", "setTenors", ".", "addAll", "(", "Arrays", ".", "asList", "(", "(", "IntStream", ".", "of", "(", "keyMap", ".", "get", "(", "moneyness", ")", "[", "1", "]", ")", ".", "boxed", "(", ")", ".", "toArray", "(", "Integer", "[", "]", "::", "new", ")", ")", ")", ")", ";", "}", "return", "setTenors", ".", "stream", "(", ")", ".", "sorted", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ";", "}" ]
Return all tenors for which data exists. @return The tenors in months.
[ "Return", "all", "tenors", "for", "which", "data", "exists", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L449-L456
159,888
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.getTenors
public int[] getTenors(int moneynessBP, int maturityInMonths) { try { List<Integer> ret = new ArrayList<>(); for(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) { if(containsEntryFor(maturityInMonths, tenor, moneynessBP)) { ret.add(tenor); } } return ret.stream().mapToInt(Integer::intValue).toArray(); } catch (NullPointerException e) { return new int[0]; } }
java
public int[] getTenors(int moneynessBP, int maturityInMonths) { try { List<Integer> ret = new ArrayList<>(); for(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) { if(containsEntryFor(maturityInMonths, tenor, moneynessBP)) { ret.add(tenor); } } return ret.stream().mapToInt(Integer::intValue).toArray(); } catch (NullPointerException e) { return new int[0]; } }
[ "public", "int", "[", "]", "getTenors", "(", "int", "moneynessBP", ",", "int", "maturityInMonths", ")", "{", "try", "{", "List", "<", "Integer", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "tenor", ":", "getGridNodesPerMoneyness", "(", ")", ".", "get", "(", "moneynessBP", ")", "[", "1", "]", ")", "{", "if", "(", "containsEntryFor", "(", "maturityInMonths", ",", "tenor", ",", "moneynessBP", ")", ")", "{", "ret", ".", "add", "(", "tenor", ")", ";", "}", "}", "return", "ret", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ";", "}", "catch", "(", "NullPointerException", "e", ")", "{", "return", "new", "int", "[", "0", "]", ";", "}", "}" ]
Return all valid tenors for a given moneyness and maturity. @param moneynessBP The moneyness in bp for which to get the tenors. @param maturityInMonths The maturities in months for which to get the tenors. @return The tenors in months.
[ "Return", "all", "valid", "tenors", "for", "a", "given", "moneyness", "and", "maturity", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L465-L478
159,889
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.getTenors
public double[] getTenors(double moneyness, double maturity) { int maturityInMonths = (int) Math.round(maturity * 12); int[] tenorsInMonths = getTenors(convertMoneyness(moneyness), maturityInMonths); double[] tenors = new double[tenorsInMonths.length]; for(int index = 0; index < tenors.length; index++) { tenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]); } return tenors; }
java
public double[] getTenors(double moneyness, double maturity) { int maturityInMonths = (int) Math.round(maturity * 12); int[] tenorsInMonths = getTenors(convertMoneyness(moneyness), maturityInMonths); double[] tenors = new double[tenorsInMonths.length]; for(int index = 0; index < tenors.length; index++) { tenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]); } return tenors; }
[ "public", "double", "[", "]", "getTenors", "(", "double", "moneyness", ",", "double", "maturity", ")", "{", "int", "maturityInMonths", "=", "(", "int", ")", "Math", ".", "round", "(", "maturity", "*", "12", ")", ";", "int", "[", "]", "tenorsInMonths", "=", "getTenors", "(", "convertMoneyness", "(", "moneyness", ")", ",", "maturityInMonths", ")", ";", "double", "[", "]", "tenors", "=", "new", "double", "[", "tenorsInMonths", ".", "length", "]", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "tenors", ".", "length", ";", "index", "++", ")", "{", "tenors", "[", "index", "]", "=", "convertTenor", "(", "maturityInMonths", ",", "tenorsInMonths", "[", "index", "]", ")", ";", "}", "return", "tenors", ";", "}" ]
Return all valid tenors for a given moneyness and maturity. Uses the payment times of the fix schedule to determine fractions. @param moneyness The moneyness as actual offset from par swap rate for which to get the maturities. @param maturity The maturities as year fraction from the reference date. @return The tenors as year fraction from reference date.
[ "Return", "all", "valid", "tenors", "for", "a", "given", "moneyness", "and", "maturity", ".", "Uses", "the", "payment", "times", "of", "the", "fix", "schedule", "to", "determine", "fractions", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L488-L497
159,890
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.convertMoneyness
private int convertMoneyness(double moneyness) { if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) { return (int) Math.round(moneyness * 100); } else if(quotingConvention == QuotingConvention.RECEIVERPRICE) { return - (int) Math.round(moneyness * 10000); } else { return (int) Math.round(moneyness * 10000); } }
java
private int convertMoneyness(double moneyness) { if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) { return (int) Math.round(moneyness * 100); } else if(quotingConvention == QuotingConvention.RECEIVERPRICE) { return - (int) Math.round(moneyness * 10000); } else { return (int) Math.round(moneyness * 10000); } }
[ "private", "int", "convertMoneyness", "(", "double", "moneyness", ")", "{", "if", "(", "quotingConvention", "==", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", "{", "return", "(", "int", ")", "Math", ".", "round", "(", "moneyness", "*", "100", ")", ";", "}", "else", "if", "(", "quotingConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", ")", "{", "return", "-", "(", "int", ")", "Math", ".", "round", "(", "moneyness", "*", "10000", ")", ";", "}", "else", "{", "return", "(", "int", ")", "Math", ".", "round", "(", "moneyness", "*", "10000", ")", ";", "}", "}" ]
Convert moneyness given as difference to par swap rate to moneyness in bp. Uses the fixing times of the fix schedule to determine fractions. @param moneyness as offset. @return Moneyness in bp.
[ "Convert", "moneyness", "given", "as", "difference", "to", "par", "swap", "rate", "to", "moneyness", "in", "bp", ".", "Uses", "the", "fixing", "times", "of", "the", "fix", "schedule", "to", "determine", "fractions", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L506-L514
159,891
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.convertMaturity
private double convertMaturity(int maturityInMonths) { Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12); return schedule.getFixing(0); }
java
private double convertMaturity(int maturityInMonths) { Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12); return schedule.getFixing(0); }
[ "private", "double", "convertMaturity", "(", "int", "maturityInMonths", ")", "{", "Schedule", "schedule", "=", "fixMetaSchedule", ".", "generateSchedule", "(", "referenceDate", ",", "maturityInMonths", ",", "12", ")", ";", "return", "schedule", ".", "getFixing", "(", "0", ")", ";", "}" ]
Convert maturity given as offset in months to year fraction. @param maturityInMonths The maturity as offset in months. @return The maturity as year fraction.
[ "Convert", "maturity", "given", "as", "offset", "in", "months", "to", "year", "fraction", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L522-L525
159,892
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.convertTenor
private double convertTenor(int maturityInMonths, int tenorInMonths) { Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths); return schedule.getPayment(schedule.getNumberOfPeriods()-1); }
java
private double convertTenor(int maturityInMonths, int tenorInMonths) { Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths); return schedule.getPayment(schedule.getNumberOfPeriods()-1); }
[ "private", "double", "convertTenor", "(", "int", "maturityInMonths", ",", "int", "tenorInMonths", ")", "{", "Schedule", "schedule", "=", "fixMetaSchedule", ".", "generateSchedule", "(", "referenceDate", ",", "maturityInMonths", ",", "tenorInMonths", ")", ";", "return", "schedule", ".", "getPayment", "(", "schedule", ".", "getNumberOfPeriods", "(", ")", "-", "1", ")", ";", "}" ]
Convert tenor given as offset in months to year fraction. @param maturityInMonths The maturity as offset in months. @param tenorInMonths The tenor as offset in months. @return THe tenor as year fraction.
[ "Convert", "tenor", "given", "as", "offset", "in", "months", "to", "year", "fraction", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L534-L537
159,893
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.containsEntryFor
public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) { return entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP)); }
java
public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) { return entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP)); }
[ "public", "boolean", "containsEntryFor", "(", "int", "maturityInMonths", ",", "int", "tenorInMonths", ",", "int", "moneynessBP", ")", "{", "return", "entryMap", ".", "containsKey", "(", "new", "DataKey", "(", "maturityInMonths", ",", "tenorInMonths", ",", "moneynessBP", ")", ")", ";", "}" ]
Returns true if the lattice contains an entry at the specified location. @param maturityInMonths The maturity in months to check. @param tenorInMonths The tenor in months to check. @param moneynessBP The moneyness in bp to check. @return True iff there is an entry at the specified location.
[ "Returns", "true", "if", "the", "lattice", "contains", "an", "entry", "at", "the", "specified", "location", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L547-L549
159,894
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.convertToConvention
private double convertToConvention(double value, DataKey key, QuotingConvention toConvention, double toDisplacement, QuotingConvention fromConvention, double fromDisplacement, AnalyticModel model) { if(toConvention == fromConvention) { if(toConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) { return value; } else { if(toDisplacement == fromDisplacement) { return value; } else { return convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model), key, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model); } } } Schedule floatSchedule = floatMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor); Schedule fixSchedule = fixMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor); double forward = Swap.getForwardSwapRate(fixSchedule, floatSchedule, model.getForwardCurve(forwardCurveName), model); double optionMaturity = floatSchedule.getFixing(0); double offset = key.moneyness /10000.0; double optionStrike = forward + (quotingConvention == QuotingConvention.RECEIVERPRICE ? -offset : offset); double payoffUnit = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, model.getDiscountCurve(discountCurveName), model); if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL)) { return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward + fromDisplacement, value, optionMaturity, optionStrike + fromDisplacement, payoffUnit); } else if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL)) { return AnalyticFormulas.bachelierOptionValue(forward, value, optionMaturity, optionStrike, payoffUnit); } else if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.RECEIVERPRICE)) { return value + (forward - optionStrike) * payoffUnit; } else if(toConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) { return AnalyticFormulas.blackScholesOptionImpliedVolatility(forward + toDisplacement, optionMaturity, optionStrike + toDisplacement, payoffUnit, value); } else if(toConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) { return AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, value); } else if(toConvention.equals(QuotingConvention.RECEIVERPRICE) && fromConvention.equals(QuotingConvention.PAYERPRICE)) { return value - (forward - optionStrike) * payoffUnit; } else { return convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model), key, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model); } }
java
private double convertToConvention(double value, DataKey key, QuotingConvention toConvention, double toDisplacement, QuotingConvention fromConvention, double fromDisplacement, AnalyticModel model) { if(toConvention == fromConvention) { if(toConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) { return value; } else { if(toDisplacement == fromDisplacement) { return value; } else { return convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model), key, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model); } } } Schedule floatSchedule = floatMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor); Schedule fixSchedule = fixMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor); double forward = Swap.getForwardSwapRate(fixSchedule, floatSchedule, model.getForwardCurve(forwardCurveName), model); double optionMaturity = floatSchedule.getFixing(0); double offset = key.moneyness /10000.0; double optionStrike = forward + (quotingConvention == QuotingConvention.RECEIVERPRICE ? -offset : offset); double payoffUnit = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, model.getDiscountCurve(discountCurveName), model); if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL)) { return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward + fromDisplacement, value, optionMaturity, optionStrike + fromDisplacement, payoffUnit); } else if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL)) { return AnalyticFormulas.bachelierOptionValue(forward, value, optionMaturity, optionStrike, payoffUnit); } else if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.RECEIVERPRICE)) { return value + (forward - optionStrike) * payoffUnit; } else if(toConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) { return AnalyticFormulas.blackScholesOptionImpliedVolatility(forward + toDisplacement, optionMaturity, optionStrike + toDisplacement, payoffUnit, value); } else if(toConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) { return AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, value); } else if(toConvention.equals(QuotingConvention.RECEIVERPRICE) && fromConvention.equals(QuotingConvention.PAYERPRICE)) { return value - (forward - optionStrike) * payoffUnit; } else { return convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model), key, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model); } }
[ "private", "double", "convertToConvention", "(", "double", "value", ",", "DataKey", "key", ",", "QuotingConvention", "toConvention", ",", "double", "toDisplacement", ",", "QuotingConvention", "fromConvention", ",", "double", "fromDisplacement", ",", "AnalyticModel", "model", ")", "{", "if", "(", "toConvention", "==", "fromConvention", ")", "{", "if", "(", "toConvention", "!=", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", "{", "return", "value", ";", "}", "else", "{", "if", "(", "toDisplacement", "==", "fromDisplacement", ")", "{", "return", "value", ";", "}", "else", "{", "return", "convertToConvention", "(", "convertToConvention", "(", "value", ",", "key", ",", "QuotingConvention", ".", "PAYERPRICE", ",", "0", ",", "fromConvention", ",", "fromDisplacement", ",", "model", ")", ",", "key", ",", "toConvention", ",", "toDisplacement", ",", "QuotingConvention", ".", "PAYERPRICE", ",", "0", ",", "model", ")", ";", "}", "}", "}", "Schedule", "floatSchedule", "=", "floatMetaSchedule", ".", "generateSchedule", "(", "getReferenceDate", "(", ")", ",", "key", ".", "maturity", ",", "key", ".", "tenor", ")", ";", "Schedule", "fixSchedule", "=", "fixMetaSchedule", ".", "generateSchedule", "(", "getReferenceDate", "(", ")", ",", "key", ".", "maturity", ",", "key", ".", "tenor", ")", ";", "double", "forward", "=", "Swap", ".", "getForwardSwapRate", "(", "fixSchedule", ",", "floatSchedule", ",", "model", ".", "getForwardCurve", "(", "forwardCurveName", ")", ",", "model", ")", ";", "double", "optionMaturity", "=", "floatSchedule", ".", "getFixing", "(", "0", ")", ";", "double", "offset", "=", "key", ".", "moneyness", "/", "10000.0", ";", "double", "optionStrike", "=", "forward", "+", "(", "quotingConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", "?", "-", "offset", ":", "offset", ")", ";", "double", "payoffUnit", "=", "SwapAnnuity", ".", "getSwapAnnuity", "(", "fixSchedule", ".", "getFixing", "(", "0", ")", ",", "fixSchedule", ",", "model", ".", "getDiscountCurve", "(", "discountCurveName", ")", ",", "model", ")", ";", "if", "(", "toConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERPRICE", ")", "&&", "fromConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", ")", "{", "return", "AnalyticFormulas", ".", "blackScholesGeneralizedOptionValue", "(", "forward", "+", "fromDisplacement", ",", "value", ",", "optionMaturity", ",", "optionStrike", "+", "fromDisplacement", ",", "payoffUnit", ")", ";", "}", "else", "if", "(", "toConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERPRICE", ")", "&&", "fromConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERVOLATILITYNORMAL", ")", ")", "{", "return", "AnalyticFormulas", ".", "bachelierOptionValue", "(", "forward", ",", "value", ",", "optionMaturity", ",", "optionStrike", ",", "payoffUnit", ")", ";", "}", "else", "if", "(", "toConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERPRICE", ")", "&&", "fromConvention", ".", "equals", "(", "QuotingConvention", ".", "RECEIVERPRICE", ")", ")", "{", "return", "value", "+", "(", "forward", "-", "optionStrike", ")", "*", "payoffUnit", ";", "}", "else", "if", "(", "toConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", "&&", "fromConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERPRICE", ")", ")", "{", "return", "AnalyticFormulas", ".", "blackScholesOptionImpliedVolatility", "(", "forward", "+", "toDisplacement", ",", "optionMaturity", ",", "optionStrike", "+", "toDisplacement", ",", "payoffUnit", ",", "value", ")", ";", "}", "else", "if", "(", "toConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERVOLATILITYNORMAL", ")", "&&", "fromConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERPRICE", ")", ")", "{", "return", "AnalyticFormulas", ".", "bachelierOptionImpliedVolatility", "(", "forward", ",", "optionMaturity", ",", "optionStrike", ",", "payoffUnit", ",", "value", ")", ";", "}", "else", "if", "(", "toConvention", ".", "equals", "(", "QuotingConvention", ".", "RECEIVERPRICE", ")", "&&", "fromConvention", ".", "equals", "(", "QuotingConvention", ".", "PAYERPRICE", ")", ")", "{", "return", "value", "-", "(", "forward", "-", "optionStrike", ")", "*", "payoffUnit", ";", "}", "else", "{", "return", "convertToConvention", "(", "convertToConvention", "(", "value", ",", "key", ",", "QuotingConvention", ".", "PAYERPRICE", ",", "0", ",", "fromConvention", ",", "fromDisplacement", ",", "model", ")", ",", "key", ",", "toConvention", ",", "toDisplacement", ",", "QuotingConvention", ".", "PAYERPRICE", ",", "0", ",", "model", ")", ";", "}", "}" ]
Convert the value to requested quoting convention. Conversion involving receiver premium assumes zero wide collar. @param value The value to convert. @param key The key of the value. @param toConvention The convention to convert to. @param toDisplacement The displacement to be used, if converting to log normal implied volatility. @param fromConvention The current convention of the value. @param fromDisplacement The current displacement. @param model The model for context. @return The converted value.
[ "Convert", "the", "value", "to", "requested", "quoting", "convention", ".", "Conversion", "involving", "receiver", "premium", "assumes", "zero", "wide", "collar", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L666-L713
159,895
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getCouponPayment
public double getCouponPayment(int periodIndex, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) { throw new IllegalArgumentException("No forward curve with name '" + forwardCurveName + "' was found in the model:\n" + model.toString()); } double periodLength = schedule.getPeriodLength(periodIndex); double couponPayment=fixedCoupon ; if(forwardCurve != null ) { couponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex)); } return couponPayment*periodLength; }
java
public double getCouponPayment(int periodIndex, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) { throw new IllegalArgumentException("No forward curve with name '" + forwardCurveName + "' was found in the model:\n" + model.toString()); } double periodLength = schedule.getPeriodLength(periodIndex); double couponPayment=fixedCoupon ; if(forwardCurve != null ) { couponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex)); } return couponPayment*periodLength; }
[ "public", "double", "getCouponPayment", "(", "int", "periodIndex", ",", "AnalyticModel", "model", ")", "{", "ForwardCurve", "forwardCurve", "=", "model", ".", "getForwardCurve", "(", "forwardCurveName", ")", ";", "if", "(", "forwardCurve", "==", "null", "&&", "forwardCurveName", "!=", "null", "&&", "forwardCurveName", ".", "length", "(", ")", ">", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No forward curve with name '\"", "+", "forwardCurveName", "+", "\"' was found in the model:\\n\"", "+", "model", ".", "toString", "(", ")", ")", ";", "}", "double", "periodLength", "=", "schedule", ".", "getPeriodLength", "(", "periodIndex", ")", ";", "double", "couponPayment", "=", "fixedCoupon", ";", "if", "(", "forwardCurve", "!=", "null", ")", "{", "couponPayment", "=", "floatingSpread", "+", "forwardCurve", ".", "getForward", "(", "model", ",", "schedule", ".", "getFixing", "(", "periodIndex", ")", ")", ";", "}", "return", "couponPayment", "*", "periodLength", ";", "}" ]
Returns the coupon payment of the period with the given index. The analytic model is needed in case of floating bonds. @param periodIndex The index of the period of interest. @param model The model under which the product is valued. @return The value of the coupon payment in the given period.
[ "Returns", "the", "coupon", "payment", "of", "the", "period", "with", "the", "given", "index", ".", "The", "analytic", "model", "is", "needed", "in", "case", "of", "floating", "bonds", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L209-L222
159,896
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getValueWithGivenSpreadOverCurve
public double getValueWithGivenSpreadOverCurve(double evaluationTime,Curve referenceCurve, double spread, AnalyticModel model) { double value=0; for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods();periodIndex++) { double paymentDate = schedule.getPayment(periodIndex); value+= paymentDate>evaluationTime ? getCouponPayment(periodIndex,model)*Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate): 0.0; } double paymentDate = schedule.getPayment(schedule.getNumberOfPeriods()-1); return paymentDate>evaluationTime ? value+Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate):0.0; }
java
public double getValueWithGivenSpreadOverCurve(double evaluationTime,Curve referenceCurve, double spread, AnalyticModel model) { double value=0; for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods();periodIndex++) { double paymentDate = schedule.getPayment(periodIndex); value+= paymentDate>evaluationTime ? getCouponPayment(periodIndex,model)*Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate): 0.0; } double paymentDate = schedule.getPayment(schedule.getNumberOfPeriods()-1); return paymentDate>evaluationTime ? value+Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate):0.0; }
[ "public", "double", "getValueWithGivenSpreadOverCurve", "(", "double", "evaluationTime", ",", "Curve", "referenceCurve", ",", "double", "spread", ",", "AnalyticModel", "model", ")", "{", "double", "value", "=", "0", ";", "for", "(", "int", "periodIndex", "=", "0", ";", "periodIndex", "<", "schedule", ".", "getNumberOfPeriods", "(", ")", ";", "periodIndex", "++", ")", "{", "double", "paymentDate", "=", "schedule", ".", "getPayment", "(", "periodIndex", ")", ";", "value", "+=", "paymentDate", ">", "evaluationTime", "?", "getCouponPayment", "(", "periodIndex", ",", "model", ")", "*", "Math", ".", "exp", "(", "-", "spread", "*", "paymentDate", ")", "*", "referenceCurve", ".", "getValue", "(", "paymentDate", ")", ":", "0.0", ";", "}", "double", "paymentDate", "=", "schedule", ".", "getPayment", "(", "schedule", ".", "getNumberOfPeriods", "(", ")", "-", "1", ")", ";", "return", "paymentDate", ">", "evaluationTime", "?", "value", "+", "Math", ".", "exp", "(", "-", "spread", "*", "paymentDate", ")", "*", "referenceCurve", ".", "getValue", "(", "paymentDate", ")", ":", "0.0", ";", "}" ]
Returns the value of the sum of discounted cash flows of the bond where the discounting is done with the given reference curve and an additional spread. This method can be used for optimizer. @param evaluationTime The evaluation time as double. Cash flows prior and including this time are not considered. @param referenceCurve The reference curve used for discounting the coupon payments. @param spread The spread which should be added to the discount curve. @param model The model under which the product is valued. @return The value of the bond for the given curve and spread.
[ "Returns", "the", "value", "of", "the", "sum", "of", "discounted", "cash", "flows", "of", "the", "bond", "where", "the", "discounting", "is", "done", "with", "the", "given", "reference", "curve", "and", "an", "additional", "spread", ".", "This", "method", "can", "be", "used", "for", "optimizer", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L235-L244
159,897
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getValueWithGivenYield
public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) { DiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors("referenceCurve", new double[] {0.0, 1.0}, new double[] {1.0, 1.0}); return getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model); }
java
public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) { DiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors("referenceCurve", new double[] {0.0, 1.0}, new double[] {1.0, 1.0}); return getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model); }
[ "public", "double", "getValueWithGivenYield", "(", "double", "evaluationTime", ",", "double", "rate", ",", "AnalyticModel", "model", ")", "{", "DiscountCurve", "referenceCurve", "=", "DiscountCurveInterpolation", ".", "createDiscountCurveFromDiscountFactors", "(", "\"referenceCurve\"", ",", "new", "double", "[", "]", "{", "0.0", ",", "1.0", "}", ",", "new", "double", "[", "]", "{", "1.0", ",", "1.0", "}", ")", ";", "return", "getValueWithGivenSpreadOverCurve", "(", "evaluationTime", ",", "referenceCurve", ",", "rate", ",", "model", ")", ";", "}" ]
Returns the value of the sum of discounted cash flows of the bond where the discounting is done with the given yield curve. This method can be used for optimizer. @param evaluationTime The evaluation time as double. Cash flows prior and including this time are not considered. @param rate The yield which is used for discounted the coupon payments. @param model The model under which the product is valued. @return The value of the bond for the given yield.
[ "Returns", "the", "value", "of", "the", "sum", "of", "discounted", "cash", "flows", "of", "the", "bond", "where", "the", "discounting", "is", "done", "with", "the", "given", "yield", "curve", ".", "This", "method", "can", "be", "used", "for", "optimizer", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L256-L259
159,898
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getSpread
public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) { GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0); while(search.getAccuracy() > 1E-11 && !search.isDone()) { double x = search.getNextPoint(); double fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model); double y = (bondPrice-fx)*(bondPrice-fx); search.setValue(y); } return search.getBestPoint(); }
java
public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) { GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0); while(search.getAccuracy() > 1E-11 && !search.isDone()) { double x = search.getNextPoint(); double fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model); double y = (bondPrice-fx)*(bondPrice-fx); search.setValue(y); } return search.getBestPoint(); }
[ "public", "double", "getSpread", "(", "double", "bondPrice", ",", "Curve", "referenceCurve", ",", "AnalyticModel", "model", ")", "{", "GoldenSectionSearch", "search", "=", "new", "GoldenSectionSearch", "(", "-", "2.0", ",", "2.0", ")", ";", "while", "(", "search", ".", "getAccuracy", "(", ")", ">", "1E-11", "&&", "!", "search", ".", "isDone", "(", ")", ")", "{", "double", "x", "=", "search", ".", "getNextPoint", "(", ")", ";", "double", "fx", "=", "getValueWithGivenSpreadOverCurve", "(", "0.0", ",", "referenceCurve", ",", "x", ",", "model", ")", ";", "double", "y", "=", "(", "bondPrice", "-", "fx", ")", "*", "(", "bondPrice", "-", "fx", ")", ";", "search", ".", "setValue", "(", "y", ")", ";", "}", "return", "search", ".", "getBestPoint", "(", ")", ";", "}" ]
Returns the spread value such that the sum of cash flows of the bond discounted with a given reference curve with the additional spread coincides with a given price. @param bondPrice The target price as double. @param referenceCurve The reference curve used for discounting the coupon payments. @param model The model under which the product is valued. @return The optimal spread value.
[ "Returns", "the", "spread", "value", "such", "that", "the", "sum", "of", "cash", "flows", "of", "the", "bond", "discounted", "with", "a", "given", "reference", "curve", "with", "the", "additional", "spread", "coincides", "with", "a", "given", "price", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L270-L280
159,899
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getYield
public double getYield(double bondPrice, AnalyticModel model) { GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0); while(search.getAccuracy() > 1E-11 && !search.isDone()) { double x = search.getNextPoint(); double fx=getValueWithGivenYield(0.0,x,model); double y = (bondPrice-fx)*(bondPrice-fx); search.setValue(y); } return search.getBestPoint(); }
java
public double getYield(double bondPrice, AnalyticModel model) { GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0); while(search.getAccuracy() > 1E-11 && !search.isDone()) { double x = search.getNextPoint(); double fx=getValueWithGivenYield(0.0,x,model); double y = (bondPrice-fx)*(bondPrice-fx); search.setValue(y); } return search.getBestPoint(); }
[ "public", "double", "getYield", "(", "double", "bondPrice", ",", "AnalyticModel", "model", ")", "{", "GoldenSectionSearch", "search", "=", "new", "GoldenSectionSearch", "(", "-", "2.0", ",", "2.0", ")", ";", "while", "(", "search", ".", "getAccuracy", "(", ")", ">", "1E-11", "&&", "!", "search", ".", "isDone", "(", ")", ")", "{", "double", "x", "=", "search", ".", "getNextPoint", "(", ")", ";", "double", "fx", "=", "getValueWithGivenYield", "(", "0.0", ",", "x", ",", "model", ")", ";", "double", "y", "=", "(", "bondPrice", "-", "fx", ")", "*", "(", "bondPrice", "-", "fx", ")", ";", "search", ".", "setValue", "(", "y", ")", ";", "}", "return", "search", ".", "getBestPoint", "(", ")", ";", "}" ]
Returns the yield value such that the sum of cash flows of the bond discounted with the yield curve coincides with a given price. @param bondPrice The target price as double. @param model The model under which the product is valued. @return The optimal yield value.
[ "Returns", "the", "yield", "value", "such", "that", "the", "sum", "of", "cash", "flows", "of", "the", "bond", "discounted", "with", "the", "yield", "curve", "coincides", "with", "a", "given", "price", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L290-L300