ToS to Pine help conversion - pine-script-v5

Looking for help converting a this section of a ToS script to pine.
Seems like I could use USI:TICK.NY for data?
input len = 50;
input capMultiplier = 5.0;
def isTickChart = if GetAggregationPeriod() <= 5000 then 1 else 0;
def timer = SecondsTillTime(1615);
def deltaT = AbsValue(timer[-1] - timer);
def momentum = if isTickChart then volume / deltaT else 0;
def aveSM = Average(momentum, len );
def sdAve = aveSM + 2 * StDev(momentum, len );
def spikeCap = TotalSum(momentum) / BarNumber() * capMultiplier;
USI:TICK.NY for volume data... no luck

Related

How to find the first value of Bollinger Bands when bar open

Actually, the Bollinger Bands code is:
//#version=4
study(title="AAAA", shorttitle="AAAA", overlay=true)
len = 5
multi = 2
bb5med = sma(close, len)
devBB5 = mult2 * stdev(close, len)
bb5top = bb5med + devBB5
bb5bot = bb5med - devBB5
I would want to find the first value of those 3 lines when the new bar comes, means, when close==open.
Also, I need it to work when I change the len to 20, 50 and/or when I change the multi to 3
Please help me. Thank you.
//#version=5
indicator("BB Open", overlay = true)
len = input.int(20)
mult = input.float(2.000)
basis = (math.sum(close, len - 1)[1] + open) / len
float dev_sum = 0.0
for i = 1 to len - 1
dev_sum += math.pow(basis - close[i], 2)
dev_sum += math.pow(basis - open, 2)
stdev = math.sqrt(dev_sum / len)
up = basis + stdev * mult
dn = basis - stdev * mult
plot(basis, color = color.yellow)
plot(up)
plot(dn)
Function :
f_BBopen(_close, _open, _len, _mult) =>
_basis = (math.sum(_close, _len - 1)[1] + _open) / _len
float _dev_sum = 0.0
for i = 1 to _len - 1
_dev_sum += math.pow(_basis - _close[i], 2)
_dev_sum += math.pow(_basis - _open, 2)
_stdev = math.sqrt(_dev_sum / _len)
_up = _basis + _stdev * _mult
_dn = _basis - _stdev * _mult
[_basis, _up, _dn]
[basis, up, dn] = f_BBopen(close, open, len, mult)

Using zero_grad() after loss.backward(), but still receives RuntimeError: "Trying to backward through the graph a second time..."

