plotter only plot the time, not the date - datetime

im trying to follow this guide on plotting a time series chart but ive run into a small issue. is there any way to change the bottom label to only show the current time (H:M:S) instead of the current date? ive been trying for a while now to find a way to do this but it still havent been able to. im following the code in the guide so this is the code im working with:
use plotters::prelude::*;
use chrono::{Utc, TimeZone};
fn main() {
let root_area = BitMapBackend::new("images/2.11.png", (600, 400))
.into_drawing_area();
root_area.fill(&WHITE).unwrap();
let start_date = Utc.ymd(2019, 10, 1);
let end_date = Utc.ymd(2019, 10, 18);
let mut ctx = ChartBuilder::on(&root_area)
.set_label_area_size(LabelAreaPosition::Left, 40)
.set_label_area_size(LabelAreaPosition::Bottom, 40)
.caption("MSFT daily close price", ("sans-serif", 40))
.build_cartesian_2d(start_date..end_date, 130.0..145.0)
.unwrap();
ctx.configure_mesh().draw().unwrap();
ctx.draw_series(
LineSeries::new(
(0..).zip(DATA.iter()).map(|(idx, price)| {
let day = (idx / 5) * 7 + idx % 5 + 1;
let date = Utc.ymd(2019,10, day);
(date, *price)
}),
&BLUE,
)
).unwrap();
}
const DATA: [f64; 14] = [ 137.24, 136.37, 138.43, 137.41, 139.69, 140.41, 141.58, 139.55, 139.68, 139.10, 138.24, 135.67, 137.12, 138.12];
ive tried using chrono's NaiveTime but it doesnt seem to be supported, DateTime causes the entire date and time to be printed instead of just the time, and ive also tried creating my own element series but i cant figure out how to get that working. anyone have any ideas?

You can add this line, or something like it to the ChartBuilder:
.x_label_formatter(&|x| format!("{:02}:{:02}", x.hour(), x.minute()))
where x is a DateTime struct. You can use other DateTime functions to get different parts of the time, as required.

Related

How to calculate the number of day-off trading like weekend, holidays?

Good Morning All!
The question in Pinescript,
Is there any trick to let my code determines whether the day before (yesterday) was day-off trading?
For example, I want my code to calculate the number of days-off.
I've coded this one, but it doesn't work perfectly at running data especially on the first day after off-market, but it works fine at historical data.
T=security(syminfo.tickerid, "1440", time)
fun()=>
NumDays= change(T)/86400000
Please Help!
This should work.
//#version=4
study("StackOverflow", overlay=true, max_labels_count=500)
daysBetween = change(dayofmonth(time))
if daysBetween > 1
label.new(bar_index, high, tostring(daysBetween) + " days", yloc=yloc.abovebar)
Edit: New code example.
This should work better.
I've actually asked a question about this myself recently.
See Detecting session breaks
//#version=4
study("NewSession", overlay=true)
var int days_off = na
var float change_in_ms = na
var int ms_per_day = 24 * 60 * 60 * 1000
change_in_ms := change(time("D"))
if change_in_ms
days_off := int(change_in_ms / ms_per_day)-1
bgcolor(change_in_ms ? color.yellow : na, 60)
plotchar(days_off, "days_off", "")

How to start/stop function based on entry start stop time

I've some LED lights that I want to turn on from entry box 0600 to 1800, or perhaps start another function from 1800 to 0300. how can I make a function to set so the action is ON during the period between the entry values and off otherwise. I've used Time but I'm running into issues. I don't know if I should convert the entry to Int() and compare but find it doesn't resolve the evening On entry. Any thoughts on this one would be appreciated.
LED_time_on_txt = StringVar()
LED_time_on = Entry(control_window, width = 4, bd=5, font= "Arial",14),textvariable=LED_time_on_txt)
LED_time_on.grid(row=3,column=8,sticky=W)
LED_time_off_txt = StringVar()
LED_time_off = Entry(control_window, width = 4, bd=5, font=("Arial",14),textvariable=LED_time_off_txt)
LED_time_off.grid(row=3,column=10,sticky=W)
Figured it out wiht other posts... function looks something like this:
now = datetime.now()
timeontxt = LED_time_on_txt.get()
timeofftxt = LED_time_off_txt.get()
time_on = now.replace(hour=int(timeontxt[:2]),
minute=int(timeontxt[:2]),second=0, microsecond=0)
time_off = now.replace(hour=int(timeofftxt[:2]), minute=int(timeofftxt[:2]), second=0, microsecond=0)
if time_on > time_off:
time_off = time_off + timedelta(days=1)
if time_on<now<time_off:
LED_status.config(text="ON")

Function not changing the data frame

