How to set proper back test range - back-testing

I do not know how to code and I am trying to learn Pinescript but it really makes no sense to me so i googled how to set a backtest range and used some code someone else wrote but it doesn't seem to be actually testing the area i would like, it tests the entirety of the chart. I'd like to test from 1/1/2018 to present. I'm trying to do this for multiple strategies so I can better tailor them to the current market. here is wat I have for one of them and if you are willing to help with the others I would very much appreciate it!!! feel free to DM me.
//#version=5
strategy("Bollinger Bands BACKTEST", overlay=true)
source = close
length = input.int(20, minval=1)
mult = input.float(2.0, minval=0.001, maxval=50)
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev
buyEntry = ta.crossover(source, lower)
sellEntry = ta.crossunder(source, upper)
if (ta.crossover(source, lower))
strategy.entry("BBandLE", strategy.long, stop=lower, oca_name="BollingerBands", oca_type=strategy.oca.cancel, comment="BBandLE")
else
strategy.cancel(id="BBandLE")
if (ta.crossunder(source, upper))
strategy.entry("BBandSE", strategy.short, stop=upper, oca_name="BollingerBands", oca_type=strategy.oca.cancel, comment="BBandSE")
else
strategy.cancel(id="BBandSE")
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
// === INPUT BACKTEST RANGE ===
fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromYear = input.int(defval = 2018, title = "From Year", minval = 1970)

Related

Use rblpapi::getTicks() to obtain the Mid Price at a point in time