Below is my implementation of a2c using PyTorch. Upon learning about backpropagation in PyTorch, I have known to zero_grad() the optimizer after each update iteration. However, there is still a RunTime error on second-time backpropagation.
def torchworker(number, model):
worker_env = gym.make("Taxi-v3").env
max_steps_per_episode = 2000
worker_opt = optim.Adam(lr=5e-4, params=model.parameters())
p_history = []
val_history = []
r_history = []
running_reward = 0
episode_count = 0
under = 0
start = time.time()
for i in range(2):
state = worker_env.reset()
episode_reward = 0
penalties = 0
drop = 0
print("Episode {} begins ({})".format(episode_count, number))
worker_env.render()
criterion = nn.SmoothL1Loss()
time_solve = 0
for _ in range(1, max_steps_per_episode):
#worker_env.render()
state = torch.tensor(state, dtype=torch.long)
action_probs = model.forward(state)[0]
critic_value = model.forward(state)[1]
val_history.append((state, critic_value[0]))
# Choose action
action = np.random.choice(6, p=action_probs.detach().numpy())
p_history.append(torch.log(action_probs[action]))
# Apply chosen action
state, reward, done, _ = worker_env.step(action)
r_history.append(reward)
episode_reward += reward
time_solve += 1
if reward == -10:
penalties += 1
elif reward == 20:
drop += 1
if done:
break
# Update running reward to check condition for solving
running_reward = (running_reward * (episode_count) + episode_reward) / (episode_count + 1)
# Calculate discounted returns
returns = deque(maxlen=3500)
discounted_sum = 0
for r in r_history[::-1]:
discounted_sum = r + gamma * discounted_sum
returns.appendleft(discounted_sum)
# Calculate actor losses and critic losses
loss_actor_value = 0
loss_critic_value = 0
history = zip(p_history, val_history, returns)
for log_prob, value, ret in history:
diff = ret - value[1]
loss_actor_value += -log_prob * diff
ret_tensor = torch.tensor(ret, dtype=torch.float32)
loss_critic_value += criterion(value[1], ret_tensor)
loss = loss_actor_value + 0.1 * loss_critic_value
print(loss)
# Update params
loss.backward()
worker_opt.step()
worker_opt.zero_grad()
# Log details
end = time.time()
episode_count += 1
if episode_count % 1 == 0:
worker_env.render()
if running_reward > -50: # Condition to consider the task solved
under += 1
if under > 5:
print("Solved at episode {} !".format(episode_count))
break
I believe there may be something to do with the architecture of my AC model, so I also include it here for reference.
class ActorCriticNetwork(nn.Module):
def __init__(self, num_inputs, num_hidden, num_actions):
super(ActorCriticNetwork, self).__init__()
self.embed = nn.Embedding(500, 10)
self.fc1 = nn.Linear(10, num_hidden * 2)
self.fc2 = nn.Linear(num_hidden * 2, num_hidden)
self.c = nn.Linear(num_hidden, 1)
self.fc3 = nn.Linear(num_hidden, num_hidden)
self.a = nn.Linear(num_hidden, num_actions)
def forward(self, x):
out = F.relu(self.embed(x))
out = F.relu(self.fc1(out))
out = F.relu(self.fc2(out))
critic = self.c(out)
out = F.relu(self.fc3(out.detach()))
actor = F.softmax(self.a(out), dim=-1)
return actor, critic
Would you please tell me what the mistake here is? Thank you in advance.
SOLVED: I forgot to clear the history of probabilities, action-values and rewards after iterations. It is clear why that would cause the issue, as the older elements would cause propagating through old dcgs.

How to count digits in BigDecimal?

I’m dealing with BigDecimal in Java and I need to make 2 check against BigDecimal fields in my DTO:
Number of digits of full part (before point) < 15
Total number of
digits < 32 including scale (zeros after point)
What is the best way to implement it? I extremely don’t want toBigInteger().toString() and .toString()
I think this will work.
BigDecimal d = new BigDecimal("921229392299229.2922929292920000");
int fractionCount = d.scale();
System.out.println(fractionCount);
int wholeCount = (int) (Math.ceil(Math.log10(d.longValue())));
System.out.println(wholeCount);
I did some testing of the above method vs using indexOf and subtracting lengths of strings. The above seems to be signficantly faster if my testing methodology is reasonable. Here is how I tested it.
Random r = new Random(29);
int nRuns = 1_000_000;
// create a list of 1 million BigDecimals
List<BigDecimal> testData = new ArrayList<>();
for (int j = 0; j < nRuns; j++) {
String wholePart = r.ints(r.nextInt(15) + 1, 0, 10).mapToObj(
String::valueOf).collect(Collectors.joining());
String fractionalPart = r.ints(r.nextInt(31) + 1, 0, 10).mapToObj(
String::valueOf).collect(Collectors.joining());
BigDecimal d = new BigDecimal(wholePart + "." + fractionalPart);
testData.add(d);
}
long start = System.nanoTime();
// Using math
for (BigDecimal d : testData) {
int fractionCount = d.scale();
int wholeCount = (int) (Math.ceil(Math.log10(d.longValue())));
}
long time = System.nanoTime() - start;
System.out.println(time / 1_000_000.);
start = System.nanoTime();
//Using strings
for (BigDecimal d : testData) {
String sd = d.toPlainString();
int n = sd.indexOf(".");
int m = sd.length() - n - 1;
}
time = System.nanoTime() - start;
System.out.println(time / 1_000_000.);
}

