Extend Mathematica finance package capability

Extend Mathematica finance package capability


Mathematica can pull end of day trading data, but cannot pull intraday trading data. We can use webapi to pull intraday trading data and plot using Mathematica’s TradingChart or InteractiveTradingChart. Even though there are more convenient quote and indicators showing software such as TradingView, but use Mathematica we can add self-defined indicators, and we can do batch plot or customized aligned plot such as histogram PDF and CDF plot.

The tradingchart and interactivetradingchart function in mathematica show a header like "O:6.00 H:6:00 L:6:00 C:6.00 Wed. Nov 10,2021", but for intraday timeseries we want to see hours and minutes for the datetime, not the week month day and year as in the default display. We need to customize the datetime display to show hours and minutes in tradingchart. It would be desirable if we can update the datetime showing hours and minutes when we move cursor along the curves, the same as the original title lines updating OHLC and date (but not showing hours and minutes) dynamically. This can be done by set plotlabel to a string using dynamical module to calculate and interpolate the datetime using cursor coordinates. The DynamicModule tested is better than alternative ways such as using RuleCondition or Block with “/;True” trick methods.

We can use alphavantage for ten days up to yesterday's extended hours by minutes trading data for US’s stock exchange traded symbols.

intradayplotsalphavantage8t[sbll_, imagesize_:1200, ratio_:1/3]:=Module[{fi8,data, ts,dt,factor, colors},

fi8={"DI", "RMI","RSI","MAE","RRC","HMA",FinancialIndicator["SMA",21],"V"};

data=Import["https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol="<>sbll<>"&interval=1min&outputsize=full&apikey=yourkeyhere", "Data"];

ts=TimeSeries[Transpose[{(data[[2,2,All,1]]),ToExpression/@(data[[2,2,All,2,All,2]])}]];

dt=ts["Dates"];

factor=Length[dt]/100.0;

colors=(ColorData["Legacy",#]&/@{"AlizarinCrimson","Magenta","Navy","Blue"});

TradingChart[ts,fi8,PlotLabel->Style["\n"<>sbll<>" "<>(StringRiffle[ToString/@fi8,","])<>" "<>DynamicModule[{x=(Dynamic[DateString[dt[[IntegerPart[Min[Max[(MousePosition["Graphics"][[1]]),1/factor],100]*(factor)]]],"DateTimeShort"]])},x],Small, Blue],ImageSize->imagesize, AspectRatio->ratio,ChartStyle-> colors]

]

We can use twelvedata for two half month intraday thirty-five minutes late than real time plot, but it may have missing data for some date.

intradayplotstwelvedata1t[sbll_, enddate_:"2021-11-13",imagesize_:1200, ratio_:1/3]:=Module[{fi8,data,data1, ts, dt,factor,colors},

fi8={"DI", "RMI","RSI","MAE","RRC","HMA",FinancialIndicator["SMA",21],"V"};

data=Import["https://api.twelvedata.com/time_series?symbol="<>sbll<>"&end_date="<>enddate<>"&interval=1min&apikey=yourkeyhere&outputsize=5000", "Data"];

data1=Select[data[[2,2]], #[[-1,-1]]!="0"&];

ts=TimeSeries[Transpose[{(data1[[-1;;1;;-1,1,2]]),ToExpression/@data1[[-1;;1;;-1,2;;,2]]}]];

dt=ts["Dates"];

factor=Length[dt]/100.0;

colors=(ColorData["Legacy",#]&/@{"AlizarinCrimson","Magenta","Navy","Blue"});

TradingChart[ts,fi8,PlotLabel->Style["\n"<>sbll<>" "<>(StringRiffle[ToString/@fi8,","])<>" "<>DynamicModule[{x=(Dynamic[DateString[dt[[IntegerPart[Min[Max[(MousePosition["Graphics"][[1]]),1/factor],100]*(factor)]]],"DateTimeShort"]])},x],Small, Blue],ImageSize->imagesize, AspectRatio->ratio,ChartStyle-> colors]

]

We can use rapid yahoofinance for intraday 5 days per 1 minutes 18 minutes late than real time data, or 1 month per 5 minutes 52 minutes late than real time data, or 3 month per 60 minutes 52 minutes late than real time data plot, which has TSX symbols while the first two do not have.

intradayplotsrapid1t[symbol_,interval_:"2m", range_:"1mo",imagesize_:1200, ratio_:1/3]:=Module[{fi7,data,data1, ts, dt,factor,colors},

Off[StringJoin::string];

fi7={"RMI","RSI","MAE","RRC","HMA",FinancialIndicator["SMA",21],"V"};

data=Import["https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval="<>interval<>"&symbol="<>symbol<>"&range="<>range<>"&region=CA", "Data", Authentication-><|"Headers"->{"x-rapidapi-host"->"yh-finance.p.rapidapi.com","x-rapidapi-key"->"yourkeyhere"}|>];

data1=Select[Transpose@Prepend[{"open", "high", "low","close", "volume"}/.data[[1,2,1,2,1, 3, 2, 1,2,1]],data[[1,2,1,2,1,2,2]]], #[[-1]]>0&];

ts=TimeSeries[Transpose[{FromUnixTime/@(data1[[All,1]]),ToExpression/@data1[[All,2;;]]}]];

dt=ts["Dates"];

factor=Length[dt]/100.0;

colors=(ColorData["Legacy",#]&/@{"AlizarinCrimson","Magenta","Navy","Blue"});

TradingChart[ts,fi7,PlotLabel->Style["\n"<>symbol<>" "<>(StringRiffle[ToString/@fi7,","])<>" "<>DynamicModule[{x=(Dynamic[DateString[dt[[IntegerPart[Min[Max[(MousePosition["Graphics"][[1]]),1/factor],100]*(factor)]]],"DateTimeShort"]])},x],Small, Blue],ImageSize->imagesize, AspectRatio->ratio,ChartStyle-> colors]

]

One problem of these methods are that they are not persistent across sessions. An alternative way is to retrieve input form and use string replace to alter the displayed datetime.

intradayplotsalphavantage2treplace[sbll_, imagesize_:1200, ratio_:1/3]:=Module[{fi2,data, ts,out,colors},

Off[StringJoin::string];

fi2={"RRC","V"};

data=Import["https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol="<>sbll<>"&interval=1min&outputsize=full&apikey= yourkeyhere", "Data"];

ts=TimeSeries[Transpose[{(data[[2,2,All,1]]),ToExpression/@(data[[2,2,All,2,All,2]])}]];

colors=(ColorData["Legacy",#]&/@{"AlizarinCrimson","Magenta","Navy","Blue"});

out=InputForm[TradingChart[ts,fi2,PlotLabel->Style["\n"<>sbll<>" "<>(StringRiffle[ToString/@fi2,","]),Small, Blue],ImageSize->imagesize, AspectRatio->ratio,ChartStyle-> colors]];

out=StringReplace[ToString[out],"System`TradingChartDump`$visdates = {"~~Shortest[x___]~~"}":>"System`TradingChartDump`$visdates = "~~ToString@MapIndexed[#2[[1]]->("\""~~DateString[#1,"DateTimeShort"]~~"\"")&, out[[1,1,1,5]]]];

Show[Evaluate[ToExpression[out]]]

]

intradayplotstwelvedata1t04replace[sbll_, enddate_:"2021-11-13",imagesize_:1200, ratio_:1/3]:=Module[{fi4,data,data1, ts,colors},

Off[StringJoin::string];

fi4={"RSI","MAE","RRC","V"};

data=Import["https://api.twelvedata.com/time_series?symbol="<>sbll<>"&end_date="<>enddate<>"&interval=1min&apikey= yourkeyhere&outputsize=5000", "Data"];

data1=Select[data[[2,2]], #[[-1,-1]]!="0"&];

ts=TimeSeries[Transpose[{(data1[[-1;;1;;-1,1,2]]),ToExpression/@data1[[-1;;1;;-1,2;;,2]]}]];

colors=(ColorData["Legacy",#]&/@{"AlizarinCrimson","Magenta","Navy","Blue"});

out=InputForm[TradingChart[ts,fi4,PlotLabel->Style["\n"<>sbll<>" "<>(StringRiffle[ToString/@fi4,","]),Small, Blue],ImageSize->imagesize, AspectRatio->ratio,ChartStyle-> colors]];

out=StringReplace[ToString[out],"System`TradingChartDump`$visdates = {"~~Shortest[x___]~~"}":>"System`TradingChartDump`$visdates = "~~ToString@MapIndexed[#2[[1]]->("\""~~DateString[#1,"DateTimeShort"]~~"\"")&, out[[1,1,1,5]]]];

Show[Evaluate[ToExpression[out]]]

]

intradayplotsrapid7replace[symbol_,interval_:"2m", range_:"1mo",imagesize_:1200, ratio_:1/3]:=Module[{fi7,data,data1, ts,colors},

Off[StringJoin::string];

fi7={"RMI","RSI","MAE","RRC","HMA",FinancialIndicator["SMA",21],"V"};

data=Import["https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval="<>interval<>"&symbol="<>symbol<>"&range="<>range<>"&region=CA", "Data", Authentication-><|"Headers"->{"x-rapidapi-host"->"yh-finance.p.rapidapi.com","x-rapidapi-key"->" yourkeyhere"}|>];

data1=Select[Transpose@Prepend[{"open", "high", "low","close", "volume"}/.data[[1,2,1,2,1, 3, 2, 1,2,1]],data[[1,2,1,2,1,2,2]]], #[[-1]]>0&];

ts=TimeSeries[Transpose[{FromUnixTime/@(data1[[All,1]]),ToExpression/@data1[[All,2;;]]}]];

colors=(ColorData["Legacy",#]&/@{"AlizarinCrimson","Magenta","Navy","Blue"});

out=InputForm[TradingChart[ts,fi7,PlotLabel->Style["\n"<>symbol<>" "<>(StringRiffle[ToString/@fi7,","]),Small, Blue],ImageSize->imagesize, AspectRatio->ratio,ChartStyle-> colors]];

out=StringReplace[ToString[out],"System`TradingChartDump`$visdates = {"~~Shortest[x___]~~"}":>"System`TradingChartDump`$visdates = "~~ToString@MapIndexed[#2[[1]]->("\""~~DateString[#1,"DateTimeShort"]~~"\"")&, out[[1,1,1,5]]]];

Show[Evaluate[ToExpression[out]]]

]

One drawback of the replacing method is that it only works for TradingChart, for InteractiveTradingChart there is not such a variable exist, and it seems the only way is to use dynamic variable to display calculated datetime string from cursor coordinates.

In addition, experiments seems indicate that when the data points are more than 8000 both TradingChart and InteractiveTradingChart will not work. The following is an example case:

TradingChart[{"GE",{{1989,1,1},{2021,11,24}}}, ImageSize->Large]

The limitation of TradingChat seems is somewhat related to the Mathematica kernel calculating buffering and caching mechanism rather than hardware problem (with a test machine of about 200GB free memory). Trial and error find the upper bound of the TradingChat capability is about 7000 data points, 10 days equivalent of by minutes trading data. This limit can be seen from the following experiments:

Column[TradingChart[{"GE",{{#,1,1},{2021,11,24}}}]&/@Range[1949, 2009, 10]]

The following work with 6776 points:

FinancialData["GE",{{1995,1,1},{2021,11,24}}]

TradingChart[{"GE",{{1995,1,1},{2021,11,24}}}, ImageSize->Large]

The following have 7535 points and so the first three years’ data is skipped by TradingChat:

TradingChart[{"GE",{{1992,1,1},{2021,11,24}}}, ImageSize->Large]

Even only show 10 days’ worth of by minutes data of time series window, TradingChat may sometimes work and sometimes not, which may work after repetitive re-evaluate the failed plot, or first evaluate another plot and return to the failed plot and repeat re-evaluation until it works.


Jinzhu Jiang, FSA

Manager at AmerihealthCaritas

2 年

Frank - Great Work!

回复
Gina zhang

股东 - Xinyue Confinement Center

2 年

很棒呀!老王

回复

要查看或添加评论,请登录

Frank Wang的更多文章

  • Compound Poisson with Uniform Severity Loss Distribution

    Compound Poisson with Uniform Severity Loss Distribution

    The CDF of compound Poisson with Uniform severity distribution is found to be Sum[((-1)^k*(-k +…

  • New Algorithm for Convolution

    New Algorithm for Convolution

    We expect the AI age will be (almost) no-coding-programming, https://dx.doi.

    1 条评论
  • Summarize webpages to form a cover letter

    Summarize webpages to form a cover letter

    LinkedIn and Teal HQ LinkedIn have a function of create resume from your profile, but it focused on certifications from…

  • Double Pareto Distribution

    Double Pareto Distribution

    For given skewness, the maximum shape factor value achievable by GB2 can be attained by a Double Pareto (DP)…

  • Normalized skewness and normalized kurtosis

    Normalized skewness and normalized kurtosis

    Normalized skewness and normalized kurtosis Heuristically, skewness and kurtosis measuring up to the third and fourth…

  • Bing Aided Programming

    Bing Aided Programming

    AI empowered Bing is vastly knowledgeable, apprehensive of human intension, and easy to catch human hint or clue…

  • Python code to pull merge and save to txt from parquet files

    Python code to pull merge and save to txt from parquet files

    Bing now can give sound answers for many questions. Below is the conversation that I have with Bing for pull merge and…

  • PyCharm breakpoint action

    PyCharm breakpoint action

    If we want to change a variable value to effect specific code path in debug mode at some break point in PyCharm for…

  • EFEP distribution

    EFEP distribution

    We defined Twisted Wang Transform Distribution (TWTD) family, and found for a hurricane reinsurance-portfolio-loss the…

  • Shape factor asymptotic analysis II

    Shape factor asymptotic analysis II

    Probability distribution is the core for stochastic modeling. What type of distribution is more suitable for an…

社区洞察

其他会员也浏览了