combining 3 indicators into a strategy - combinations

I want to combine 3 indicators (MACD, EMA, and VOLUME) to build a strategy where to get notified (overlay=true, with character) if the candle is over 7 days EMA and the VOLUME is higher than the previous 4 days and the MACD is in a positive direction.
strategy('MACD')
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
ema7 = ema(close, 7)
buy = close > ema7
vol = volume
vol1 = volume[1]
vol2 = volume[2]
vol3 = volume[3]
buycon = buy and macdLine >= signalLine and vol > vol1 and vol > vol2 and vol > vol3
stopcon = close < ema7
start = timestamp(2019,1,1,0,0)
if time >= start
strategy.entry("buy", strategy.long, 1000, when = buycon)
strategy.close("buy", when = stopcon)
Please help

Related

How to calculate the percentage of 5 stars, 4 stars rating for an object

I have this rating for my review django model.
5 star 4 star 3 star 2 star 1 star
What I want to do is get the percentage of each component based on the rating.
Something like this:
# get 5 average rating
five_avg_rating = qs.filter(rating=5).aggregate(Avg('rating'))['rating__avg']
five_avg_rating = (five_avg_rating / 5) * 100 if five_avg_rating != None else 0.0
# get 4 average rating
four_avg_rating = qs.filter(rating=4).aggregate(Avg('rating'))['rating__avg']
four_avg_rating = (four_avg_rating / 5) * 100 if four_avg_rating != None else 0.0
....
# get 1 average rating
one_avg_rating = qs.filter(rating=1).aggregate(Avg('rating'))['rating__avg']
one_avg_rating = (one_avg_rating / 5) * 100 if one_avg_rating != None else 0.0
The sum up percentages should = 100%. So if the math is correct, add all the rating percentages should = 100%
Here is an image of what I get now, which is not what I really want:
enter image description here
How can I implement this better?
Doing the below seems to give me what I want! unless there is some better Django way of going about it.
# get 5 average rating
five_avg_rating = qs.filter(rating=5).aggregate(Avg('rating'))['rating__avg']
five_avg_rating = ((five_avg_rating * qs.filter(rating=5).count() / qs.count()) * 100) / 5 if five_avg_rating != None else 0.0

Computing gradients for outputs taken from intermediate layers and updating weights using optimizer

