I've converted this formula (ZLEMA Moving Average)
But I have many issues with "Data(Lag Days Ago)", it seems that it cant go back to find the result. Here's the function but unfortunately it doesn't produce the desired result.
def fzlema(source,period):
zxLag = period / 2 if (period / 2) == np.round(period / 2) else (period - 1) / 2
zxLag = int(zxLag)
zxEMAData = source + (source - source.iloc[zxLag]) # Probably error is in this line
zlema = zxEMAData.ewm(span=period, adjust=False).mean()
zlema = np.round(zlema,2)
return zlema
zlema = fzlema(dataframe['close'], 50)
To be clear, the script runs perfectly but what I got is unmatched as it's been calculated on Tradingview.
I tried used iloc[..] and tail(..) but neither return exact results.
I can use the libraries pandas and numpy.
Any point of view?
SOLVED:
Simply using source.shift(zxLag)
Related
hI i have a code in matlab. Based on my understanding I have translated that code to python. Can someone let me know if it is the right way to translate.
for i = 1:length(Filters)
Filters{i} = gpuArray(2*(single(sign(Filters{i}))-0.5));
NumLearntWeightsEachLayer(i) = size(Filters{i},3)*size(Filters{i},4)*4;
end
NumLearntWeightsEachLayer(end) = size(Filters{end},3)*size(Filters{end},4);
NumLearntWeightsEachLayer
TotalLearntWeights = sum(NumLearntWeightsEachLayer)
Could someone let me know if this could be an equivalent code for the for loop here.
for i in range (1,Filters):
Filters(i) = (2* (Filters(i) - 0.5))
NumLearntWeightsEachLayer(i) = (Filters(i),3).shape * (Filters(i),4).shape *4
I also want to know what could be the right translation for the last part of the code
NumLearntWeightsEachLayer(end) = size(Filters{end},3)*size(Filters{end},4);
It's a good start.. some small fixes -
for i in range (0,len(Filters)):
for j in range(0, len(Filters[i]):
Filters[i][j] = 2*(round(Filters[i][j],1) - 0.5)
NumLearntWeightsEachLayer[i] = len(Filters[i][3])*len(Filters[i][4])*4
For the last line-
NumLearntWeightsEachLayer(end) = size(Filters{end},3)*size(Filters{end},4);
It can be written as -
NumLearntWeightsEachLayer[-1] = len(Filters[-1][3])*len(Filters[-1][4]);
I'm trying to port a code from c++ to python, where at some point a frame is extracted from a .oni recording (OpenNI2), scaled to 8 bit and saved as jpg.
I use OpenCV function convertTo in c++, which is not available in python, so reading the documentation I'm triying to do the same operation manually, but something is wrong.
This is the c++
cv::Mat depthImage8;
double maxVal = 650.0;
double minVal = 520.0;
depthImage.convertTo(depthImage8, CV_8UC1, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
cv::imwrite(dst_folder + "/" + std::to_string(DepthFrameIndex) + "_8bit.jpg", depthImage8);
which produce:
This is the Python version:
depth_scale_factor = 255.0 / (650.0-520.0)
depth_scale_beta_factor = -520.0*255.0/(650.0-520.0)
depth_uint8 = (depth_array*depth_scale_factor+depth_scale_beta_factor).astype('uint8')
which produce:
This code seems to work, but however images generated are different, while the original one (16UC1) are identical (already checked and they match pixel by pixel), so there should be something wrong in the conversion functions.
Thanks to the comments I came up with the solution. As stated by users michelson and Dan Masek Opencv performs saturate_cast operation, while numpy don't. So in order to get the same result, Python version must be:
depth_uint8 = depth_array*depth_scale_factor+depth_scale_beta_factor
depth_uint8[depth_uint8>255] = 255
depth_uint8[depth_uint8<0] = 0
depth_uint8 = depth_uint8.astype('uint8')
Hey so I am just working on some coding homework for my Python class using JES. Our assignment is to take a sound, add some white noise to the background and to add an echo as well. There is a bit more exacts but I believe I am fine with that. There are four different functions that we are making: a main, an echo equation based on a user defined length of time and amount of echos, a white noise generation function, and a function to merge the noises.
Here is what I have so far, haven't started the merging or the main yet.
#put the following line at the top of your file. This will let
#you access the random module functions
import random
#White noise Generation functiton, requires a sound to match sound length
def whiteNoiseGenerator(baseSound) :
noise = makeEmptySound(getLength(baseSound))
index = 0
for index in range(0, getLength(baseSound)) :
sample = random.randint(-500, 500)
setSampleValueAt(noise, index, sample)
return noise
def multipleEchoesGenerator(sound, delay, number) :
endSound = getLength(sound)
newEndSound = endSound +(delay * number)
len = 1 + int(newEndSound/getSamplingRate(sound))
newSound = makeEmptySound(len)
echoAmplitude = 1.0
for echoCount in range (1, number) :
echoAmplitude = echoAmplitude * 0.60
for posns1 in range (0, endSound):
posns2 = posns1 + (delay * echoCount)
values1 = getSampleValueAt(sound, posns1) * echoAmplitude
values2 = getSampleValueAt(newSound, posns2)
setSampleValueAt (newSound, posns2, values1 + values2)
return newSound
I receive this error whenever I try to load it in.
The error was:
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
Please check line 38 of C:\Users\insanity180\Desktop\Work\Winter Sophomore\CS 140\homework3\homework_3.py
That line of code is:
setSampleValueAt (newSound, posns2, values1 + values2)
Anyone have an idea what might be happening here? Any assistance would be great since I am hoping to give myself plenty of time to finish coding this assignment. I have gotten a similar error before and it was usually a syntax error however I don't see any such errors here.
The sound is made before I run this program and I defined delay and number as values 1 and 3 respectively.
Check the arguments to setSampleValueAt; your sample value must be out of bounds (should be within -32768 - 32767). You need to do some kind of output clamping for your algorithm.
Another possibility (which indeed was the error, according to further input) is that your echo will be out of the range of the sample - that is, if your sample was 5 seconds long, and echo was 0.5 seconds long; or the posns1 + delay is beyond the length of the sample; the length of the new sound is not calculated correctly.
I found the following example from another question:
Here
It has some pyparsing code like this:
from pyparsing import *
survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''
number = Word(nums+'.').setParseAction(lambda t: float(t[0]))
separator = Suppress(',')
latitude = Suppress('LA') + number
longitude = Suppress('LN') + number
elevation = Suppress('EL') + number
line = (Suppress('GPS,PN1,')
+ latitude
+ separator
+ longitude
+ separator
+ elevation)
print line.parseString(survey)
It says that the output is:
[52.125133215643, 21.031048525561, 116.898812]
However, I get the following output:
[W:(0123...), W:(0123...), W:(0123...)]
How can I get float outputs instead of these "W:(0123...)" values?
Thanks!
I upgraded my python and pyparsing version and it still did not work correctly. However, the next morning it suddenly worked just fine. I'm not sure why, maybe the restart overnight did something. Either way, it appears to work correctly now.
I'm moving the backend of a site to Django because it was originally coded in PHP and it's the biggest mess on Earth or Mars... anyway.. so I copied the PHP and Python that I've conjured up to copy it below. They both return IDENTICAL values, but for some reason, the Django/Python doesn't return anything from the query.
I'm up for suggestions, I'd consider installing GeoDjango, but I was hoping to get this going without having to do so.
So here's the code:
PHP:
$lat = $myrow['latitude'];
$lon = $myrow['longitude'];
// get the min/max latitudes and longitudes for the radius search
$lat_range = $miles / 69.172;
$lon_range = abs($miles / (cos($lon) * 69.172));
$min_lat = $lat - $lat_range;
$max_lat = $lat + $lat_range;
$min_lon = $lon - $lon_range;
$max_lon = $lon + $lon_range;
$sql = "SELECT * FROM zipcodes WHERE
(latitude >= $min_lat AND latitude <= $max_lat AND
longitude >= $min_lon AND longitude <= $max_lon)";
Python:
distance = float(distance)
orderloc = Zipcodes.objects.get(zip=order.zip)
orderloc.longitude = float(orderloc.longitude)
orderloc.latitude = float(orderloc.latitude)
latrange = distance/69.172
lonrange = math.fabs(distance/(math.cos(orderloc.longitude) * 69.172))
minlat = orderloc.latitude - latrange
maxlat = orderloc.latitude + latrange
minlon = orderloc.longitude - lonrange
maxlon = orderloc.longitude + lonrange
distanceresults = Zipcodes.objects.all().filter(longitude__gte=minlon,
longitude__lte=maxlon,latitude__gte=minlat,latitude__lte=maxlat)
P.S. This is the query that Django returns...
SELECT (a ton of stuff here) FROM `zipcodes` WHERE (`zipcodes`.`longitude` <= -74.489601513 AND `zipcodes`.`longitude` >= -75.957598487 AND `zipcodes`.`latitude` >= 39.8528641705 AND `zipcodes`.`latitude` <= 41.2985358295 )
I noticed that you're converting the latitude and longitude on orderloc to floats. What field type are they on your model in the first place? Django has a FloatField field type, so if you're dealing with floats, you should use that field type on your model. I'm thinking based on this that it might be an issue of comparing the actual true-blue float with something like a CHAR value, and it's not exactly matching.
Alternatively, floats in Python can be a little weird sometimes, returning numbers like 25.00000000001 instead of an even 25 after doing calculations. Since you're dealing with latitude and longitude, which typically have a fixed set of digits, you might also try using DecimalFields. These essentially function like floats, but limit stored data to a defined number of places. Again, just throwing out ideas.