I've recently made a simple for loop that outputs the Max and Min of the past 5 prices and it works perfectly, creating 2 new columns showing MaxH and MinL:
for(i in 5:nrow(XBTUSD_df_s)){
XBTUSD_df_s$MaxH[i] = max(XBTUSD_df_s$Price[(i-(5-1)):i])
XBTUSD_df_s$MinL[i] = min(XBTUSD_df_s$Price[(i-(5-1)):i])
}
I then put this for loop into a function so that I can adjust how many prices I want the Max and Min to be based off like so (the print lines were added as a sanity check):
FindMaxMin = function(x){
for(i in x:nrow(XBTUSD_df_s)){
XBTUSD_df_s$MaxH[i] = max(XBTUSD_df_s$Price[(i-(x-1)):i])
XBTUSD_df_s$MinL[i] = min(XBTUSD_df_s$Price[(i-(x-1)):i])
print(XBTUSD_df_s$MaxH[i])
print(XBTUSD_df_s$MinL[i])
}
}
But after for example:
FindMaxMin(x = 10)
The console will spit out all the expected results but unlike the for loop by itself, my dataframe will not automatically add on the MaxH and MinL columns.
I've tried return() and I think most likely it is a global environment problem but can't seem to wrap my head around it.
Thanks in advance!
You need to return the object from the function and then assign it later:
FindMaxMin = function(x, XBTUSD_df_s){
for(i in x:nrow(XBTUSD_df_s)){
XBTUSD_df_s$MaxH[i] = max(XBTUSD_df_s$Price[(i-(x-1)):i])
XBTUSD_df_s$MinL[i] = min(XBTUSD_df_s$Price[(i-(x-1)):i])
print(XBTUSD_df_s$MaxH[i])
print(XBTUSD_df_s$MinL[i])
}
return (XBTUSD_df_s)
}
new = FindMaxMin(10, XBTUSD_df_s)

Issues with RQuantLib advance date function

I'm relatively new to R and have found to SO invaluable to my coding journey, so first off: thank you to all contributors!
I'm writing some code looking at options trading, but I'm having issues with some of the RQuantLib functions. I am trying to 'add' days to a date using the "UnitedStates/NYSE" calendar. If you run the code below you can see the value is not as expected from the businessDaysBetween function (note the dates and the number of days returned or as an argument):
library(RQuantLib)
# This shows there is only one business day between the dates using the "UnitedStates/NYSE" calendar
businessDaysBetween(calendar = "UnitedStates/NYSE", from = as.Date("2010-06-20"), to = as.Date("2010-06-22"))
# And this next line of code should advance the date to "2010-06-22" but doesn't...
advance(calendar = "UnitedStates/NYSE", dates = as.Date("2010-06-20"), n = 1, timeUnit = 0)
Any help would be greatly appreciated as it's doing my nut in!
Best,
L
OK, so not a great start for me. I realised what the issue is: advance moves to the first business day after the date you supply if it is not a business day.
I wrote the following function to do that if it's useful. If anyone else knows a better way around this, please let us know!
GenerateClosestBusinessDay <- function(date) {
d <- 0
repeat {
if (isBusinessDay(calendar = cal, dates = as.Date(date + d))) {
return(as.Date(date + d))
break
} else {
d <- d + 1
}
}
}

How to always show the first and the last AxisX Label with Microsoft Chart Controls?

I'm developing a stocks evolution chart with Microsoft Chart Controls and I need to show the initial and final dates on the AxisX labels but I can't do it.
I google and found many solutions like set the properties:
Chart1.ChartAreas[0].AxisX.Minimum = InitialDate.ToOADate();
Chart1.ChartAreas[0].AxisX.Maximum = FinalDate.ToOADate();
Chart1.ChartAreas[0].AxisX.LabelStyle.IsEndLabelVisible = true;
Nothing made same differnce. I need a help !
On the sample below the initial date was Jul 26, 2007 and the final was Jul 26, 2010, this is what I need to show on the chart labels, the others dates don't make difference and can be showed in any interval.
alt text http://img826.imageshack.us/img826/6518/evolucaoinvestimento.png
LCharts(iChart).Chart.ChartAreas(0).AxisX.Minimum = MinDate.ToOADate
LCharts(iChart).Chart.ChartAreas(0).AxisX.Maximum = MaxDate.ToOADate
LCharts(iChart).Chart.ChartAreas(0).AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount
'LCharts(iChart).Chart.ChartAreas(0).AxisX.IsMarginVisible = True
LCharts(iChart).Chart.ChartAreas(0).AxisX.LabelStyle.IsEndLabelVisible = True
I get a way:
// get the interval in days
double days = (double)((TimeSpan)(FinalDate - InitialDate)).Days;
// the number os labels
double labels = 10.0;
// check if the number of days is bigger than labels
if (days > labels)
{
// calculate the interval
double interval = days / labels;
Chart1.ChartAreas[0].AxisX.Interval = interval;
}
else
{
// set the interval of 1 day
Chart1.ChartAreas[0].AxisX.Interval = 1;
}
Here is the result:
chart http://img691.imageshack.us/img691/7796/chartimgca42ufcm.png

Resources