I am trying to implement below architecture and not sure in applying gradient tape properly.
In the above architecture we can see, outputs taken from multiple layers in the blue boxes. Each blue box is termed as loss branch in the paper which contains two losses namely cross entropy and l2 loss. I wrote architecture in tensorflow 2 and using gradient tape for custom training purpose. One thing I am not sure is how should I update the losses using gradient tape.
I have two queries,
How am I supposed to use gradient tape for multiple losses in this scenario. I am interested in seeing code!
For instance, consider the 3rd blue box(3rd loss branch) in the above image, where we will take inputs from conv 13 layer and get two outputs, one for classification and other for regression.
So after computing the losses how I am supposed to update the weights, should I update all the layers above(from conv 1 to conv 13) or should I only update the layers weights which fetched me conv 13 (conv 11, 12 and 13).
I am also attaching a link where I posted a question yesterday in detail.
Below is the snippet which I have tried for gradient descent. Please correct me if I am wrong.
images = batch.data[0]
images = (images - 127.5) / 127.5
targets = batch.label
with tensorflow.GradientTape() as tape:
outputs = self.net(images)
loss = self.loss_criterion(outputs, targets)
self.scheduler(i, self.optimizer)
grads = tape.gradient(loss, self.net.trainable_variables)
self.optimizer.apply_gradients(zip(grads, self.net.trainable_variables))
Below is the code for custom loss function which is used as loss_criterion above.
losses = []
for i in range(self.num_output_scales):
pred_score = outputs[i * 2]
pred_bbox = outputs[i * 2 + 1]
gt_mask = targets[i * 2]
gt_label = targets[i * 2 + 1]
pred_score_softmax = tensorflow.nn.softmax(pred_score, axis=1)
loss_mask = tensorflow.ones(pred_score_softmax.shape, tensorflow.float32)
if self.hnm_ratio > 0:
pos_flag = (gt_label[:, 0, :, :] > 0.5)
pos_num = tensorflow.math.reduce_sum(tensorflow.cast(pos_flag, dtype=tensorflow.float32))
if pos_num > 0:
neg_flag = (gt_label[:, 1, :, :] > 0.5)
neg_num = tensorflow.math.reduce_sum(tensorflow.cast(neg_flag, dtype=tensorflow.float32))
neg_num_selected = min(int(self.hnm_ratio * pos_num), int(neg_num))
neg_prob = tensorflow.where(neg_flag, pred_score_softmax[:, 1, :, :], \
tensorflow.zeros_like(pred_score_softmax[:, 1, :, :]))
neg_prob_sort = tensorflow.sort(tensorflow.reshape(neg_prob, shape=(1, -1)), direction='ASCENDING')
prob_threshold = neg_prob_sort[0][int(neg_num_selected)]
neg_grad_flag = (neg_prob <= prob_threshold)
loss_mask = tensorflow.concat([tensorflow.expand_dims(pos_flag, axis=1),
tensorflow.expand_dims(neg_grad_flag, axis=1)], axis=1)
else:
neg_choice_ratio = 0.1
neg_num_selected = int(tensorflow.cast(tensorflow.size(pred_score_softmax[:, 1, :, :]), dtype=tensorflow.float32) * 0.1)
neg_prob = pred_score_softmax[:, 1, :, :]
neg_prob_sort = tensorflow.sort(tensorflow.reshape(neg_prob, shape=(1, -1)), direction='ASCENDING')
prob_threshold = neg_prob_sort[0][int(neg_num_selected)]
neg_grad_flag = (neg_prob <= prob_threshold)
loss_mask = tensorflow.concat([tensorflow.expand_dims(pos_flag, axis=1),
tensorflow.expand_dims(neg_grad_flag, axis=1)], axis=1)
pred_score_softmax_masked = tensorflow.where(loss_mask, pred_score_softmax,
tensorflow.zeros_like(pred_score_softmax, dtype=tensorflow.float32))
pred_score_log = tensorflow.math.log(pred_score_softmax_masked)
score_cross_entropy = - tensorflow.where(loss_mask, gt_label[:, :2, :, :],
tensorflow.zeros_like(gt_label[:, :2, :, :], dtype=tensorflow.float32)) * pred_score_log
loss_score = tensorflow.math.reduce_sum(score_cross_entropy) /
tensorflow.cast(tensorflow.size(score_cross_entropy), tensorflow.float32)
mask_bbox = gt_mask[:, 2:6, :, :]
predict_bbox = pred_bbox * mask_bbox
label_bbox = gt_label[:, 2:6, :, :] * mask_bbox
# l2 loss of boxes
# loss_bbox = tensorflow.math.reduce_sum(tensorflow.nn.l2_loss((label_bbox - predict_bbox)) ** 2) / 2
loss_bbox = mse(label_bbox, predict_bbox) / tensorflow.math.reduce_sum(mask_bbox)
# Adding only losses relevant to a branch and sending them for back prop
losses.append(loss_score + loss_bbox)
# losses.append(loss_bbox)
# Adding all losses and sending to back prop Approach 1
# loss_cls += loss_score
# loss_reg += loss_bbox
# loss_branch.append(loss_score)
# loss_branch.append(loss_bbox)
# loss = loss_cls + loss_reg
return losses
I am not getting any error but my losses aren't minimizing. Here is the log for my training.
Someone please help me in fixing this.

How to improve my python code to speed it up?

