Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date and time plot from .csv in Mathematica

i would like to plot a chart with date and time on the orizontal axis and integer value on the vertical axis. The data I have is in a .csv format, see the file.

I tried with

db = Dataset[
  Flatten[Import[
    "C:\\Users\\Matteo\\AppData\\Roaming\\MetaQuotes\\Terminal\\\
C10F84FF203255BEE7679EDC837848E1\\MQL4\\Files\\Data\\date_box.csv"]]]

DateListPlot[db]

but it turns out errors:

"The first two levels of \
{$Failed,$Failed,$Failed,$Failed,$Failed,$Failed,$Failed,$Failed,$\<<9951>>} cannot be transposed. "

Unable to automatically determine horizontal coordinates for the \
given data and DataRange.

"\!\(TraditionalForm\`{\"2018.02.02 21:59;0\", \"2018.02.02 \
21:59;0\", \"2018.02.02 21:58;0\", ...\) is not a \
valid dataset or list of datasets."

i can't fix it

like image 692
perjliv Avatar asked Feb 28 '26 01:02

perjliv


1 Answers

data = Import["C:\\Users\\Matteo\\...\\Files\\Data\\date_box.csv"];
d2 = StringSplit[#, ";"] & /@ Flatten[data];
t = DateList /@ d2[[All, 1]];
i = ToExpression /@ Last /@ d2;
DateListPlot[Transpose[{t, i}]]

enter image description here

Removing the weekend

days = Take[#, 3] & /@ t;
union = {#, DateString[#, "DayNameShort"]} & /@ Union[days]

Looks like you have some data points on Sunday

sundaypos = Position[days, {2018, 1, 28}];
Extract[i, sundaypos]

Deleting them

tnew = Delete[t, sundaypos];
inew = Delete[i, sundaypos];

Plotting with an adjustment to eliminate the weekend

t1 = AbsoluteTime[{2018, 1, 24}];
t2 = AbsoluteTime[{2018, 1, 27}];
t3 = AbsoluteTime[{2018, 1, 29}];

a = AbsoluteTime /@ tnew;
a2 = If[# >= t2, # - (t3 - t2), #] & /@ a;

labels = {AbsoluteTime[First[#]], Last[#]} & /@
   DeleteCases[union, {{2018, 1, 28}, "Sun"}];
labels[[All, 1]] = If[# >= t2, # - (t3 - t2), #] & /@
   labels[[All, 1]];

ListLinePlot[Sort@Transpose[{a2, inew}], Frame -> True, 
 FrameTicks -> {{Automatic, None}, {labels, None}}]

enter image description here

Version 3

{t1, t2, t3, t4, t5} = AbsoluteTime /@ {{2018, 1, 24},
    {2018, 1, 26, 22, 0, 0}, {2018, 1, 28, 22, 0, 0},
    {2018, 2, 2, 22, 0, 0}, {2018, 2, 4, 22, 0, 0}};

a = AbsoluteTime /@ t;
a2 = Which[
     # >= t4, # - (t3 - t2) - (t5 - t4),
     # >= t2, # - (t3 - t2),
     True, #] & /@ a;

labels = {AbsoluteTime[#],
     DateString[#, {"MonthNameShort", " ", "Day", "\n00:00"}]} & /@
   Append[DeleteCases[union,
      {{2018, 1, 28}, "Sun"}], {{2018, 2, 5}, "Mon"}][[All, 1]];

labels[[All, 1]] = Which[
     # >= t4, # - (t3 - t2) - (t5 - t4),
     # >= t2, # - (t3 - t2),
     True, #] & /@ labels[[All, 1]];

ListPlot[Sort@Transpose[{a2, i}], Frame -> True,
 FrameTicks -> {{Automatic, None}, {labels, None}},
 Epilog -> {Dashed, Gray, Line[{{t2, 100}, {t2, -800}}],
   Line[{{t4 - (t3 - t2), 100}, {t4 - (t3 - t2), -800}}]},
 ImageSize -> Large]

enter image description here

like image 116
Chris Degnen Avatar answered Mar 02 '26 14:03

Chris Degnen