How to compare function value with a constant

I'm working with Python Scipy I have the next code:
...
t = np.linspace(0, simtime, points)
def Vbooster90(t):
return np.sin(t * 2 * np.pi*F_booster + 0.5 * np.pi)
def beam(t):
return np.sign(Vrfq(t) - Vrfq(bunchwidth)) * 0.5 + 0.5
def criteria(t):
return np.sign(Vbooster90(t))
def kicker(t):
if criteria(t) > 0:
k(t)=beam(t)
else:
k(t)=0
return k(t)
I have a problem with the last function kicker(t). I want to compare the function criteria(t) with zero at each value of t, and in case if criteria(t) is higher than zero, I want to assign kicker(t) to the value of function beam(t) at the same t value. I'm new to Python and don't know syntax well.
Modify the kicker function like following.
def kicker(t):
k = 0
if criteria(t) > 0:
k = beam(t)
return k
Thanks for answers, instead of defining a function I solved it next way:
kicker = np.empty(points)
i = np.arange(points)
time = np.empty(points)
time[i] = i*simtime/points
for i in range(points):
if criteria(time[i]) > 0:
kicker[i] = beam(time[i])
else:
kicker[i] = 0

Calculate IRR (Internal Rate Return) and NPV programmatically in Objective-C

I am developing a financial app and require IRR (in-built functionality of Excel) calculation and found such great tutorials in C here and such answer in C# here.
I implemented code of the C language above, but it gives a perfect result when IRR is in positive. It is not returning a negative value when it should be. Whereas in Excel =IRR(values,guessrate) returns negative IRR as well for some values.
I have referred to code in above C# link too, and it seems that it follows good procedures and returns errors and also hope that it returns negative IRR too, the same as Excel. But I am not familiar with C#, so I am not able to implement the same code in Objective-C or C.
I am writing C code from the above link which I have implemented for helping you guys.
#define LOW_RATE 0.01
#define HIGH_RATE 0.5
#define MAX_ITERATION 1000
#define PRECISION_REQ 0.00000001
double computeIRR(double cf[], int numOfFlows)
{
int i = 0, j = 0;
double m = 0.0;
double old = 0.00;
double new = 0.00;
double oldguessRate = LOW_RATE;
double newguessRate = LOW_RATE;
double guessRate = LOW_RATE;
double lowGuessRate = LOW_RATE;
double highGuessRate = HIGH_RATE;
double npv = 0.0;
double denom = 0.0;
for (i=0; i<MAX_ITERATION; i++)
{
npv = 0.00;
for (j=0; j<numOfFlows; j++)
{
denom = pow((1 + guessRate),j);
npv = npv + (cf[j]/denom);
}
/* Stop checking once the required precision is achieved */
if ((npv > 0) && (npv < PRECISION_REQ))
break;
if (old == 0)
old = npv;
else
old = new;
new = npv;
if (i > 0)
{
if (old < new)
{
if (old < 0 && new < 0)
highGuessRate = newguessRate;
else
lowGuessRate = newguessRate;
}
else
{
if (old > 0 && new > 0)
lowGuessRate = newguessRate;
else
highGuessRate = newguessRate;
}
}
oldguessRate = guessRate;
guessRate = (lowGuessRate + highGuessRate) / 2;
newguessRate = guessRate;
}
return guessRate;
}
I have attached the result for some value which are different in Excel and the above C language code.
Values: Output of Excel: -33.5%
1 = -18.5, Output of C code: 0.010 or say (1.0%)
2 = -18.5,
3 = -18.5,
4 = -18.5,
5 = -18.5,
6 = 32.0
Guess rate: 0.1
Since low_rate and high_rate are both positive, you're not able to get a negative score. You have to change:
#define LOW_RATE 0.01
to, for example,
#define LOW_RATE -0.5