Below is my current code:
import pandas as pd
import math
import csv
fund = 10000
print("investment",fund)
pval = 0
oldportfolio = []
dts = ["06 Feb 2017", "07 Feb 2017", "08 Feb 2017", "09 Feb 2017", "10 Feb 2017", "13 Feb 2017", "14 Feb 2017", "15 Feb 2017", "16 Feb 2017", "17 Feb 2017",
"20 Feb 2017", "21 Feb 2017", "22 Feb 2017", "23 Feb 2017", "27 Feb 2017"]
for dt in dts:
files = ["stocklistcustom.csv"]
for file in files:
df = pd.read_csv(file, header=None)
i = 0
filecount = len(df)
result = []
while i < filecount:
# while i < 10:
name = df[0][i]
link = df[1][i]
mcsym = df[2][i]
i = i + 1
filepath = "data/nse/his/" + mcsym + ".csv"
try:
sp = pd.read_csv(filepath, header=None)
endrow = sp[sp[0] == dt].index[0] + 1
parray = []
tarray = []
starray = []
intdate = []
p1 = 0
p2 = 0
p3 = 0
p4 = 0
j = 0
mavg15 = ''
mavg60 = ''
olddiff = 0
days = 2
strtrow = endrow - days - 60
for k in range (strtrow, endrow):
date = sp[0][k]
price = float(sp[4][k])
k = k + 1
parray.append(price)
j = j + 1
strtavg = j - 15
mavg15 = sum(parray[strtavg:j]) / 15
strtavg = j - 60
mavg60 = sum(parray[strtavg:j]) / 60
# buy criteria
if j > 59:
diff = mavg60 - mavg15
if diff < 0 and olddiff > 0:
trigger = 1
intdate.append(date)
else:
trigger = 0
tarray.append(trigger)
olddiff = diff
# sell criteria
if j == (days + 60):
pricep = (price - p1) * 100 / p1
p1p = (p1 - p2) * 100 / p2
p2p = (p2 - p3) * 100 / p3
p3p = (p3 - p4) * 100 / p4
if pricep < -5 or pricep > 8:
sell = 1
if price < p1 and p1 < p2 and p2 < p3:
sell = 1
else:
sell = 0
p4 = p3
p3 = p2
p2 = p1
p1 = price
if sum(tarray) > 0:
result.append([name,mcsym,"buy",price])
if sell > 0:
result.append([name,mcsym,"sell",price])
except:
# print(name,"not found")
pass
# print(result)
output = "output/triggers/"+dt+"trigger.csv"
with open(output, "wb") as f:
writer = csv.writer(f)
writer.writerows(result)
print(output,"exported")
The above code create an array named result and exports various csv files with calls...
The code below now process the data in result array to compute portfolio value
# Code for calculating investment
portfolio = []
for row in result:
if row[2] == "sell" and len(oldportfolio) > 0:
pindex = 0
for buys in oldportfolio:
bindex = 0
for stock in buys:
if row[0] == stock[0]:
sellqty = stock[2]
sellp = row[3]
sellval = sellqty * sellp
purchasep = stock[1]
sellcost = purchasep * sellqty
print(dt,"selling",row[0],row[1],sellp,sellqty,sellval)
# print(oldportfolio)
del oldportfolio[pindex][bindex]
# print(oldportfolio)
fund = fund + sellval
pval = pval - sellcost
bindex = bindex + 1
pindex = pindex + 1
# print("op", oldportfolio)
# print(dt,"fund after selling",fund)
buycount = sum(1 for row in result if row[2]==("buy"))
if buycount > 0:
maxinvest = fund / buycount
for row in result:
if row[2] == "buy":
name = row[0]
price = row[3]
qty = math.floor(maxinvest / price)
if qty > 0:
val = qty * price
print(dt,"buying",name,row[1],price,qty,val)
portfolio.append([name,price,qty,val])
fund = fund - val
# print("portfolio",portfolio)
pval = pval + sum(row[3] for row in portfolio)
print(dt,"cash",fund,"portfolio value",pval,"total",fund+pval)
oldportfolio.append(portfolio)
print(oldportfolio)
It gives me the value of portfolio for each day after trading based on certain rules. But its execution time is too much. How to reduce its execution time?
Also, I need to change pval as it is calculated incorrectly in current code. It must be calculated based on that particular day's prices.
Your code has multiple nested loops which probably why it is so slow.
But your biggest problem isn't speed, it's readability. It is really hard to reason about your code, consider refactoring.
I'm sure you'll find some bottlenecks and be able to improve your code while refactoring.

