How to extend a Indicator COT Data Line - pine-script-v5

Unfortunately, the commodity trade market is closed at the weekend. The new COT data will come on Saturday. The script therefore only shows the old data until Monday when the markets open again. But I would like to analyze the markets at the weekend. So how can I see the COT data in the indicator already at the weekend? I thought that it would be possible if we extend the indicator line by one point as an extension or as a forecast which are downloading the new data into the future without priceaction.
'qticker = syminfo.root == 'GE'
comm_lg = request.security(legacy_cot + '4', 'W', close)
comm_sh = request.security(legacy_cot + '5', 'W', close)
comm_net = comm_lg - comm_sh
plot(comm_net, color=color.new(color.red, 0), title='Commercials Net', style=plot.style_line, linewidth=2)`

Related

Saving synchronised 7T fMRI Triggers received via USB connected NNL SyncBox, on every TR and Task Response Keypress (PsychoPy)

I would like to get synchronised timings and number of triggers for each single pulse sent by the 7T MRI scanner together with each single SPACEBAR keypress as a participant’s response when particular letters (A, B, C, X, Y) are presented on the screen, also the stimulus start time with each corresponding trigger.
So far I have added a “Waiting for scanner” routine where I get the first pulse via USB connected NNL Synbox saved in the .csv data file but I want to save each single pulse (TR) and timings. Triggers are automatically emulated as letter ‘s’ sent by the NNL Synbox.
# Code component: Creat routine "Wait for Scanner"
text_wait = visual.TextStim(win=win, name='text_wait',
text='Waiting for scanner...',
font='Arial',
pos=(0, 0), height=0.8, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
#Set first MR Trigger
mr_trigger_number = [] # list for triggers
mr_trigger_time = [] # list for time of each trigger
ScannerKeyboard = keyboard.Keyboard() # set keyboard
count_mr_trigger = 0 # counts amount of MR scanner trigger, starts with zero
start_trigger = ScannerKeyboard.getKeys(keyList=['s'], waitRelease = False) # experiment starts with MR Scanner "s"
# Draw waiting Screen until "s" is sent from NNL Syncbox
while len(start_trigger) == 0: # if no trigger was sent show:
text_wait.draw() # Text "Waiting for scanner"
win.flip()
start_trigger = ScannerKeyboard.getKeys(keyList=['s'], waitRelease = False) # show text_wait until one "s" was received
# Get timing information and store trigger number
onset = core.getTime() # get Onset time of trigger
count_mr_trigger = count_mr_trigger + 1 # count MR Scanner trigger, add "1!
# Save time and number of MR Trigger
thisExp.addData('MR_trigger_time',onset) # save trigger time of onset
thisExp.addData('MR_trigger_number',count_mr_trigger)
And also I used the following code component in > Each Frame tab of 2 trials conditions to save the stimuli onset timings when a pulse 's' is received. This works fine but stimulus start time > stimulus_start_time = globalClock.getTime() - mr_trigger_time is saved based on first pulse only as I am unable to save each pulse timings.
#save stimulus onset time for two types of trial conditions
if trials.thisN == 0 and frameN == 0:
loop_start_time = globalClock.getTime() - mr_trigger_time
elif frameN == 1:
stimulus_start_time = globalClock.getTime() - mr_trigger_time
# store the data:
thisExp.addData('stimulus_start_time', stimulus_start_time)
if trials_2.thisN == 0 and frameN == 0:
loop_start_time = globalClock.getTime() - mr_trigger_time
elif frameN == 1:
stimulus_start_time = globalClock.getTime() - mr_trigger_time
# store the data:
thisExp.addData('stimulus_start_time', stimulus_start_time)
However, I want to record and save timings of each trigger pulse when a SPACEBAR response is pressed on a target letter (stimulus) by a participant, to compare the timings with accuracy and reaction times of the task with each corresponding trigger timings.
I would really appreciate your valuable suggestions on how to work around this, as I am quite new to the PsychoPy. I also posted to the PsychoPy forum but haven't got any update so far.
Thanks in advance!

Google Apps script - Checkbox to open a prefilled google form link

I have created a script that when I click on a checkbox on column "A" it then goes to column "B" to open the link in that same row. The script also clears the checkbox and two other cells in the same row. I also have an installed "onedit" trigger for the script. The script is currently working, the only thing is that sometimes it executes fast and other times it stalls and it executes slow. Can you please guide me on making the script execute fast every time without stalling. Thank you for your help! See script and picture below:
A column and B column picture
`function urlonEdit(e) {
const src = e.source.getActiveSheet();
const r = e.range;
if (src.getName() != "ROLL CALL" || r.columnStart != 1 || r.rowStart <= 2 || !r.isChecked()) return;
let url = src.getRange(r.rowStart, 2, 1, 1).getValues();
src.getRange(r.rowStart, 1, 1, 1).clearContent();
src.getRange(r.rowStart, 13, 1, 1).clearContent();
src.getRange(r.rowStart, 14, 1, 1).clearContent();
let response = UrlFetchApp.fetch(url);`}

Importing two text files to compare as lists sequentially

Student trying to compare two .txt files of string "answers" from a multiple choice test a,c,d,b, etc. I've found some information on different parts of the problems I'm having and found a possible way to get the comparisons I want, but the guide was meant for in script strings and not pulling a list from a file.
For the import of the two files and comparing them, I'm basing my code on my textbook and this video here: Video example
I've got the code up and running, but for some reason I'm only getting 0.0% match when I want to a 100.0% match, at least for the two text files I'm using with identical answer lists.
import difflib
answer_sheet = "TestAnswerList.txt"
student_sheet = "StudentAnswerList.txt"
ans_list = open(answer_sheet).readlines()
stu_list = open(student_sheet).readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=ans_list, b=stu_list)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match")
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# not the crux of my issue, but will accept advice all the same
answer_sheet.close
student_sheet.close
If I add in the close statement at the end for both of the text files, then I receive this error:
Traceback (most recent call last): File
"c:/Users/jaret/Documents/Ashford U/CPT 200/Python Code/Wk 5 Int Assg
- Tester code.py", line 18, in
answer_sheet.close AttributeError: 'str' object has no attribute 'close'
I had to re-look at how my files were being opened and realized that the syntax was for Python 2 not 3. I chose to go w/ basic open and later close to reduce any potential errors on my novice part.
import difflib
f1 = open('TestAnswerList.txt')
tst_ans = f1.readlines()
f2 = open('StudentAnswerList.txt')
stu_ans = f2.readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=stu_ans, b=tst_ans)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match") # Percentage correct
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# Visual Answer match-up
print('Test Answers: ', tst_ans)
print('Student Answers:', stu_ans)
f1.close()
f2.close()

perl Data::Dumper to extract key values

I have some perl code which I've written to get weather data/alerts from NOAA.
My code is pretty simple:
use Weather::NOAA::Alert;
use Data::Dumper;
$alert = Weather::NOAA::Alert->new(['TXC301']);
$events = $alert->get_events();
$alert->poll_events();
print Dumper($events);
# #url = (keys %{$VAR1->{'TXC301'}});
# $url = $VAR1->{'TXC301'};
$url = $events->{'TXC301'};
print "URL is $url\n";
# $expires= $events->{'TXC301'}->{$url}->{'expires'};
$expires= $events->{'TXC301'}->{'http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576'}->{'expires'};
print "Expires: $expires\n";
The output:
$VAR1 = {
'TXC301' => {
'http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576' => {
'certainty' => 'Likely',
'senderName' => 'NWS Midland-Odessa (Western Texas and Southeastern New Mexico)',
'urgency' => 'Expected',
'instruction' => 'A FLOOD WARNING MEANS THAT FLOODING IS IMMINENT OR HAS BEEN REPORTED.
STREAM RISES WILL BE SLOW AND FLASH FLOODING IS NOT EXPECTED.
HOWEVER... ALL INTERESTED PARTIES SHOULD TAKE NECESSARY PRECAUTIONS
IMMEDIATELY.
DO NOT DRIVE YOUR VEHICLE INTO AREAS WHERE THE WATER COVERS THE
ROADWAY. THE WATER DEPTH MAY BE TOO GREAT TO ALLOW YOUR CAR TO CROSS
SAFELY.',
'description' => 'THE NATIONAL WEATHER SERVICE IN MIDLAND HAS ISSUED A
FLOOD WARNING FOR...
SOUTHWESTERN LOVING COUNTY IN WEST TEXAS...
NORTHWESTERN WARD COUNTY IN WEST TEXAS...
NORTH CENTRAL REEVES COUNTY IN SOUTHWEST TEXAS...
UNTIL 300 PM CDT FRIDAY
AT 259 AM CDT...ROADS REMAIN CLOSED NEAR THE PECOS RIVER BETWEEN
RED BLUFF AND INTERSTATE 20 BECAUSE OF ELEVATED RIVER LEVELS DUE
TO RECENT RAINS. FLOODING WILL ALSO IMPACT THE CITY OF PECOS.',
'event' => 'Flood Warning',
'delete' => 0,
'category' => 'Met',
'severity' => 'Moderate',
'effective' => '2014-09-26T03:00:00-05:00',
'headline' => 'Flood Warning issued September 26 at 3:00AM CDT until September 26 at 3:00PM CDT by NWS Midland-Odessa',
'expires' => '2014-09-26T15:00:00-05:00'
}
}
};
URL is HASH(0x26384c0)
Expires: 2014-09-26T15:00:00-05:00
The TXC301 is a report identifier.
The output of the script will print all the values fetched from NOAA.
The goal is to store/return the 'expires' value.
I have lines commented out, which were attempts at achieving my goal.
The problem I'm having is getting the $url variable. I need this value in order to get my $expires value. The 2nd to last line in my code will correctly get the $expires value, but in order to do this I needed to hard code the URL into the line.
I'm trying to get the line directly above that (3rd to last) to work:
$expires= $events->{'TXC301'}->{$url}->{'expires'};
But this depends on the $url value to be stored.
I can't seem to figure out how to get the $url value.
My guesses:
#url = (keys %{$VAR1->{'TXC301'}});
$url = $VAR1->{'TXC301'};
$url = $events->{'TXC301'};
None of which work.
Any help would be great.
Thanks!
Regards,
Joseph Spenner
Given there is only one value for that level of hash ref, you could use values:
print +( values %{ $VAR1->{TXC301} } )[0]{expires}, "\n";
Outputs:
2014-09-26T15:00:00-05:00
Alternative to Data::Dumper
Also, on a separate issue, I would like to recommend the use of Data::Dump over the core library Data::Dumper.
The default settings and features for this alternative give superior output and enable one to analyze a data structure a lot quicker as demonstrated below:
$VAR1 = {
'TXC301' => {
'http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576' => {
'certainty' => 'Likely',
'senderName' => 'NWS Midland-Odessa (Western Texas and Southeastern New Mexico)',
'urgency' => 'Expected',
'instruction' => 'A FLOOD WARNING MEANS THAT FLOODING IS IMMINENT OR HAS BEEN REPORTED.
STREAM RISES WILL BE SLOW AND FLASH FLOODING IS NOT EXPECTED.
HOWEVER... ALL INTERESTED PARTIES SHOULD TAKE NECESSARY PRECAUTIONS
IMMEDIATELY.
DO NOT DRIVE YOUR VEHICLE INTO AREAS WHERE THE WATER COVERS THE
ROADWAY. THE WATER DEPTH MAY BE TOO GREAT TO ALLOW YOUR CAR TO CROSS
SAFELY.',
'description' => 'THE NATIONAL WEATHER SERVICE IN MIDLAND HAS ISSUED A
FLOOD WARNING FOR...
SOUTHWESTERN LOVING COUNTY IN WEST TEXAS...
NORTHWESTERN WARD COUNTY IN WEST TEXAS...
NORTH CENTRAL REEVES COUNTY IN SOUTHWEST TEXAS...
UNTIL 300 PM CDT FRIDAY
AT 259 AM CDT...ROADS REMAIN CLOSED NEAR THE PECOS RIVER BETWEEN
RED BLUFF AND INTERSTATE 20 BECAUSE OF ELEVATED RIVER LEVELS DUE
TO RECENT RAINS. FLOODING WILL ALSO IMPACT THE CITY OF PECOS.',
'event' => 'Flood Warning',
'delete' => 0,
'category' => 'Met',
'severity' => 'Moderate',
'effective' => '2014-09-26T03:00:00-05:00',
'headline' => 'Flood Warning issued September 26 at 3:00AM CDT until September 26 at 3:00PM CDT by NWS Midland-Odessa',
'expires' => '2014-09-26T15:00:00-05:00'
}
}
};
use Data::Dump;
dd $VAR1;
Outputs:
{
TXC301 => {
"http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576" => {
category => "Met",
certainty => "Likely",
delete => 0,
description => "THE NATIONAL WEATHER SERVICE IN MIDLAND HAS ISSUED A\n FLOOD WARNING FOR...\nSOUTHWESTERN LOVING COUNTY IN WEST TEXAS...\nNORTHWESTERN WARD COUNTY IN WEST TEXAS...\nNORTH CENTRAL REEVES COUNTY IN SOUTHWEST TEXAS...\n UNTIL 300 PM CDT FRIDAY\n AT 259 AM CDT...ROADS REMAIN CLOSED NEAR THE PECOS RIVER BETWEEN\nRED BLUFF AND INTERSTATE 20 BECAUSE OF ELEVATED RIVER LEVELS DUE\nTO RECENT RAINS. FLOODING WILL ALSO IMPACT THE CITY OF PECOS.",
effective => "2014-09-26T03:00:00-05:00",
event => "Flood Warning",
expires => "2014-09-26T15:00:00-05:00",
headline => "Flood Warning issued September 26 at 3:00AM CDT until September 26 at 3:00PM CDT by NWS Midland-Odessa",
instruction => "A FLOOD WARNING MEANS THAT FLOODING IS IMMINENT OR HAS BEEN REPORTED.\nSTREAM RISES WILL BE SLOW AND FLASH FLOODING IS NOT EXPECTED.\nHOWEVER... ALL INTERESTED PARTIES SHOULD TAKE NECESSARY PRECAUTIONS\nIMMEDIATELY.\nDO NOT DRIVE YOUR VEHICLE INTO AREAS WHERE THE WATER COVERS THE\nROADWAY. THE WATER DEPTH MAY BE TOO GREAT TO ALLOW YOUR CAR TO CROSS\nSAFELY.",
senderName => "NWS Midland-Odessa (Western Texas and Southeastern New Mexico)",
severity => "Moderate",
urgency => "Expected",
},
},
}
Ok, I was able to piece something together which worked:
use Weather::NOAA::Alert;
use Data::Dumper;
$alert = Weather::NOAA::Alert->new(['TXC301']);
$events = $alert->get_events();
$alert->poll_events();
Dumper($events);
print +( values %{ $events->{TXC301} } )[0]{expires}, "\n";
By changing $VAR1 to $events in the last line, I got rid of the error and got the exact output I needed.
Thanks for all the quick replies!
Regards,
Joseph Spenner

Schema for opening hours MongoDB

How would you store opening hours on a document, say a Library, in mongoDB, that's easily queryable with Mongoid? I've read this thread, but I'm not sure how it would be implemented with my needs.
I need to have the ability to add multiple opening and closing times per day since the Library should be able to close some hours during the day and then reopen.
I need to be able to add exceptions to these opening hours. For example; close monday on a specific date.
Please share some best practices and experiences on how one could do this the most flexible way.
Thank you, Yeggeps, for the list of requirements.
This is a revised answer based on your requirements. Of course there is no holy grail to schemae, but I would like to motivate my answer before revision (keeping a flat structure is easy to query and maintain) with some sample data + queries based on your requirement list. I reiterate, I am not saying this is the best solution, but it is a solution which is straightforward to query and easy to maintain (imho).
Code is a little quick and dirty, apologies. The data:
[
# library "lib1" open on wednesdays from 8:00 until 17:00
{"lib_id" => "lib1", "type" => "hours", "opening" => 800, "closing" => 1700, "day_of_week" => 3},
# library "lib1" open on wednesdays from 19:00 until 22:15
{"lib_id" => "lib1", "type" => "hours", "opening" => 1900, "closing" => 2215, "day_of_week" => 3},
{"lib_id" => "lib1", "type" => "hours", "opening" => 800, "closing" => 1700, "day_of_week" => 4},
{"lib_id" => "lib2", "type" => "hours", "opening" => 1100, "closing" => 1700, "day_of_week" => 3},
{"lib_id" => "lib2", "type" => "hours", "opening" => 1400, "closing" => 1700, "day_of_week" => 4},
{"lib_id" => "lib2", "type" => "hours", "opening" => 1900, "closing" => 2100, "day_of_week" => 4},
# library lib1 closed on wednesday december 7th 2011
{"lib_id" => "lib1", "type" => "closed_on", "reason" => "Rearranging the shelves", "closed_date" => Time.utc(2011, 12, 8)},
{"lib_id" => "lib2", "type" => "closed_on", "reason" => "We are closed for the holidays", "closed_date" => Time.utc(2011, 12, 7)}
].each do |schedule|
coll.save(schedule)
end
Show opening hours and exceptional dates separately:
# List all the library id's distinctly
coll.distinct("lib_id").each do |lib_id|
puts "\nLibrary #{lib_id} opening hours:\n--- "
# I need to be able to show the opening hours in correlation with the Library
# Find all the opening hour information for current library
coll.find({"lib_id" => lib_id, "type" => "hours"}).each do |schedule|
puts " #{Date::DAYNAMES[schedule["day_of_week"]]}s: #{schedule["opening"]} - #{schedule["closing"]}" if schedule["type"] == "hours"
end
# I need to show an indication if it's open or closed in correlation with the Library.
puts "This library will be closed on: "
# Find all the exceptions for current lib_id -- introduce a time-period restriction using Date.utc (...)
coll.find({"lib_id" => lib_id, "type" => "closed_on"}).each do |closed|
puts " #{closed["closed_date"].strftime("%a %B%e, %Y")}: #{closed["reason"]}"
end
end
Which libraries are open today?
# I need to be able to query on what's open right now or some time in the future with minute granularity
# here I'll also need to be able to exclude the Librarys that has added exceptions for the given time/day
puts "---"
qtime = (Time.now.hour * 100) + Time.now.min # minute granularity
qwday = Time.now.wday # this example only shows today
qclosed = Time.utc(Time.now.year, Time.now.mon, Time.now.mday)
# Query for all library ids which have opening times for this weekday, at this hour (+minutes)
coll.find({"opening" => {"$lte" => qtime}, "closing" => {"$gte" => qtime}, "day_of_week" => qwday}, {:fields => "lib_id"}).each do |lib|
# Check whether current library has an exception for this specific day
closed = coll.find_one({"lib_id" => lib["lib_id"], "closed_date" => qclosed})
if closed
# If an exception record was encountered, print the reason
puts "Library #{lib["lib_id"]} is normally open right now, but is now closed: '#{closed["reason"]}'"
else
# Else: the library is open
puts "Library #{lib["lib_id"]} is open right now! (#{Time.now.strftime("%a %B%e %Y, %H:%M")})"
end
end
Produces output as follows:
Library lib1 opening hours:
---
Wednesdays: 800 - 1700
Wednesdays: 1900 - 2215
Thursdays: 800 - 1700
This library will be closed on:
Thu December 8, 2011: Rearranging the shelves
Library lib2 opening hours:
---
Wednesdays: 1100 - 1700
Thursdays: 1400 - 1700
Thursdays: 1900 - 2100
This library will be closed on:
Wed December 7, 2011: We are closed for the holidays
---
Library lib1 is open right now! (Wed December 7 2011, 13:12)
Library lib2 is normally open right now, but is now closed: 'We are closed for the holidays'
Admittedly, the downside to my proposed solution is that it does not capture every requirement in one query.
It's difficult to provide a good solution without knowing the exact queries you'd like to run. For instance, if you're asking "what businesses are open now (5:32 PM, 5/11/2011)?" you'd want a different schema than if you were asking "when is business XYZ open next?"
In the first case, you'll want to be able to efficiently pose range queries on the current hour, minute, and day -- as well as negative queries on an exception list. Alternatively, you can handle exceptions in client code.
Last, what is the level of granularity needed? What is the smallest exception possible? Minutes? Hours? Days?
I'd post the above as a comment but I just created a user account. With additional information, I'll update this to provide an actual answer.