Pandas: Product price calculation by carrier - pandas

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?

Related

Conversion ECEF XYZ to LLH (LAT/LONG/HEIGHT) and translation back - not accurate / possible error in IronPython script

I've modeled a 3D earth with gridpoints, as below:
The points are represented in 3D space as XYZ coordinates.
I then convert XYZ to Lat/Long/Height(elevation) based on the script I took from here:
JSFiddle
For some reason I got really strange results when trying to find XYZ of LLH not from my set, so I tried to verify the initial script by converting XYZ to LLH and then the same LLH back to XYZ to see if I get the same coordinate.
Instead, the resulting coordinate is some XYZ on earth, unrelated to the original XYZ position.
XYZ to LLH script:
Source: JSFiddle
def xyzllh(x,y,z):
""" xyz vector to lat,lon,height
output:
llhvec[3] with components
flat geodetic latitude in deg
flon longitude in deg
altkm altitude in km
"""
dtr = math.pi/180.0
rrnrm = [0.0] * 3
llhvec = [0.0] * 3
geodGBL()
esq = EARTH_Esq
rp = math.sqrt( x*x + y*y + z*z )
flatgc = math.asin( z / rp )/dtr
testval= abs(x) + abs(y)
if ( testval < 1.0e-10):
flon = 0.0
else:
flon = math.atan2( y,x )/dtr
if (flon < 0.0 ):
flon = flon + 360.0
p = math.sqrt( x*x + y*y )
# on pole special case
if ( p < 1.0e-10 ):
flat = 90.0
if ( z < 0.0 ):
flat = -90.0
altkm = rp - rearth(flat)
llhvec[0] = flat
llhvec[1] = flon
llhvec[2] = altkm
return llhvec
# first iteration, use flatgc to get altitude
# and alt needed to convert gc to gd lat.
rnow = rearth(flatgc)
altkm = rp - rnow
flat = gc2gd(flatgc,altkm)
rrnrm = radcur(flat)
rn = rrnrm[1]
for x in range(5):
slat = math.sin(dtr*flat)
tangd = ( z + rn*esq*slat ) / p
flatn = math.atan(tangd)/dtr
dlat = flatn - flat
flat = flatn
clat = math.cos( dtr*flat )
rrnrm = radcur(flat)
rn = rrnrm[1]
altkm = (p/clat) - rn
if ( abs(dlat) < 1.0e-12 ):
break
llhvec[0] = flat
llhvec[1] = flon
llhvec[2] = altkm
return llhvec
# globals
EARTH_A = 0
EARTH_B = 0
EARTH_F = 0
EARTH_Ecc = 0
EARTH_Esq = 0
# starting function do_llhxyz()
CallCount = 0
llh = [0.0] * 3
dtr = math.pi/180
CallCount = CallCount + 1
sans = " \n"
llh = xyzllh(x,y,z)
latitude = llh[0]
longitude= llh[1]
hkm = llh[2]
height = 1000.0 * hkm
latitude = fformat(latitude,5)
longitude = fformat(longitude,5)
height = fformat(height,1)
sans = sans +"Latitude,Longitude, Height (ellipsoidal) from ECEF\n"
sans = sans + "\n"
sans = sans +"Latitude : " + str(latitude) + " deg N\n"
sans = sans +"Longitude : " + str(longitude - 180) + " deg E\n"
sans = sans +"Height : " + str(height) + " m\n"
lats = []
longs = []
heights = []
lats.append(str(latitude))
longs.append(str(longitude - 180))
heights.append(str(height))
And this is the LLH to XYZ script:
Source: www.mathworks.com
a = 6378137
t = 8.1819190842622e-2
# (prime vertical radius of curvature)
N = a / math.sqrt(1 - (t*t) * (math.sin(lat)*math.sin(lat)))
x = []
y = []
z = []
# results:
x.append( ((N+height) * math.cos(lat) * math.cos(long))/1000 )
y.append( ((N+height) * math.cos(lat) * math.sin(long))/1000 )
z.append( (((1-t*t) * N + height) * math.sin(lat))/1000 )
Anyone know what I'm doing wrong here?
Thanks!

Tradingview pine editor. Issue with ATR TP/SL coding from entry

