missing value where TRUE/FALSE needed - while-loop

I'm working on pairs trading data and following function should give total.profit with value "k".
optimal.k = function (k) {
u = m + k * s
l = m - k * s
profit = 0
profit = 0
total.profit = 0
i = 1
p = 0.001
while ( i <= length(r) ) {
if ( r[i] >= u ) {
buy.unit = 1/East$Close[i]
sell.unit = 1/South$Close[i]
if ( i == length(r) ) {
buy.price = buy.unit * East$Close[i]
sell.price = sell.unit * South$Close[i]
profit = sell.price - buy.price
costs = (sell.price + buy.price) * p
total.profit = total.profit + profit - costs
break
}
while ( r[i] > m ) { #################################### here
i = i + 1
}
buy.price = buy.unit * East$Close[i]
sell.price = sell.unit * South$Close[i]
profit = sell.price - buy.price
costs = (sell.price + buy.price) * p
total.profit = total.profit + profit - costs
}
if ( r[i] <= l ) {
buy.unit = 1/South$Close[i]
sell.unit = 1/East$Close[i]
if ( i == length(r) ) {
buy.price = buy.unit * South$Close[i]
sell.price = sell.unit * East$Close[i]
profit = sell.price - buy.price
costs = (sell.price + buy.price) * p
total.profit = total.profit + profit - costs
break
}
while ( r[i] < m ) {
i = i + 1
}
buy.price = buy.unit * East$Close[i]
sell.price = sell.unit * South$Close[i]
profit = sell.price - buy.price
costs = (sell.price + buy.price) * p
total.profit = total.profit + profit - costs
}
if ( i == length(r) ) stop
i = i + 1
}
print(total.profit)
}
If I run the function, I get this error message.
optimal.k(1)
Error in while (r[i] > m) { : missing value where TRUE/FALSE needed
I don't get it why (r[i] > m) is NA
Does anyone know why it occurs?

Related

Pandas: Product price calculation by carrier

I have a tariff 'tarifas' of the Sudoeste and Termaco carriers
dataframe and a products 'dpx' dataframe
tarifas = {
'Sudoeste': {
'PR': {
'Capital': {'frete_minimo': 47.40,'rate': 0.35,'pedagio_frac': 2.83,'gris': 0.0012,'taxa': 3.36},
'Interior': {'frete_minimo': 48.34,'rate': 0.36,'pedagio_frac': 2.83,'gris': 0.0012,'taxa': 3.36},},}
'Termaco': {
'CE':{
'Capital': {'frete_minimo': 52.69,'Exce_50': 1.06,'pedagio_frac': 2.64,'gris': 0.0011,'taxa': 42.71},
'Interior': {'frete_minimo': 68.76,'Exce_50': 1.39,'pedagio_frac': 2.64,'gris': 0.0011,'taxa': 42.71},},}
I have a function to calculate the delivery freight of a product to a certain region, but it is giving an error.
def calcular_frete(dpx, tarifas):
for index, row in dpx.iterrows():
uf = row['Estado do Destinatário']
regiao = row['regiao']
peso_taxado = row['Peso Taxado']
valor_mercadoria = row['Valor da Mercadoria']
for transportadora, tarifas_transp in tarifas.items():
tarifas = tarifas_transp[uf][regiao]
frete_minimo = tarifas['frete_minimo']
exce_50 = tarifas.get('Exce_50', 0)
pedagio_frac = tarifas['pedagio_frac']
gris = tarifas['gris']
taxa = tarifas['taxa']
rate = tarifas['rate']
if transportadora =='Sudoeste':
if peso_taxado > 50:
valor_frete = frete_minimo + (peso_taxado - 50) * rate + (peso_taxado / 100) * pedagio_frac + (valor_mercadoria * gris) + (valor_mercadoria * taxa)
else:
valor_frete = frete_minimo + (peso_taxado / 100) * pedagio_frac + (valor_mercadoria * gris) + (valor_mercadoria * taxa)
When I call the function to calculate shipping calcular_frete(dpx, tarifas), it results in KeyError: 'SC' in 'tarifas = tarifas_transp[uf][regiao]'
What can I do?

Accurately calculate moon phases

For a new project I like to calculate the moon phases. So far I haven't seen any code that does that. I don't want to rely on online-services for this.
I have tried some functions, but they are not 100% reliable. Functions I have tried:
NSInteger r = iYear % 100;
r %= 19;
if (r>9){ r -= 19;}
r = ((r * 11) % 30) + iMonth + iDay;
if (iMonth<3){r += 2;}
r -= ((iYear<2000) ? 4 : 8.3);
r = floor(r+0.5);
other one:
float n = floor(12.37 * (iYear -1900 + ((1.0 * iMonth - 0.5)/12.0)));
float RAD = 3.14159265/180.0;
float t = n / 1236.85;
float t2 = t * t;
float as = 359.2242 + 29.105356 * n;
float am = 306.0253 + 385.816918 * n + 0.010730 * t2;
float xtra = 0.75933 + 1.53058868 * n + ((1.178e-4) - (1.55e-7) * t) * t2;
xtra = xtra + (0.1734 - 3.93e-4 * t) * sin(RAD * as) - 0.4068 * sin(RAD * am);
float i = (xtra > 0.0 ? floor(xtra) : ceil(xtra - 1.0));
float j1 = [self julday:iYear iMonth:iMonth iDay:iDay];
float jd = (2415020 + 28 * n) + i;
jd = fmodf((j1-jd + 30), 30);
and last one
NSInteger thisJD = [self julday:iYear iMonth:iMonth iDay:iDay];
float degToRad = 3.14159265 / 180;
float K0, T, T2, T3, J0, F0, M0, M1, B1, oldJ = 0.0;
K0 = floor((iYear-1900)*12.3685);
T = (iYear-1899.5) / 100;
T2 = T*T; T3 = T*T*T;
J0 = 2415020 + 29*K0;
F0 = 0.0001178*T2 - 0.000000155*T3 + (0.75933 + 0.53058868*K0) - (0.000837*T + 0.000335*T2);
M0 = 360*[self getFrac:((K0*0.08084821133)) + 359.2242 - 0.0000333*T2 - 0.00000347*T3];
M1 = 360*[self getFrac:((K0*0.07171366128)) + 306.0253 + 0.0107306*T2 + 0.00001236*T3];
B1 = 360*[self getFrac:((K0*0.08519585128)) + 21.2964 - (0.0016528*T2) - (0.00000239*T3)];
NSInteger phase = 0;
NSInteger jday = 0;
while (jday < thisJD) {
float F = F0 + 1.530588*phase;
float M5 = (M0 + phase*29.10535608)*degToRad;
float M6 = (M1 + phase*385.81691806)*degToRad;
float B6 = (B1 + phase*390.67050646)*degToRad;
F -= 0.4068*sin(M6) + (0.1734 - 0.000393*T)*sin(M5);
F += 0.0161*sin(2*M6) + 0.0104*sin(2*B6);
F -= 0.0074*sin(M5 - M6) - 0.0051*sin(M5 + M6);
F += 0.0021*sin(2*M5) + 0.0010*sin(2*B6-M6);
F += 0.5 / 1440;
oldJ=jday;
jday = J0 + 28*phase + floor(F);
phase++;
}
float jd = fmodf((thisJD-oldJ), 30);
All are working more and less, but none is really giving the correct dates of full moon for 2017 and 2018.
Does anyone have a function that will calculate the moon phases correctly - also based on time zone?
EDIT:
I only want the function for the Moonphases. SwiftAA offers a lot more and only produces not needed overhead in the app.

Maya-like camera implementation

I am working on Maya-like camera implementation, and I've done track and dolly functions correctly but I just cannot implement tumble.
I am working in PhiloGL engine (WebGL base), so I would really appreciate some help with code in this engine.
I've looked at how Maya's camera actually work, but I cannot find out. Here is my code so-far
if(mode == "rot")
{
var angleX = diffx / 150;
var angleY = diffy / 150;
//var angleZ = sign * Math.sqrt((diffx * diffx)+(diffy * diffy)) / 150;
e.stop();
//axe Z
//camera.position.x = x * Math.cos(angleX) - y * Math.sin(angleX);
//camera.position.y = x * Math.sin(angleX) + y * Math.cos(angleX);
//axe X
//camera.position.y = y * Math.cos(angleY) - z * Math.sin(angleY);
//camera.position.z = y * Math.sin(angleY) + z * Math.cos(angleY);
//camera.update();
//axe Y
camera.position.z = z * Math.cos(angleX) - x * Math.sin(angleX);
camera.position.x = z * Math.sin(angleX) + x * Math.cos(angleX);
camera.update();
position.x = e.x;
position.y = e.y;
position.z = e.z;
}
This isn't working nor do I know what am I doing wrong.
Any clues?
I use this in inka3d (www.inka3d.com) but it does not depend on inka3d. The output is a 4x4 matrix. Can you make use of that?
// turntable like camera, y is up-vector
// tx, ty and tz are camera target position
// rx, ry and rz are camera rotation angles (rad)
// di is camera distance from target
// fr is an array where the resulting view matrix is written into (16 values, row major)
control.cameraY = function(tx, ty, tz, rx, ry, rz, di, fr)
{
var a = rx * 0.5;
var b = ry * 0.5;
var c = rz * 0.5;
var d = Math.cos(a);
var e = Math.sin(a);
var f = Math.cos(b);
var g = Math.sin(b);
var h = Math.cos(c);
var i = Math.sin(c);
var j = f * e * h + g * d * i;
var k = f * -e * i + g * d * h;
var l = f * d * i - g * e * h;
var m = f * d * h - g * -e * i;
var n = j * j;
var o = k * k;
var p = l * l;
var q = m * m;
var r = j * k;
var s = k * l;
var t = j * l;
var u = m * j;
var v = m * k;
var w = m * l;
var x = q + n - o - p;
var y = (r + w) * 2.0;
var z = (t - v) * 2.0;
var A = (r - w) * 2.0;
var B = q - n + o - p;
var C = (s + u) * 2.0;
var D = (t + v) * 2.0;
var E = (s - u) * 2.0;
var F = q - n - o + p;
var G = di;
var H = -(tx + D * G);
var I = -(ty + E * G);
var J = -(tz + F * G);
fr[0] = x;
fr[1] = A;
fr[2] = D;
fr[3] = 0.0;
fr[4] = y;
fr[5] = B;
fr[6] = E;
fr[7] = 0.0;
fr[8] = z;
fr[9] = C;
fr[10] = F;
fr[11] = 0.0;
fr[12] = x * H + y * I + z * J;
fr[13] = A * H + B * I + C * J;
fr[14] = D * H + E * I + F * J;
fr[15] = 1.0;
};

Stopping at a point

I have a space ship that I want to turn to a destination angle. Currently it works like 90% of the time, but sometimes, it 'jumps' to the destination angle rather than moving smoothly. Here is my code:
a = System.Math.Sin(.destStoppingAngle + System.Math.PI)
b = System.Math.Cos(.destStoppingAngle + System.Math.PI)
c = System.Math.Sin(.msngFacing)
d = System.Math.Cos(.msngFacing)
det = a * d - b * c
If det > 0 Then
.msngFacing = .msngFacing - .ROTATION_RATE * TV.TimeElapsed
If det < 0.1 Then
.msngFacing = .destStoppingAngle
.turning = False
End If
Else
.msngFacing = .msngFacing + .ROTATION_RATE * TV.TimeElapsed
If det > 0.1 Then
.msngFacing = .destStoppingAngle
.turning = False
End If
End If
I would do it like this. First you need a function to lerp an angle (C code, port it yourself):
float lerpangle(float from, float to, float frac) {
float a;
if ( to - from > 180 ) {
to -= 360;
}
if ( to - from < -180 ) {
to += 360;
}
a = from + frac * (to - from);
return a;
}
Then, when starting the rotation you have the duration and stoppingangle as your own parameters. Get the startingangle from your object and startingtime (in something decently precise, milliseconds) and save them. The rotation then goes like this:
current_rotation = lerpangle(startingangle, stoppingangle,
(time.now - startingtime) / duration)

How to compute the p-value in hypothesis testing (linear regression)

Currently I'm working on an awk script to do some statistical analysis on measurement data. I'm using linear regression to get parameter estimates, standard errors etc. and would also like to compute the p-value for a null-hypothesis test (t-test).
This is my script so far, any idea how to compute the p-value?
BEGIN {
ybar = 0.0
xbar = 0.0
n = 0
a0 = 0.0
b0 = 0.0
qtinf0975 = 1.960 # 5% n = inf
}
{ # y_i is in $1, x_i has to be counted
n = n + 1
yi[n] = $1*1.0
xi[n] = n*1.0
}
END {
for ( i = 1; i <= n ; i++ ) {
ybar = ybar + yi[i]
xbar = xbar + xi[i]
}
ybar = ybar/(n*1.0)
xbar = xbar/(n*1.0)
bhat = 0.0
ssqx = 0.0
for ( i = 1; i <= n; i++ ) {
bhat = bhat + (yi[i] - ybar)*(xi[i] - xbar)
ssqx = ssqx + (xi[i] - xbar)*(xi[i] - xbar)
}
bhat = bhat/ssqx
ahat = ybar - bhat*xbar
print "n: ", n
print "alpha-hat: ", ahat
print "beta-hat: ", bhat
sigmahat2 = 0.0
for ( i = 1; i <= n; i++ ) {
ri[i] = yi[i] - (ahat + bhat*xi[i])
sigmahat2 = sigmahat2 + ri[i]*ri[i]
}
sigmahat2 = sigmahat2 / ( n*1.0 - 2.0 )
print "sigma-hat square: ", sigmahat2
seb = sqrt(sigmahat2/ssqx)
print "se(b): ", seb
sigmahat = sqrt((seb*seb)*ssqx)
print "sigma-hat: ", sigma
sea = sqrt(sigmahat*sigmahat * ( 1 /(n*1.0) + xbar*xbar/ssqx))
print "se(a): ", sea
# Tests
print "q(inf)(97.5%): ", qtinf0975
Tb = (bhat - b0) / seb
if ( qtinf0975 > Tb )
print "T(b) plausible: ", Tb, " < ", qtinf0975
else
print "T(b) NOT plausible: ", Tb, " > ", qtinf0975
print "confidence(b): [", bhat - seb * qtinf0975,", ", bhat + seb * qtinf0975 ,"]"
Ta = (ahat - a0) / sea
if ( qtinf0975 > Ta )
print "T(a) plausible: ", Ta, " < ", qtinf0975
else
print "T(a) NOT plausible: ", Ta, " > ", qtinf0975
print "confidence(a): [", ahat - seb * qtinf0975,", ", ahat + seb * qtinf0975 ,"]"
}
You're probably trying to do a paired t-test under the assumption of variance equality. I suggest you have a look at the corresponding entry in the excellent MathWorld website.
OK, I've found a javascript implementation and ported it to awk this are the functions used to compute the p-value:
function statcom ( mq, mi, mj, mb )
{
zz = 1
mz = zz
mk = mi
while ( mk <= mj ) {
zz = zz * mq * mk / ( mk - mb)
mz = mz + zz
mk = mk + 2
}
return mz
}
function studpval ( mt , mn )
{
PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679 # thank you wikipedia
if ( mt < 0 )
mt = -mt
mw = mt / sqrt(mn)
th = atan2(mw, 1)
if ( mn == 1 )
return 1.0 - th / (PI/2.0)
sth = sin(th)
cth = cos(th)
if ( mn % 2 == 1 )
return 1.0 - (th+sth*cth*statcom(cth*cth, 2, mn-3, -1))/(PI/2.0)
else
return 1.0 - sth * statcom(cth*cth, 1, mn-3, -1)
}
I've integrated them like this:
pvalb = studpval(Tb, n)
if ( pvalb > 0.05 )
print "p-value(b) plausible: ", pvalb, " > 0.05"
else
print "p-value(b) NOT plausible: ", pvalb, " < 0.05"
pvala = studpval(Ta, n)
if ( pvala > 0.05 )
print "p-value(a) plausible: ", pvala, " > 0.05"
else
print "p-value(a) NOT plausible: ", pvala, " < 0.05"