Skip to content

Commit

Permalink
added convenience initializer
Browse files Browse the repository at this point in the history
  • Loading branch information
Reed Es committed Jan 26, 2022
1 parent b54ffa8 commit e0a5006
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ typealias MD = ModifiedDietz<Float>

## Initialization

Two initializers are provided, one more explicit than the other, but functionally equivalent:

- `init?(period: DateInterval, startValue: T, endValue: T, cashflowMap: [Date: T], epsilon: T)` - Conveniently initialize a ModifiedDietz with explicit parameters.

- `init?(DateInterval, ModifiedDietz<T>.MarketValueDelta, ModifiedDietz<T>.CashflowMap, epsilon: T)` - Initialize a ModifiedDietz with the specified parameters.

Initialization will fail and return `nil` if provided nonsense parameters, such as a period with zero duration.
Expand Down
10 changes: 10 additions & 0 deletions Sources/ModifiedDietz.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ public final class ModifiedDietz<T: BinaryFloatingPoint> {
/// Optional precision for comparing values that are very close to one another.
public let epsilon: T

/// Conveniently initialize a `ModifiedDietz` with explicit parameters.
public convenience init?(period: DateInterval,
startValue: T,
endValue: T,
cashflowMap: CashflowMap = [:],
epsilon: T = 0.0001) {
let mvd = MarketValueDelta(start: startValue, end: endValue)
self.init(period, mvd, cashflowMap, epsilon: epsilon)
}

/// Initialize a `ModifiedDietz` with the specified parameters.
public init?(_ period: DateInterval,
_ marketValue: MarketValueDelta,
Expand Down
15 changes: 15 additions & 0 deletions Tests/ModifiedDietzTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -238,4 +238,19 @@ final class MDTests: XCTestCase {
XCTAssertEqual(0.05, md.performance, accuracy: 0.001)
//print("\(md.performance * 100)%")
}

func testConvenienceInit() throws {
typealias MD = ModifiedDietz<Double>
let df = ISO8601DateFormatter()
let beg = df.date(from: "2020-06-01T12:00:00Z")!
let mid = df.date(from: "2020-06-16T00:00:00Z")!
let end = df.date(from: "2020-06-30T12:00:00Z")!

let period = DateInterval(start: beg, end: end)
let cf: MD.CashflowMap = [mid: -10.0]
let md = MD(period: period, startValue: 105, endValue: 100, cashflowMap: cf)!

XCTAssertEqual(0.05, md.performance, accuracy: 0.001)
//print("\(md.performance * 100)%")
}
}

0 comments on commit e0a5006

Please sign in to comment.