the question seems pretty easy, but I just did not find a solution yet.
I want to obtain mid prices for a certain timespan. Obviously I can calculate the mid price from bid and ask prices myself. But I wondered, whether it could be done via getTicks directly. I tried eventType = 'MID' and eventType = 'PX_MID', but both don't seem to be supported:
con <- Rblpapi::blpConnect()
Ticker <- 'AAPL US Equity'
Time <- as.POSIXct('2022-02-02 14:22:50 CET')
df <- Rblpapi::getTicks(security = Ticker,
eventType = 'MID',
startTime = Time - 5 * 60,
endTime = Time + 5 * 60)
Error in getTicks_Impl(con, security, eventType, startUTC, endUTC, setCondCodes = returnAs %in% :
Constant with value 'MID' does not exist.
The same code using eventType = 'BID' or eventType = 'ASK' or eventType = 'TRADE' works fine.
I was already looking for a list of all supported eventTypes, but I did not find anything in the documentation. Does such a list exist?
And is there a simple solution to this problem? Or is it possible, that Bloomberg does not support MID prices with Tick Data?
Thanks a lot!

Implementing Binomial Hypothesis Testing significance tests in Power BI (DAX)

This is partly a theory question, and partly an implementation question. My stats is a little rusty...
I am developing a report that is attempting to determine if the difference in occurances between a reference group and a selected group are statistically significant.
So, for example, if something occurs in X of n tests for one group, is it statistically significant than if it 'normally' occurs at a rate of Y of m tests for a different (control) group.
So, my H0 is that the rate is Y of m, per the control group
h1 is that it is not the same as the control group. (ideally, I'd like to use a 1-tailed test, depending if the observed occurrence is greater or less than the control, but my current implementation is 2 tailed)
I'd be comfortable with a CI of 80%.
I've got (slightly pseudocode here):
Zscore =
VAR pControl = DIVIDE(COUNT([Control occurrences]), COUNT([Control Tests])) RETURN
VAR pTest = DIVIDE(COUNT([Test occurrences]), COUNT([Test Tests])) RETURN
VAR controlStandardError =
SQRT(
DIVIDE(
(pControl * (1-pControl)
, COUNT([Control Tests])
)
) RETURN
VAR testStandardError =
SQRT(
DIVIDE(
(pTest* (1-pTest)
, COUNT([Test Tests])
)
) RETURN
DIVIDE(
(pTest - pControl)
, SQRT(POWER(testStandardError, 2) + POWER(controlStandardError, 2)
)
I'm then calculating:
p-Value =
VAR pControl = DIVIDE(COUNT([Control occurrences]), COUNT([Control Tests])) RETURN
IF(pControl > 0,
1 - ABS(NORM.DIST(Zscore, 0, 1, TRUE)
)
I am then displaying in a table each of my non-null hypotheses and filtering the table such that p-Value is less than 0.1. (2-tailed 80%)
am I on the right track here? Or have I completely bungled the theory on this one?
Theory and example tables - Right-tailed (μ > μ₀)
DAX
ControlGroup
XControl = COUNTROWS(FILTER(ControlGroup,ControlGroup[Outcome]=1))
NControl = COUNTROWS(ControlGroup)
pControl = DIVIDE([XControl],[NControl])
TreatmentGroup
XTreatment = COUNTROWS(FILTER(TreatmentGroup,TreatmentGroup[Outcome]=1))
NTreatment = COUNTROWS(TreatmentGroup)
pTreatment = DIVIDE([XTreatment],[NTreatment])
Test Parameters
PooledProportion =
DIVIDE(
[XTreatment]+[XControl],
[NTreatment]+[NControl]
)
ZCritivalValue = NORM.S.INV(0.90)
ZValue = DIVIDE(
[pTreatment]-[pControl],
SQRT(
[PooledProportion]*(1-[PooledProportion])*((1/[NTreatment])+(1/[NControl]))
)
)
Visualization (example)

Calculating results pro rata over several months with PowerQuery

I am currently stuck on below issue:
I have two tables that I have to work with, one contains financial information for vessels and the other contains arrival and departure time for vessels. I get my data combining multiple excel sheets from different folders:
financialTable
voyageTimeTable
I have to calculate the result for above voyage, and apportion the result over June, July and August for both estimated and updated.
Time in June : 4 hours (20/06/2020 20:00 - 23:59) + 10 days (21/06/2020 00:00 - 30/06/2020 23:59) = 10.1666
Time in July : 31 full days
Time in August: 1 day + 14 hours (02/08/2020 00:00 - 14:00) = 1.5833
Total voyage duration = 10.1666 + 31 + 1.5833 = 42.7499
The result for the "updated" financialItem would be the following:
Result June : 100*(10.1666/42.7499) = 23.7816
Result July : 100*(31/42.7499) = 72.5148
Result August : 100*(1.5833/42.7499) = 3.7036
sum = 100
and then for "estimated" it would be twice of everything above.
This is the format I ideally would like to get:
prorataResultTable
I have to do this for multiple vessels, with multiple timespans and several voyage numbers.
Eagerly awaiting responses, if any. Many thanks in advance.
Brds,
Not sure if you're still looking for an answer, but code below gives me your expected output:
let
financialTable = Table.FromRows({{"A", 1, "profit/loss", 200, 100}}, type table [vesselName = text, vesselNumber = Int64.Type, financialItem = text, estimated = number, updated = number]),
voyageTimeTable = Table.FromRows({{"A", 1, #datetime(2020, 6, 20, 20, 0, 0), #datetime(2020, 8, 2, 14, 0, 0)}}, type table [vesselName = text, vesselNumber = Int64.Type, voyageStartDatetime = datetime, voyageEndDatetime = datetime]),
joined =
let
joined = Table.NestedJoin(financialTable, {"vesselName", "vesselNumber"}, voyageTimeTable, {"vesselName", "vesselNumber"}, "$toExpand", JoinKind.LeftOuter),
expanded = Table.ExpandTableColumn(joined, "$toExpand", {"voyageStartDatetime", "voyageEndDatetime"})
in expanded,
toExpand = Table.AddColumn(joined, "$toExpand", (currentRow as record) =>
let
voyageInclusiveStart = DateTime.From(currentRow[voyageStartDatetime]),
voyageExclusiveEnd = DateTime.From(currentRow[voyageEndDatetime]),
voyageDurationInDays = Duration.TotalDays(voyageExclusiveEnd - voyageInclusiveStart),
createRecordForPeriod = (someInclusiveStart as datetime) => [
inclusiveStart = someInclusiveStart,
exclusiveEnd = List.Min({
DateTime.From(Date.EndOfMonth(DateTime.Date(someInclusiveStart)) + #duration(1, 0, 0, 0)),
voyageExclusiveEnd
}),
durationInDays = Duration.TotalDays(exclusiveEnd - inclusiveStart),
prorataDuration = durationInDays / voyageDurationInDays,
estimated = prorataDuration * currentRow[estimated],
updated = prorataDuration * currentRow[updated],
month = Date.MonthName(DateTime.Date(inclusiveStart)),
year = Date.Year(inclusiveStart)
],
monthlyRecords = List.Generate(
() => createRecordForPeriod(voyageInclusiveStart),
each [inclusiveStart] < voyageExclusiveEnd,
each createRecordForPeriod([exclusiveEnd])
),
toTable = Table.FromRecords(monthlyRecords)
in toTable
),
expanded =
let
dropped = Table.RemoveColumns(toExpand, {"estimated", "updated", "voyageStartDatetime", "voyageEndDatetime"}),
expanded = Table.ExpandTableColumn(dropped, "$toExpand", {"month", "year", "estimated", "updated"})
in expanded
in
expanded
The code tries to:
join financialTable and voyageTimeTable, so that for each vesselName and vesselNumber combination, we know: estimated, updated, voyageStartDatetime and voyageEndDatetime.
generate a list of months for the period between voyageStartDatetime and voyageEndDatetime (which get expanded into new table rows)
for each month (in the list), do all the arithmetic you mention in your question
get rid of some columns (like the old estimated and updated columns)
I recommend testing it with different vesselNames and vesselNumbers from your dataset, just to see if the output is always correct (I think it should be).
You should be able to manually inspect the cells in the $toExpand column (of the toExpand step/expression) to see the nested rows before they get expanded.

Pinescript - "Compare" Indicator with Percentage Change Function takes only last bar data

need help pls.
In Tradingview I use "Compare" to see the BTCUSDT vs. ETHUSDT on Binance and it's basically OK. But lines on the chart are too "up & down" and I want to see the SMA or EMA for those tickers.
I'm trying to do it step by step but I can't pass through the issue that my code takes only last calculated value in consideration and "percentage change line" starts from 0 with each new data. So it makes no sence. Meaning, my last data doesn't add upon prior value, but always starts from zero.
So, data (value) that comes out is good (same as when I put same tickers on Tradingview "Compare") but Tradingview "Compare" calculates / adds data on historical data, while my code starts from 0.
Here is the Pine script code:
//#version=4
study(title="Compare", shorttitle="Compare", overlay=false, max_bars_back=0)
perc_change = (((close[0] - open[0]) / open [0]) * 100)
sym1 = "BINANCE:BTCUSDT", res1 = "30", source1 = perc_change
plot(security(sym1, res1, source1), color=color.orange, linewidth=2)
sym2 = "BINANCE:ETHUSDT", res2 = "30", source2 = perc_change
plot(security(sym2, res2, source2), color=color.blue, linewidth=2)
Sounds like the delta between the two ROCs is what you are looking for. With this you can show only the 2 ROCs, but also columns representing the delta between the two. you can also change the ROC's period:
//#version=4
study(title="Compare", shorttitle="Compare")
rocPeriod = input(1, minval = 1)
showLines = input(true)
showDelta = input(true)
perc_change = roc(close, rocPeriod)
sym1 = "BINANCE:BTCUSDT"
sym2 = "BINANCE:ETHUSDT"
res = "30"
s1 = security(sym1, res, perc_change)
s2 = security(sym2, res, perc_change)
delta = s1 - s2
plot(showLines ? s1 : na, "s1", color.orange)
plot(showLines ? s2 : na, "s2", color.blue)
hline(0)
plot(showDelta ? delta : na, "delta", delta > 0 ? color.lime : color.red, 1, plot.style_columns)

How to randomly generate an Oct-Tuple with SML

Edit: Here is the code I have so far for generating the Patient Oct-Tuples.
(thanks Anon for giving me the bost on how to calculate weighted probability/setting the seed)
fun genPatients(x:int) =
let
val seed=let
val m=Date.minute(Date.fromTimeLocal(Time.now()))
val s=Date.second(Date.fromTimeLocal(Time.now()))
in Random.rand(m,s)
end;
val survivalrate = ref(1)
val numl = ref(1)
val td = ref(1)
val xray = ref(false)
val count= ref(0)
val emnum= ref(1000)
val ageList = [1, 2, 3, 3];
val xrayList=[false,true];
val age = Random.randRange (0, 3) seed;(* random age*)
val nextInt1 = Random.randRange(0, 1)(* random xray*)
val r1 = Random.rand(1,1)
val nextInt2 = Random.randRange(1, 10000000)(* random td*)
val r2 = Random.rand(1,1)
val r1hold= ref(1);
in
while !count < x do
(
count:= !count + 1;
List.nth(ageList, age);
r1hold:= nextInt1 r1;
td:= nextInt2 r2;
(!emnum,age,survivalrate,numl,[],[],xray,td);
emnum:= !emnum + 1
)
end;
My question now is now how to go about indexing a boolean list?
So I was looking for some help defining my Oct-tuple to finish up my project and lo and behold I find someone posting the entirety of my project hoping for a handout answer. Not only that, but I'm almost certain we're in the same class, and you think posting this the night before the morning the project is due is what a responsible student does? Pretty sure nobody on SO is gonna do your homework for you anyway, in fact I'm not even sure it's allowed.
Maybe do some work and then ask for help when you've actually done anything. Or maybe in the next phase try a little harder.
EDIT: I'll give you something to get you started.
To calculate weighted probability you need a seed.
val seed=let
val m=Date.minute(Date.fromTimeLocal(Time.now()))
val s=Date.second(Date.fromTimeLocal(Time.now()))
in Random.rand(m,s)
end;
Here's one. Then you can calculate probability, at least for the age, like this:
val ageList = [1, 2, 3, 3];
val ageInt = Random.randRange (0, 3) seed;
List.nth(ageList, ageInt)
This was how I decided to do the weighted probability portion, you can equate this to the other weighted sections if you're creative. Good luck.