Invalid synthx error on line 9

I'm not sure what I did wrong but it's returning invalid syntax on line 9, if anyone can help thank you.
hrs = raw_input("Enter Hours:")
rate = raw_input ("Enter Rates:")
hrs = float(hrs)
rate = float(rate)
def computepay(hrs,rate):
if hrs > 40:
pay = (hrs * rate) + (rate * 1.5) + (hrs- 40)
else:
pay = hrs * rate
return pay
p = computepay(10,20)
print "Pay", p

Python update the plot limits and multiple lines in the plot

I have some problems the first one is that I can't update the plot limits of the y axis and the second is that I want to see 6 lines from each sensor, as you can see in the picture I see only one if I make some changes I see all the sensors variations in one line
here is the code where I create the plot and a picture of this:
http://i.imgur.com/ogFoMDJ.png?1
# Flag variables
self.isLogging = False
# Create data buffers
self.N = 70
self.n = range(self.N)
self.M = 6 # just one lead - i.e. 1 number per sample
self.x = 0 * numpy.ones(self.N, numpy.int)
# Data logging file
self.f = 0
# Create plot area and axes
self.x_max = 500
self.x_min = 330
self.fig = Figure(facecolor='#e4e4e4')
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
self.canvas.SetPosition((330,50))
self.canvas.SetSize((550,280))
self.ax = self.fig.add_axes([0.08,0.1,0.86,0.8])
self.ax.autoscale(False)
self.ax.set_xlim(0, self.N - 1)
self.ax.set_ylim(self.x_min, self.x_max)
self.ax.plot(self.n,self.x)
# Filter taps
self.taps = [0, 0, 0]
# Create timer to read incoming data and scroll plot
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.GetSample, self.timer)
And here is where I grab the data and I try to update the limits of the plot
if len(sample_string) != 6:
sample_string = sample_string[0:-1]
self.taps[1:3] = self.taps[0:2]
self.taps[0] = int(array[1])
#value = 0.5 * self.taps[0] + 0.5 * self.taps[2]
value = self.taps[0]
self.x[0:self.N-1] = self.x[1:]
self.x[self.N-1] = value
# print sample to data logging file
if self.f != 0:
self.f.write(str(value))
self.f.write("\n")
# update plot limits
maxval = max(self.x[:])
minval = min(self.x[:])
self.x_max += ((maxval + 10) - self.x_max) / 100.0
self.x_min -= (self.x_min - (minval - 10)) / 100.0
# Update plot
self.ax.cla()
self.ax.autoscale(False)
self.ax.set_xlim(0, self.N - 1)
self.ax.set_ylim(self.x_min, self.x_max)
self.ax.plot(self.n, self.x)
self.canvas.draw()
if b7 == True:
self.textctrl0.Clear()
self.textctrl0.AppendText(array[1])
self.textctrl1.Clear()
self.textctrl1.AppendText(array[2])
self.textctrl2.Clear()
self.textctrl2.AppendText(array[3])
self.textctrl3.Clear()
self.textctrl3.AppendText(array[4])
self.textctrl4.Clear()
self.textctrl4.AppendText(array[5])
self.textctrl5.Clear()
self.textctrl5.AppendText(array[6])
b7=False
p.s I removed the faulty code where I tried to add the other sensors,here is only the working code for the one sensor plot..