I need to code Take profit and Stop loss with Average true range from the past. I have an issue my code is calculating latest ATR and i cannot find a way to lock ATR number from the entry. ATR is calculating after candle close that means while candle is active it doesn't exist. Adding picture where I have marked what I'm looking for and what pine is calculating.
Paint shows what I'm looking for, original pine shows code calculations
//#version=2
strategy("Heiwa",initial_capital=1000,default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.15, overlay=true)
//WADARINDICATOR----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
sensitivity = input(200, title="Sensitivity")
fastLength=input(20, title="FastEMA Length")
slowLength=input(40, title="SlowEMA Length")
channelLength=input(20, title="BB Channel Length")
mult=input(2.0, title="BB Stdev Multiplier")
deadZone=input(20, title="No trade zone threshold")
calc_macd(source, fastLength, slowLength) =>
fastMA = ema(source, fastLength)
slowMA = ema(source, slowLength)
fastMA - slowMA
calc_BBUpper(source, length, mult) =>
basis = sma(source, length)
dev = mult * stdev(source, length)
basis + dev
calc_BBLower(source, length, mult) =>
basis = sma(source, length)
dev = mult * stdev(source, length)
basis - dev
t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength))*sensitivity
t2 = (calc_macd(close[2], fastLength, slowLength) - calc_macd(close[3], fastLength, slowLength))*sensitivity
e1 = (calc_BBUpper(close, channelLength, mult) - calc_BBLower(close, channelLength, mult))
//e2 = (calc_BBUpper(close[1], channelLength, mult) - calc_BBLower(close[1], channelLength, mult))
trendUp = (t1 >= 0) ? t1 : 0
trendDown = (t1 < 0) ? (-1*t1) : 0
Waddardtdis = input(50, minval=1)
//WADARINDICATOR----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//ATR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
atrBandDays = input(15, minval=1, title="Days for ATR", type=integer)
atrBand = atr(atrBandDays)
atrPlus1 = close + atrBand
atrPlus2 = close + atrBand*2
atrPlus3 = close + atrBand*3
atrStop = close - atrBand*2
plot(atrPlus1, color=green)
plot(atrPlus2, color=orange)
plot(atrPlus3, color=red)
plot(atrStop, color=blue)
//ATR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Heikinashi---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
haTicker = heikinashi(tickerid)
haOpen = security(haTicker, period, open)
haClose = security(haTicker, period, close)
//Heikinashi---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
longCondition = haClose > haOpen and haOpen > haClose[1] and trendUp>e1
exitCondition = haClose < haOpen and trendDown>Waddardtdis
strategy.entry("Long", strategy.long, when=longCondition)
strategy.exit("TP1", "Long", qty_percent = 60, limit=atrPlus1)
strategy.exit("TP2", "Long", qty_percent = 20, limit=atrPlus2)
strategy.exit("TP3", "Long", qty_percent = 20, limit=atrPlus3)
strategy.exit("SL", "Long", stop = atrStop)
strategy.close ( "Long", when = exitCondition)
I'd just preserve the atr value at entry, like that:
entryAtr = entryAtr[1]
if (longCondition)
strategy.entry("Long", strategy.long)
entryAtr := atrBand // save the value to use it for exit

Vpython greyscreen crash

I have found many times a solution for my problems from here, but this time I am totally baffled. I don't know what's wrong at my code.
I made a code to create a box with charged particles inside with Vpython. As I launch the program, I get only a grey screen and the program crash. No error message, nothing.
from visual import *
from random import *
def electronizer(num):
list = []
electron_charge = -1.60217662e-19
electron_mass = 9.10938356e-31
for i in range(num):
another_list = []
e = sphere(pos=(random(), random(),random()), radius=2.818e-15,
color=color.cyan)
e.v = vector(random(), random(), random())
another_list.append(e)
another_list.append(e.v)
another_list.append(electron_charge)
another_list.append(electron_mass)
list.append(another_list)
return list
def protonizer(num):
list = []
proton_charge = 1.60217662e-19
proton_mass = 1.6726219e-27
for i in range(num):
another_list = []
p = sphere(pos=(random(), random(),random()), radius=0.8408739e-15, color=color.red)
p.v = vector(random(), random(), random())
another_list.append(p)
another_list.append(p.v)
another_list.append(proton_charge)
another_list.append(proton_mass)
list.append(another_list)
return list
def cross(a, b):
c = vector(a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0])
return c
def positioner(work_list):
k = 8.9875517873681764e3 #Nm2/C2
G = 6.674e-11 # Nm2/kg2
vac_perm = 1.2566370614e-6 # H/m
pi = 3.14159265
dt = 0.1e-3
constant = 1
force = vector(0,0,0)
for i in range(len(work_list)):
for j in range(len(work_list)):
if i != j:
r = work_list[i][0].pos - work_list[j][0].pos
r_mag = mag(r)
r_norm = norm(r)
F = k * ((work_list[i][2] * work_list[j][2]) / (r_mag**2)) * r_norm
force += F
B = constant*(vac_perm / 4*pi) * (cross(work_list[j][2] * work_list[j][1], norm(r)))/r_mag**2
F = cross(work_list[i][2] * work_list[i][1], B)
force += F
F = -(G * work_list[i][3] * work_list[j][3]) / r_mag**2 * r_norm
force += F
acceleration = force / work_list[i][3]
difference_in_velocity = acceleration * dt
work_list[i][1] += difference_in_velocity
difference_in_position = work_list[i][1] * dt
work_list[i][0].pos += difference_in_position
if abs(work_list[i][0].pos[0]) > 2.5e-6:
work_list[i][1][0] = -work_list[i][1][0]
elif abs(work_list[i][0][1]) > 2.5e-6:
work_list[i][1][1] = -work_list[i][1][1]
elif abs(work_list[i][0][2]) > 2.5e-6:
work_list[i][1][2] = -work_list[i][1][2]
return work_list
box = box(pos=(0, 0, 0), length = 5e-6, width = 5e-6, height = 5e-6, opacity = 0.5)
protons_num = raw_input("number of protons: ")
electrons_num = raw_input("number of electrons: ")
list_of_electrons = electronizer(int(electrons_num))
list_of_protons = protonizer(int(protons_num))
work_list = list_of_electrons + list_of_protons
while True:
work_list = positioner(work_list)
You should ask your question on the VPython.org forum where the VPython experts hang out and will be able to answer your question. You should mention which operating system you are using and which version of python you are using. From your code I see that you are using classic VPython. There is a newer version of VPython 7 that just came out but the VPython syntax has changed.

missing value where TRUE/FALSE needed

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?

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)