I am currently making an app where I have to retrieve allowances for certain hours worked.
For example, I work from 3:00 pm to 10:00 pm.
Between this time an allowance would be given between 8:00 pm - 10:00 pm 20% and from 10:00 pm to 11:00 pm 35%.
Until now I did not get much further than a rather complicated if construction.
if startUur <= 20 && eindUur >= 22 || 20..<22 ~= startUur || 20..<22 ~= eindUur || startUur > 20 && eindUur <= 22 && startMinuut > 0 || startUur < 20 {
//code to calculate allowance
}
I have been looking for a good and better way to do this, but I cannot find it.
Is there a better way or am I bound to such a way with an if construction?
struct TimeAndMoneyFrame {
var timeHourStart:Int = 0
var timeHourEnd:Int = 0
var percentage: Double = 0
}
extension TimeAndMoneyFrame {
func timeLength() -> Int {
return timeHourEnd - timeHourStart
}
}
let 2000to2200 = TimeAndMoneyFrame(timeHourStart = 20, timeHourEnd = 22, percentage = 0.2)
let 2200to2300 = TimeAndMoneyFrame(timeHourStart = 22, timeHourEnd = 23, percentage = 0.35)
let timeArray:[TimeAndMoneyFrame] = [2000to2200]
//Assuming 'startUur' means startingHour
//Assuming 'eindUur' means endingHour
let startUur:Int = someHour // You define some hour
let eindUure:Int = someHour // You define some hour
let hourlyRateOfPay: Double = somePay // You define some pay
var totalPay: Double = 0
for time in timeArray {
let start = time.timeHourStart
let end = time.timeHourEnd
let percent = time.percentage
//Encompasses entirely
if(start > startUur && end < eindUur) {
totalPay += (hourlyRateOfPay * (1 + percent) * time.timeLength())
}
//Only encompassed the left side - i.e., their time worked ends within this time frame
else if(start > startUur) {
let timeWithinThisFrame = eindUur - start
totalPay += (hourlyRateOfPay * (1 + percent) * (timeWithinThisFrame/time.timeLength())
}
//Only encompassed right side - i.e., the beginning of the starts within this time frame
else if(eindUur < end) {
let timeWithinThisFrame = end - startUur
totalPay += (hourlyRateOfPay * (1 + percent) * (timeWithinThisFrame/time.timeLength())
}
}
So, we can break this problemn up into a couple problems.
1) Defining a struct/class that encompasses a time frame with an associated percentage
2) The algorithm necessary to calculate the total pay
I have a base assumption.
1) You say allowances - a person gets 35% if they work from 2200-2300 - I took this as a bonus so say 1.35% of the normal hourly rate. If this is not the case, the idea of consuming time frames one at a time would be the same. The only difference might be the totalPay calculation.
My algorithm goes through each time frame and determines if the current time intercepts any of the time frames. If it does, I calculate how much it intercepts and calculate the rate of pay.
Note: I coded all of this on SO - there might be some syntax issues.
Related
I am trying to code an RSI (which has been a good way for me to learn API data fetching and algorithms already).
The API I am fetching data from comes from a reputable exchange so I know the values my algorithm is analyzing are correct, that's a good start.
The issue I'm having is that the result of my calculations are completely off from what I can read on that particular exchange and which also provides an RSI indicator (I assume they analyze their own data, so the same data as I have).
I used the exact same API to translate the Ichimoku indicator into code and this time everything is correct! I believe my RSI calculations might be wrong somehow but I've checked and re-checked many times.
I also have a "literal" version of the code where every step is calculated like an excel sheet. It's pretty stupid in code but it validates the logic of the calculation and the results are the same as the following code.
Here is my code to calculate the RSI :
let period = 14
// Upward Movements and Downward Movements
var upwardMovements : [Double] = []
var downwardMovements : [Double] = []
for idx in 0..<15 {
let diff = items[idx + 1].close - items[idx].close
upwardMovements.append(max(diff, 0))
downwardMovements.append(max(-diff, 0))
}
// Average Upward Movements and Average Downward Movements
let averageUpwardMovement1 = upwardMovements[0..<period].reduce(0, +) / Double(period)
let averageDownwardMovement1 = downwardMovements[0..<period].reduce(0, +) / Double(period)
let averageUpwardMovement2 = (averageUpwardMovement1 * Double(period - 1) + upwardMovements[period]) / Double(period)
let averageDownwardMovement2 = (averageDownwardMovement1 * Double(period - 1) + downwardMovements[period]) / Double(period)
// Relative Strength
let relativeStrength1 = averageUpwardMovement1 / averageDownwardMovement1
let relativeStrength2 = averageUpwardMovement2 / averageDownwardMovement2
// Relative Strength Index
let rSI1 = 100 - (100 / (relativeStrength1 + 1))
let rSI2 = 100 - (100 / (relativeStrength2 + 1))
// Relative Strength Index Average
let relativeStrengthAverage = (rSI1 + rSI2) / 2
BitcoinRelativeStrengthIndex.bitcoinRSI = relativeStrengthAverage
Readings at 3:23pm this afternoon give 73.93 for my algorithm and 18.74 on the exchange. As the markets are crashing right now and I have access to different RSIs on different exchanges, they all display an RSI below 20 so my calculations are off.
Do you guys have any idea?
I am answering this 2 years later, but hopefully it helps someone.
RSI gets more precise the more data points you feed into it. For a default RSI period of 14, you should have at least 200 previous data points. The more, the better!
Let's suppose you have an array of close candle prices for a given market. The following function will return RSI values for each candle. You should always ignore the first data points, since they are not precise enough or the number of candles is not the 14 (or whatever your periods number is).
func computeRSI(on prices: [Double], periods: Int = 14, minimumPoints: Int = 200) -> [Double] {
precondition(periods > 1 && minimumPoints > periods && prices.count >= minimumPoints)
return Array(unsafeUninitializedCapacity: prices.count) { (buffer, count) in
buffer.initialize(repeating: 50)
var (previousPrice, gain, loss) = (prices[0], 0.0, 0.0)
for p in stride(from: 1, through: periods, by: 1) {
let price = prices[p]
let value = price - previousPrice
if value > 0 {
gain += value
} else {
loss -= value
}
previousPrice = price
}
let (numPeriods, numPeriodsMinusOne) = (Double(periods), Double(periods &- 1))
var avg = (gain: gain / numPeriods, loss: loss /numPeriods)
buffer[periods] = (avg.loss > .zero) ? 100 - 100 / (1 + avg.gain/avg.loss) : 100
for p in stride(from: periods &+ 1, to: prices.count, by: 1) {
let price = prices[p]
avg.gain *= numPeriodsMinusOne
avg.loss *= numPeriodsMinusOne
let value = price - previousPrice
if value > 0 {
avg.gain += value
} else {
avg.loss -= value
}
avg.gain /= numPeriods
avg.loss /= numPeriods
if avgLoss > .zero {
buffer[p] = 100 - 100 / (1 + avg.gain/avg.loss)
} else {
buffer[p] = 100
}
previousPrice = price
}
count = prices.count
}
}
Please note that the code is very imperative to reduce the amount of operations/loops and get the maximum compiler optimizations. You might be able to squeeze more performance using the Accelerate framework, though. We are also handling the edge case where you might get all gains or losses in a periods range.
If you want to have a running RSI calculation. Just store the last RSI value and perform the RSI equation for the new price.
I would like to find out the number of hours and minutes between two date time stamp.
if for example
sDateTime = 2016-01-01 01:00
eDateTime = 2016-01-03 02:30
I would like it to output it as 49:30 (49hours and 30minutes)
I am unable to figure a method to work this out.
what I have so far:
Set oMNOF=##class(MNOF.MNOF).%OpenId(Id)
Set zstartDt=oMNOF.sDateTime
Set startDt=$PIECE(zstartDt,",",1)
Set startTime=$PIECE(zstartDt,",",2)
Set zendDt=oMNOF.eDateTime
Set endDt=$PIECE(zendDt,",",1)
Set endTime=$PIECE(zendDt,",",2)
set dateDiff=((endDt - startDt)) //2 days
set timeDiff=(endTime - startTime) //outputs 5400 seconds
set d = (dateDiff * 24 * 60 * 60)
set h = ((timeDiff - d) / 60)
set m = timeDiff - (d) - (h * 60)
Thank you for the help.
Another option:
USER>set mm=$system.SQL.DATEDIFF("mi","2016-01-02 01:00","2016-01-03 02:30")
USER>write "hours=", mm \ 60
hours=25
USER>write "minutes=", mm # 60
minutes=30
Hi thanks to all for the help.
I managed to come up with the below, appreciate if someone can improve on this.
<script language="cache" method="MGetData" arguments="pStartDt:%String,pEndDt:%String,pTimeField:%String" returntype="%Library.String">
set val1="00"
//HOUR: check if length equals 1
if $LENGTH($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/3600))=1{
//add leading zero
set val1 ="0"_$SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/3600)
}
else{
//get without leading zero
set val1 = $SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/3600)
}
//MINUTES: check if length equals 1
if $LENGTH($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/60) - ($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/3600)*60))=1{
//add leading zero
set val2 ="0"_($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/60) - ($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/3600)*60))
}
else{
//get without leading zero
set val2 = ($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/60) - ($SYSTEM.SQL.FLOOR($system.SQL.DATEDIFF("ss",pStartDt,pEndDt)/3600)*60))
}
//insert result data into the time field
Write "document.getElementById('"_pTimeField_"').value='"_val1_":"_val2_"';"
//Write "alert('"_val1_"^"_val2_"');"
QUIT 1
The code below shows two ways of building a spreadsheet :
by using:
str = str + "\(number) ; "
or
str.append("\(number)");
Both are really slow because, I think, they discard both strings and make a third one which is the concatenation of the first two.
Now, If I repeat this operation hundreds of thousands of times to grow a spreadsheet... that makes a lot of allocations.
For instance, the code below takes 11 seconds to execute on my MacBook Pro 2016:
let start = Date()
var str = "";
for i in 0 ..< 86400
{
for j in 0 ..< 80
{
// Use either one, no difference
// str = str + "\(Double(j) * 1.23456789086756 + Double(i)) ; "
str.append("\(Double(j) * 1.23456789086756 + Double(i)) ; ");
}
str.append("\n")
}
let duration = Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate;
print(duration);
How can I solve this issue without having to convert the doubles to string myself ? I have been stuck on this for 3 days... my programming skills are pretty limited, as you can probably see from the code above...
I tried:
var str = NSMutableString(capacity: 86400*80*20);
but the compiler tells me:
Variable 'str' was never mutated; consider changing to 'let' constant
despite the
str.append("\(Double(j) * 1.23456789086756 + Double(i)) ; ");
So apparently, calling append does not mutate the string...
I tried writing it to an array and the limiting factor seems to be the conversion of a double to a string.
The code below takes 13 seconds or so on my air
doing this
arr[i][j] = "1.23456789086756"
drops the execution time to 2 seconds so 11 seconds is taken up in converting Double to String. You might be able to shave off some time by writing your own conversion routine but that seems the limiting factor. I tried using memory streams and that seems even slower.
var start = Date()
var arr = Array(repeating: Array(repeating: "1.23456789086756", count: 80), count: 86400 )
var duration = Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate;
print(duration); //0.007
start = Date()
var a = 1.23456789086756
for i in 0 ..< 86400
{
for j in 0 ..< 80
{
arr[i][j] = "\(a)" // "1.23456789086756" //String(a)
}
}
duration = Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate;
print(duration); //13.46 or 2.3 with the string
I am storing numbers in a MySQL DB as doubles so I can get min, max and sums.
I have a decimal number 1.66777777778 which equals 01:40:04 however I am wanting to be able to convert this decimal in to hour:minutes:seconds in Swift so I can display the value as 01:40:04 however I don't know how.
I have done some searching but most results are calculators without explanation.
I have this function to convert to decimal:
func timeToHour(hour: String, minute:String, second:String) -> Double
{
var hourSource = 0.00
if hour == ""
{
hourSource = 0.00
}
else
{
hourSource = Double(hour)!
}
let minuteSource = Double(minute)!
let secondSource = Double(second)!
let timeDecimal: Double = hourSource + (minuteSource / 60) + (secondSource / 3600)
return timeDecimal
}
but need one to go back the other way.
Thanks
Try:
func hourToString(hour:Double) -> String {
let hours = Int(floor(hour))
let mins = Int(floor(hour * 60) % 60)
let secs = Int(floor(hour * 3600) % 60)
return String(format:"%d:%02d:%02d", hours, mins, secs)
}
Basically break each component out and concatenate them all together.
I am trying to calculate the time difference between 2 date time strings.
I have 2 inputs where the input string is something like this "1:00 PM" and the second one "3:15 PM". I want to know the time difference. So for the above example I want to display 3.15
What I have done:
Converted the time to a 24 hours format. So "1:00 PM" becomes "13:00:00"
Appended the new time to a date like so: new Date("1970-1-1 13:00:00")
Calculated the difference like so:
Code:
var total = Math.round(((new Date("1970-1-1 " + end_time) -
new Date("1970-1-1 " + start_time) ) / 1000 / 3600) , 2 )
But the total is always returning integers and not decimals, so the difference between "1:00 PM" and "3:15 PM" is 2 not 2.15.
I have also tried this (using jQuery, but that is irrelevant):
$('#to_ad,#from_ad').change(function(){
$('#total_ad').val( getDiffTime() );
});
function fixTimeString(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
return sHours + ':' + sMinutes + ':00';
}
function getDiffTime(){
var start_time = fixTimeString($('#from_ad').val());
var end_time = fixTimeString($('#to_ad').val());
var start = new Date("1970-1-1 " + end_time).getTime(),
end = new Date("1970-1-1 " + start_time).getTime();
return parseInt(((start - end) / 1000 / 3600, 10)*100) / 100;
}
But the total_ad input is displaying only integer values.
How can I fix this problem?
Math.round rounds to the nearest integer, multiply and divide instead
var start = new Date("1970-1-1 " + start_time).getTime(),
end = new Date("1970-1-1 " + end_time).getTime();
var total = (parseInt(((start-end) / 1000 / 3600)*100, 10)) / 100;
FIDDLE
When you take the time 15:15:00 and subtract 13:00:00, you're left with 2.15 hours, not 3.15, and this example would return 2.15 even without making sure there is only two decimals, but for other times that might not be the case.
You could also use toFixed(2), but that would leave you with 3.00 and not 3 etc.
This is how I calculate it:
calculateDiff();
function calculateDiff(){
_start = "7:00 AM";
_end = "1:00 PM";
_start_time = parseAMDate(_start);
_end_time = parseAMDate(_end);
if (_end_time < _start_time){
_end_time = parseAMDate(_end,1);
}
var difference= _end_time - _start_time;
var hours = Math.floor(difference / 36e5),
minutes = Math.floor(difference % 36e5 / 60000);
if (parseInt(hours) >= 0 ){
if (minutes == 0){
minutes = "00";
}
alert(hours+":"+minutes);
}
}
function parseAMDate(input, next_day) {
var dateReg = /(\d{1,2}):(\d{2})\s*(AM|PM)/;
var hour, minute, result = dateReg.exec(input);
if (result) {
hour = +result[1];
minute = +result[2];
if (result[3] === 'PM' && hour !== 12) {
hour += 12;
}
}
if (!next_day) {
return new Date(1970, 01, 01, hour, minute).getTime();
}else{
return new Date(1970, 01, 02, hour, minute).getTime();
}
}