I'm new to pinescript and I can't figure out what's wrong with my if syntax. Please help
//#version=4
strategy(title="Weighted Moving ATR", shorttitle="WMATR Stra Test", overlay = true)
//Changing inputs based on ticker
if (syminfo.ticker == "AAPL")
LenWATR = 43
MultWATR = 1
else if (syminfo.ticker == "AAL")
LenWATR = 21
MultWATR = 1
I keep getting line 13: Mismatched input 'LenWATR' expecting 'end of line without line continuation'.
The reason you're getting the error is because the indentation is wrong.
You're indenting with 5 whitespaces, but indententations should be a multiple of 4 whitespaces.
You could also write it like this:
//#version=4
strategy(title="Weighted Moving ATR", shorttitle="WMATR Stra Test", overlay = true)
var int LenWATR = na
var int MultWATR = na
//Changing inputs based on ticker
LenWATR := if syminfo.ticker == "AAPL"
43
else if syminfo.ticker == "AAL"
1
else
99 // default value
MultWATR := if syminfo.ticker == "AAL"
1
else if syminfo.ticker == "AAL"
1
else
77 // default value
//Changing inputs based on ticker: short version
LenWATR := syminfo.ticker == "AAPL" ? 43 : syminfo.ticker == "AAL" ? 1 : 99
MultWATR := syminfo.ticker == "AAPL" ? 1 : syminfo.ticker == "AAL" ? 1 : 77
plot(na)
You don't need parenthesis. Also if you are using = in your if statement blocks you are initializing variables in a local scope. If the variables exist elsewhere value assignment should use :=
Related
I am just starting out in C++.
I am writing a console application, to "read in" an .evt file (custom, not to be confused with Event viewer files in Windows) and its contents but now I need to write a method to.
a) Store each block of 'EVENT X' including but also ending at 'END'.
b) Make the contents of each block searchable/selectable.
If the content wasn't so 'wildly' varied, I would be happy to put this into some SQL table or experiment with an array but I don't know a starting point to do this as the number of 'fields' or parameters varies. The maximum number of lines I have seen in a block is around 20, the maximum number of parameters per line I have seen is around 13.
I'm not asking for an explicit answer or the whole code to do it although it is welcome, just a generic sample of code to get started that might be appropriate.
This my function to just load the data as it is.
void event_data_loader()
{
string evt_data;
string response2;
cout << "You have chosen to Create/Load Soma events\n\n";
ifstream named_EVT("C:/evts/1.evt");
while (getline(named_EVT, evt_data))
{
// Output the text from the file
cout << evt_data << "\n"; // Iterate out each line of the EVT file including spaces
//name_EVT.close();*/
}
cout << "Does the output look ok?(Y/N)";
cin >> response2;
if (response2 == "Y")
{
// Vectors? Dynamic array? to re-arrange the data?
}
}
The files themselves have content like this. I know what most of the functions do, less so all of the parameters. For some reason putting this on the page it puts them into a single line.
EVENT 01
A CHECK_HUMAN
A CHECK_POSITION 1 250 90 350 90
E BBS_OPEN 1 0
END
EVENT 02
E SELECT_MSG 336 363 314 337 03 338 12 -1 -1
END
EVENT 03
E RUN_EVENT 761
E RUN_EVENT 04
E RUN_EVENT 05
END
EVENT 761
A EXIST_ITEM 373 1
E SELECT_MSG 857 315 762 316 763 -1 -1 -1 -1
E RETURN
END
EVENT 762
A EXIST_ITEM 373 1
E ROB_ITEM 373 1
E SHOW_MAGIC 6
E CHANGE_HP 1 10000
E CHANGE_MP 1 10000
E MESSAGE_NONE 858
E RETURN
END
EVENT 1862
A ABSENT_EVENT 1582
A EXIST_ITEM 1800 1
A EXIST_ITEM 1801 1
A EXIST_ITEM 1802 1
A EXIST_ITEM 1803 1
A EXIST_ITEM 1804 1
A EXIST_ITEM 1805 1
A EXIST_ITEM 1806 1
A EXIST_ITEM 1807 1
A WEIGHT 365 1854 1 1832 1 -1 1 -1 -1 -1 -1
A CHECK_ITEMSLOT 393 1854 1 1832 1 -1 1 -1 -1 -1 -1
A GENDER 1
E ADD_EVENT 1582
E MESSAGE_NONE 3237
E ROB_ITEM 1800 1
E ROB_ITEM 1801 1
E ROB_ITEM 1802 1
E ROB_ITEM 1803 1
E ROB_ITEM 1804 1
E ROB_ITEM 1805 1
E ROB_ITEM 1806 1
E ROB_ITEM 1807 1
E GIVE_ITEM 1854 1
E GIVE_ITEM 1832 1
E RETURN
END
I would do something like this:
struct Subevent {
std::string selector;
std::string name;
std::vector<int> params;
};
struct Event {
int id;
std::vector<Subevent> subevents;
};
std::vector<Event> load_events(std::istream& input_stream) {
std::vector<Event> out;
Event current_event {}; // current event being built
std::string line;
bool inside_event = false; // are we inside the scope of an event?
while (std::getline(input_stream, line)) {
// strip trailing whitespace
while (isspace(line.back())) {
line.pop_back();
}
// skip empty lines
if (line.size() == 0) {
continue;
}
// read first token (until first space)
std::stringstream ss(line);
std::string first_token;
ss >> first_token;
bool is_new_event_line = first_token == "EVENT";
bool is_end_line = first_token == "END";
if (is_new_event_line) {
// line: EVENT <id>
if (inside_event) {
// error: "not expecting new event"
// choose your own error messaging method
}
int id;
ss >> id; // read <id>
// setup new event
current_event.id = id;
inside_event = true;
}
else if (is_end_line) {
// line: END
if (!inside_event) {
// error: "unexpected END"
}
// record and clear current event
out.push_back(current_event);
inside_event = false;
current_event = Event();
}
else {
// line: <selector> <name> <params...>
// e.g.: A GENDER 1
if (!inside_event) {
// error: "unexpected property entry"
}
// read subevent
Subevent subevent {};
subevent.selector = first_token;
ss >> subevent.name;
// copy over the int params from the line
std::copy(
std::istream_iterator<int>(ss),
std::istream_iterator<int>(),
std::back_inserter(subevent.params)
);
// push back subevent
event.subevents.push_back(subevent);
}
}
return out;
}
I am trying to extract where clause from SQL query.
Multiple conditions in where clause should be in form array. Please help me.
Sample Input String:
select * from table where col1=1 and (col2 between 1 and 10 or col2 between 190 and 200) and col2 is not null
Output Expected:
Array("col1=1", "(col2 between 1 and 10 or col2 between 190 and 200)", "col2 is not null")
Thanks in advance.
EDIT:
My question here is like... I would like to split all the conditions as separate items... let's say my query is like
select * from table where col1=1 and (col2 between 1 and 10 or col2 between 190 and 200) and col2 is not null
The output I'm expecting is like
List("col1=1", "col2 between 1 and 10", "col2 between 190 and 200", "col2 is not null")
The thing is the query may have multiple levels of conditions like
select * from table where col1=1 and (col2 =2 or(col3 between 1 and 10 or col3 is between 190 and 200)) and col4='xyz'
in output each condition should be a separate item
List("col1=1","col2=2", "col3 between 1 and 10", "col3 between 190 and 200", "col4='xyz'")
I wouldn't use Regex for this. Here's an alternative way to extract your conditions based on Catalyst's Logical Plan :
val plan = df.queryExecution.logical
val predicates: Seq[Expression] = plan.children.collect{case f: Filter =>
f.condition.productIterator.flatMap{
case And(l,r) => Seq(l,r)
case o:Predicate => Seq(o)
}
}.toList.flatten
println(predicates)
Output :
List(('col1 = 1), ((('col2 >= 1) && ('col2 <= 10)) || (('col2 >= 190) && ('col2 <= 200))), isnotnull('col2))
Here the predicates are still Expressions and hold information (tree representation).
EDIT :
As asked in comment, here's a String (user friendly I hope) representation of the predicates :)
val plan = df.queryExecution.logical
val predicates: Seq[Expression] = plan.children.collect{case f: Filter =>
f.condition.productIterator.flatMap{
case o:Predicate => Seq(o)
}
}.toList.flatten
def stringifyExpressions(expression: Expression): Seq[String] = {
expression match{
case And(l,r) => (l,r) match {
case (gte: GreaterThanOrEqual,lte: LessThanOrEqual) => Seq(s"""${gte.left.toString} between ${gte.right.toString} and ${lte.right.toString}""")
case (_,_) => Seq(l,r).flatMap(stringifyExpressions)
}
case Or(l,r) => Seq(Seq(l,r).flatMap(stringifyExpressions).mkString("(",") OR (", ")"))
case eq: EqualTo => Seq(s"${eq.left.toString} = ${eq.right.toString}")
case inn: IsNotNull => Seq(s"${inn.child.toString} is not null")
case p: Predicate => Seq(p.toString)
}
}
val stringRepresentation = predicates.flatMap{stringifyExpressions}
println(stringRepresentation)
New Output :
List('col1 = 1, ('col2 between 1 and 10) OR ('col2 between 190 and 200), 'col2 is not null)
You can keep playing with the recursive stringifyExpressions method if you want to customize the output.
EDIT 2 : In response to your own edit :
You can change the Or / EqualTo cases to the following
def stringifyExpressions(expression: Expression): Seq[String] = {
expression match{
case And(l,r) => (l,r) match {
case (gte: GreaterThanOrEqual,lte: LessThanOrEqual) => Seq(s"""${gte.left.toString} between ${gte.right.toString} and ${lte.right.toString}""")
case (_,_) => Seq(l,r).flatMap(stringifyExpressions)
}
case Or(l,r) => Seq(l,r).flatMap(stringifyExpressions)
case EqualTo(l,r) =>
val prettyLeft = if(l.resolved && l.dataType == StringType) s"'${l.toString}'" else l.toString
val prettyRight = if(r.resolved && r.dataType == StringType) s"'${r.toString}'" else r.toString
Seq(s"$prettyLeft=$prettyRight")
case inn: IsNotNull => Seq(s"${inn.child.toString} is not null")
case p: Predicate => Seq(p.toString)
}
}
This gives the 4 elements List :
List('col1=1, 'col2 between 1 and 10, 'col2 between 190 and 200, 'col2 is not null)
For the second example :
select * from table where col1=1 and (col2 =2 or (col3 between 1 and 10 or col3 between 190 and 200)) and col4='xyz'
You'd get this output (List[String] with 5 elements) :
List('col1=1, 'col2=2, 'col3 between 1 and 10, 'col3 between 190 and 200, 'col4='xyz')
Additional note: If you want to print the attribute names without the starting quote, you can handle it by printing this instead of toString :
node.asInstanceOf[UnresolvedAttribute].name
I am trying to compare version numbers that range from 1.0 to 1.10.11, they range anywhere from 1.2 to 1.3.35 and I would like to write an if statement that could push() values between a range of 1.0 - 1.0.99 then 1.2.
ie my code below :)
I keep trying different things but am not sure. I tried changing the numbers to string but I realise that makes no sense. I figure there has got be a simpler way. (I am junior dev btw so any advice would be helpful) Thanks in advance.
function sortVersion() {
let sVw = document.getElementsByClassName('triangle-td-software-version');
for(let vN of sVw) {
let versionNumber = vN.innerText;
if(versionNumber == 1.0 || versionNumber < 1.09.99 ){
v1_0.push(versionNumber)
console.log('V1_0 =', v1_0);
}else if(versionNumber == 1.1.0 || versionNumber <= 1.1.35){
v1_1.push(versionNumber);
console.log('V1_1 =', v1_1);
} else if(versionNumber == 1.2 || versionNumber <= 1.2.2){
v1_2.push(versionNumber);
console.log('V1_2 =', v1_2);
}else if(versionNumber == 1.3 || versionNumber <= 1.3.11){
v1_3.push(versionNumber);
console.log('V1_3 =', v1_3);
}else if(versionNumber == 1.4){
v1_4.push(versionNumber);
console.log('V1_4 =', v1_4);
}
}```
Here is some code in Swift that should work. It should be easy to translate it into JavaScript (not so familiar to me).
Since I did not know better, and just for fun, I wrote it recursively so that the number of subversions is arbitrary.
let versions = ["3.0", "1.0", "1.10.11", "3.1.5", "1.3.35", "1.2"]
// Convert your versions string to an array of versions, each represented by an array of ints. Store the version length
var versionLength = 0
var versionsInts: [[Int]] = []
for version in versions {
let versionComponents = version.components(separatedBy: ".")
if versionComponents.count > versionLength {
versionLength = versionComponents.count
}
var versionInts: [Int] = []
for versionComponent in versionComponents {
versionInts.append(Int(versionComponent)!)
}
versionsInts.append(versionInts)
}
// Make each int array of the same length
for index in 0 ..< versionsInts.count {
var versionInts = versionsInts[index]
for _ in versionInts.count ..< versionLength {
versionInts.append(0)
}
versionsInts[index] = versionInts
}
// Recursive helper function that compares 2 versions using a subindex
func cmp(version1: [Int], version2: [Int], subIndex: Int) -> Bool {
if subIndex == version1.count { return true } // Both versions are the same, take any
if version1[subIndex] < version2[subIndex] { return true } // ascending order
if version1[subIndex] > version2[subIndex] { return false } // descending order
return cmp(version1: version1, version2: version2, subIndex: subIndex+1) // If both versions up to now are the same, check next level
}
let sortedVersions = versionsInts.sorted(by: { (v1: [Int], v2: [Int]) -> Bool in
return cmp(version1: v1, version2: v2, subIndex: 0) // recursively check versions
})
Output:
Printing description of sortedVersions:
▿ 6 elements
▿ 0 : 3 elements
- 0 : 1
- 1 : 0
- 2 : 0
▿ 1 : 3 elements
- 0 : 1
- 1 : 2
- 2 : 0
▿ 2 : 3 elements
- 0 : 1
- 1 : 3
- 2 : 35
▿ 3 : 3 elements
- 0 : 1
- 1 : 10
- 2 : 11
▿ 4 : 3 elements
- 0 : 3
- 1 : 0
- 2 : 0
▿ 5 : 3 elements
- 0 : 3
- 1 : 1
- 2 : 5
Thanks for your help. I ended up using the str.split() method like this. But this pointed me in the right direction. Appreciate everyone.
let v1_0 = [],
v1_1 = [],
v1_2 = [],
v1_3 = [],
v1_4 = [],
v1_5 = [],
v1_6 = [],
v1_7 = [],
v1_8 = [],
v1_9 = [],
v1_10 = [],
v1_11 = [],
v1_12 = [],
what_are_you = [] ;
function sortVersion() {
let sVw = document.getElementsByClassName('triangle-td-software-version');
for(let vN of sVw) {
let versionNumber = vN.innerText;
if(versionNumber.split(".")[1] == 0){
v1_0.push(versionNumber)
}else if(versionNumber.split(".")[1] < 2 ){
v1_1.push(versionNumber);
console.log(v1_1.length)
} else if(versionNumber.split(".")[1] < 3){
v1_2.push(versionNumber);
}else if(versionNumber.split(".")[1] < 4){
v1_3.push(versionNumber);
}else if(versionNumber.split(".")[1] < 5){
v1_4.push(versionNumber);
}else if(versionNumber.split(".")[1] < 6){
v1_5.push(versionNumber);
}else if(versionNumber.split(".")[1] < 7){
v1_6.push(versionNumber);
}else if(versionNumber.split(".")[1] < 8){
v1_7.push(versionNumber);
}else if(versionNumber.split(".")[1] < 9){
v1_8.push(versionNumber);
}else if(versionNumber.split(".")[1] < 10){
v1_9.push(versionNumber);
}else if(versionNumber.split(".")[1] < 11){
v1_10.push(versionNumber);
}else if(versionNumber.split(".")[1] > 10 || versionNumber.split(".")[1] < 0 || versionNumber.split(".")[1] == nil){
what_are_you.push(version);
console.log("Waht Are you!?!?", versionNumber);
}
}
}//end of function
I tried referencing the pandas documentation but still can't figure out how to proceed.
I have this data
In [6]:
df
Out[6]:
strike putCall
0 50 C
1 55 P
2 60 C
3 65 C
4 70 C
5 75 P
6 80 P
7 85 C
8 90 P
9 95 C
10 100 C
11 105 P
12 110 P
13 115 C
14 120 P
15 125 C
16 130 C
17 135 P
18 140 C
19 145 C
20 150 C
and am trying to run this code:
if df['putCall'] == 'P':
if df['strike']<100:
df['optVol'] = 1
else:
df['optVol'] = -999
else:
if df['strike']>df['avg_syn']:
df['optVol'] = 1
else:
df['optVol']= =-999
I get an error message:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
the above code and data are example only to illustrate the problem I ran into
Any assistance would be appreciated.
John
OP add-on
The above question was answered very well by Joris, but I have a slight add-on question.
how would I call a function such as
def Bool2(df):
df['optVol'] = df['strike']/100
return(df)
rather than assign the value of optVol directly to 1 in the line:
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
I would like to have the function Bool2 called and do the assigning. Obviously, the Bool2 function is much more complicated than I have portrayed.
I tried this (shot in the dark), but it did not work:
df.loc[(df['putCall'] == 'P') & (df['strike']<100), 'optVol'] =df.apply(Bool2,axis=1)
thanks again for the help
Typically, when you want to set values using such a if-else logic, boolean indexing is the solution (see docs):
The logic in:
if df['strike']<100:
df['optVol'] = 1
can be expressed with boolean indexing as:
df.loc[df['strike'] < 100, 'optVol'] = 1
For your example, you have multiple nested if-else, and then you can combine conditions using &:
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
The full equivalent of your code above could be like this:
df['optVol'] = -999
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
df.loc[(df['putCall'] != 'P') & (df['strike']>df['avg_syn']), 'optVol'] = 1
The reason you get the error message above is because when doing if df['strike']<100 this comparison works elementwise, so df['strike']<100 gives you a Series of True and False values, while if expects a single True or False value.
This code ask for a message and a value to the user and then it modifies it with the given value. The problem is that I want the ASCII codes to not go over 126 or under 33, I tried to do so in the highlighted part of the code but when the value of the ASCII code gets over 126 the code returns me nothing for some reason.
loop = True
def start():
final_word = []
word_to_crypt = str(raw_input("Type a word: "))
crypt_value = int(raw_input("Choose a number to cript yout message with: "))
ascii_code = 0
n = 0
m = len(word_to_crypt)
m = int(m - 1)
while n <= m:
ascii_code = ord(word_to_crypt[n])
ascii_code += crypt_value
############# highlight #############
if 33 > ascii_code > 126:
ascii_code = (ascii_code%94)+33
############# highlight #############
final_word.append(chr(ascii_code))
n += 1
print 'Your crypted word is: ' + ''.join(final_word)
while loop:
start()
Sorry if it's not formatted well or for any mistakes in my explanation but I'm on my phone and I'm not native
Solved thank you very much this site and this community is helping me a lot!
There is no number that is greater than 126 and less than 33 at the same time. It should be:
if 33 < ascii_code < 126:
Edit:
If you want the reversed case, you will have to do it separately:
if ascii_code < 33 or ascii_code > 126:
Or you can just use the in operator and a list:
if ascii_code not in [33,126]: