How can I output/print in thinkscript? - thinkscript

Pretty straight forward. I just want to print in thinkscript. If this question indicates that I'm missing a crucial element of thinkscript by asking this, please let me know that as well.

Use something like this: AddLabel(yes, if close > 0 then "whatyouwanttoprint"

If you're asking how to actually print out the code for a script: the best I can find is to copy the code into another editor and print from there.
If you're looking for ways to output for debugging purposes, say, then #Mteam888's answer, AddLabel is one way. Another is AddChartBubble:
#hint: Demonstrates adding a chart bubble at a given bar number and a label showing the last (most recent) bar number.\nNote: bar[0] is the rightmost, or most recent, bar. It is actually n bars from the leftmost side of the chart;\nbar[1] is one bar left of bar[0], and bar[2] is 2 bars left of bar 0.\nThis example also shows no plot is required in this case.
def isLastBar = !IsNaN(close) and IsNaN(close[-1]);
def lastBarNum = if isLastBar then BarNumber() else 0;
AddChartBubble( "time condition"=(BarNumber() == 15), "price location"=high, text="BarNumber" + BarNumber(), color=Color.YELLOW);
AddChartBubble( "time condition"=(BarNumber() == 30), "price location"=high, text="BarNumber" + BarNumber(), color=Color.YELLOW);
AddChartBubble( "time condition"=(BarNumber() == 45), "price location"=high, text="BarNumber" + BarNumber(), color=Color.YELLOW);
AddLabel(visible=isLastBar, text="bar[0] (rightmost): " + lastBarNum, color=Color.GREEN);
AddLabel(visible=isLastBar, text="bar[1]: " + (lastBarNum - 1), color=Color.YELLOW);
AddLabel(visible=isLastBar, text="bar[2]: " + (lastBarNum - 2), color=Color.ORANGE);
#plot Data = close; #plot is not required if only adding labels/chart bubbles

Related

Filter formula for multiple cell references

How can I make it so the formula on E2 reads values entered in any of the search cells and displays it as results, considering I have a button to clear all search boxes and users are instructed to only search one box at a time and to press the button if multiple boxes are filled?
See image
Here's my editable Spreadsheet
Much appreciated.
try:
=IFNA(QUERY(A2:C4; "where A = '"&B6&"'
or B = '"&B7&"'
or C = '"&B8&"'"; 0))
I'd like results to be shown only if the data users look for are in the same row.
=IFNA(QUERY(A2:C4; "where A = '"&B6&"'
and B = '"&B7&"'
and C = '"&B8&"'"; 0))
UPDATE:
=IFNA(QUERY(A2:C4; "where "&TEXTJOIN(" and "; 1;
IF(B6="";;"A = '"&B6&"'");
IF(B7="";;"B = '"&B7&"'");
IF(B8="";;"C = '"&B8&"'"))&""; 0))
You can combine conditions via + and *
=IFNA(
FILTER(A2:C4;(A2:A4=B6)+(B2:B4=B7)+(C2:C4=B8));
"Enter the data for the request"
)

How to add a WHERE function to a complex string

I am trying to only query data that has a number > 0 in Column K within this complex string.
=QUERY('Form Responses 1'!A1:K,"SELECT *" & if(COUNTBLANK('Helper Formulas'!A1:A3)=3,""," WHERE " & TEXTJOIN(" AND ",TRUE,'Helper Formulas'!A1:A3)),1)
I tried...
=QUERY('Form Responses 1'!A1:K,"SELECT * WHERE K > 0" & if(COUNTBLANK('Helper Formulas'!A1:A3)=3,""," WHERE " & TEXTJOIN(" AND ",TRUE,'Helper Formulas'!A1:A3)),1)
But keep getting an error.
Not sure what I need to do.
try:
=QUERY('Form Responses 1'!A1:K,
"where K > 0"&IF(COUNTBLANK('Helper Formulas'!A1:A3)=3,,
" and "&TEXTJOIN(" and ", 1, 'Helper Formulas'!A1:A3)), 1)
The second formula has two WHEREs. Replace the second one with AND, something like:
=QUERY('Form Responses 1'!A1:K,"SELECT * WHERE K > 0" & if(COUNTBLANK('Helper Formulas'!A1:A3)=3,""," AND " & TEXTJOIN(" AND ",TRUE,'Helper Formulas'!A1:A3)),1)
You may need to tweak this if you end up with too many "AND"s.
When troubleshooting this sort of thing it's often helpful to just display the string in the cell (i.e. just the bit inside the query() function). That would have shown up the error quite quickly.

Shiny - dygraphs: Show all error-bar values in legend

I am using dygraphs for R and I opened the following issue on GitHub the other day, however, I have not yet received an answer. Therefore, I am hoping someone in here will be able to answer my question.
I want to know if it is possible to show all the values of the prediction interval in the legend, i.e. , lower, actual, upper, without having them as three separate plain dySeries? I like the look of the shading that the upper/lower bars bring, but I would also like to be able to hover over a point and see all the values for that particular point, not just the middle one. If such a function does not exists, is there an easy workaround, maybe with fillGraph = TRUE or something?
library(dygraphs)
hw <- HoltWinters(ldeaths)
p <- predict(hw, n.ahead = 72, prediction.interval = TRUE)
dygraph(p, main = "Predicted Lung Deaths (UK)") %>%
dySeries(c("lwr", "fit", "upr"), label = "Deaths")
The preceding code is the example from the web page, which is similar to my problem. I simply want to see the lwr and upr values in the legend when hovering.
So I found a workaround for anybody looking for something similar.
library(dygraphs)
hw <- HoltWinters(ldeaths)
p <- predict(hw, n.ahead = 72, prediction.interval = TRUE)
max <- p[,2]
min <- p[,3]
p <- ts.union(p, max, min)
dygraph(p, main = "Predicted Lung Deaths (UK)") %>%
dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Deaths") %>%
dySeries("max", label = "Max", pointSize = 0.01, strokeWidth = 0.001) %>%
dySeries("min", label = "Max", pointSize = 0.01, strokeWidth = 0.001)
Obviously, this can be modified to suit your needs (e.g. color of the points etc.) The main idea in this method is simply to create two new columns containing the same information that is used in the bands, and then to make the lines to these too small to see.

Split row in multiple other rows in Power Bi based on a division of a number

In Power BI Desktop i have a table from an excel file and i want to split a row based on a division between the value of a specific column and a default number.
In more details lets assume tha we have a table like this :
if the default value we want to devide column Amount is 50,then the desirable result would be something like that :
Do you have any idea how can i implement that in Power query editor or with dax?
Thanks
Tested this in Power Query for Excel, but hopefully should work for you in Power BI too. If you create a function like:
divisionToList = (numberToDivide as number, numberToDivideBy as number) as list =>
let
divisionResult = numberToDivide / numberToDivideBy,
isResultValid = (divisionResult >= 0) and (Number.Mod(divisionResult, 1) = 0),
errorIfInvalid = Error.Record("Cannot create a list with " & Text.From(divisionResult) & " items", Number.ToText(numberToDivide) & " / " & Number.ToText(numberToDivideBy) & " = " & Text.From(divisionResult), null),
listOrError = if isResultValid then List.Repeat({divisionResult}, divisionResult) else error errorIfInvalid
in listOrError,
It should divide two numbers and return a list of length d in which each element is d (d is the result of the division). This list can then, in the context of a table, be expanded into new rows.
There is some basic error handling in the function for cases where the division yields a problematic number (since you can't have a list with, for example, 5.1 elements or -1 elements). You can change/remove this handling if necessary.
I think this code below takes me from your first image to your second image -- and hopefully will give you some idea on how to go about achieving this.
let
mockData = Table.FromColumns({{200, 400}, {"A", "B"}}, type table [Amount = number, Description = text]),
defaultValue = 50, // Not sure what logic is required for arriving at this figure, so have simply assigned it.
divisionToList = (numberToDivide as number, numberToDivideBy as number) as list =>
let
divisionResult = numberToDivide / numberToDivideBy,
isResultValid = (divisionResult >= 0) and (Number.Mod(divisionResult, 1) = 0),
errorIfInvalid = Error.Record("Cannot create a list with " & Text.From(divisionResult) & " items", Number.ToText(numberToDivide) & " / " & Number.ToText(numberToDivideBy) & " = " & Text.From(divisionResult), null),
listOrError = if isResultValid then List.Repeat({divisionResult}, divisionResult) else error errorIfInvalid
in listOrError,
invokeFunction = Table.TransformColumns(mockData, {{"Amount", each divisionToList(_, defaultValue), type list}}),
expanded = Table.ExpandListColumn(invokeFunction, "Amount")
in
expanded

difflib.get_close_matches GET SCORE

I am trying to get the score of the best match using difflib.get_close_matches:
import difflib
best_match = difflib.get_close_matches(str,str_list,1)[0]
I know of the option to add 'cutoff' parameter, but couldn't find out how to get the actual score after setting the threshold.
Am I missing something? Is there a better solution to match unicode strings?
I found that difflib.get_close_matches is the simplest way for matching/fuzzy-matching strings. But there are a few other more advanced libraries like fuzzywuzzy as you mentioned in the comments.
But if you want to use difflib, you can use difflib.SequenceMatcher to get the score as follows:
import difflib
my_str = 'apple'
str_list = ['ape' , 'fjsdf', 'aerewtg', 'dgyow', 'paepd']
best_match = difflib.get_close_matches(my_str,str_list,1)[0]
score = difflib.SequenceMatcher(None, my_str, best_match).ratio()
In this example, the best match between 'apple' and the list is 'ape' and the score is 0.75.
You can also loop through the list and compute all the scores to check:
for word in str_list:
print "score for: " + my_str + " vs. " + word + " = " + str(difflib.SequenceMatcher(None, my_str, word).ratio())
For this example, you get the following:
score for: apple vs. ape = 0.75
score for: apple vs. fjsdf = 0.0
score for: apple vs. aerewtg = 0.333333333333
score for: apple vs. dgyow = 0.0
score for: apple vs. paepd = 0.4
Documentation for difflib can be found here: https://docs.python.org/2/library/difflib.html
To answer the question, the usual route would be to obtain the comparative score for a match returned by get_close_matches() individually in this manner:
match_ratio = difflib.SequenceMatcher(None, 'aple', 'apple').ratio()
Here's a way that increases speed in my case by about 10% ...
I'm using get_close_matches() for spellcheck, it runs SequenceMatcher() under the hood but strips the scores returning just a list of matching strings. Normally.
But with a small change in Lib/difflib.py currently around line 736 the return can be a dictionary with scores as values, thus no need to run SequenceMatcher again on each list item to obtain their score ratios. In the examples I've shortened the output float values for clarity (like 0.8888888888888888 to 0.889). Input n=7 says to limit the return items to 7 if there are more than 7, i.e. the highest 7, and that could apply if candidates are many.
Current mere list return
In this example result would normally be like ['apple', 'staple', 'able', 'lapel']
... at the default cutoff of .6 if omitted (as in Ben's answer, no judgement).
The change
in difflib.py is simple (this line to the right shows the original):
return {v: k for (k, v) in result} # hack to return dict with scores instead of list, original was ... [x for score, x in result]
New dictionary return
includes scores like {'apple': 0.889, 'staple': 0.8, 'able': 0.75, 'lapel': 0.667}
>>> to_match = 'aple'
>>> candidates = ['lapel', 'staple', 'zoo', 'able', 'apple', 'appealing']
Increasing minimum score cutoff/threshold from .4 to .8:
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.4)
{'apple': 0.889, 'staple': 0.8, 'able': 0.75, 'lapel': 0.667, 'appealing': 0.461}
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.7)
{'apple': 0.889, 'staple': 0.8, 'able': 0.75}
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.8)
{'apple': 0.889, 'staple': 0.8}