Skip to main content

Interfacing C# .Net and R - Integrating the best of both worlds (Part 3) - Trader Desk Example

In this third and final part of the series (Part 1, Part 2), I am going to continue shaping the examples in the previous posts by quickly building a small application - a simple Trading Desk application. In the example I will use the same C# and R interface method together with a specific Quantitative Financial Modelling R library called Quantmod.

Example Objective
In the example the objective is to build a C# Web Form which acts as the main application controller that captures various user option parameters with the main functions being:

1. To automatically kick off an R routine to download data from Yahoo Finance.
2. To select specific dates of interest
3. To add or udpate different charts
4. To add different chart indicators
5. To calculate Period Return Statistics

Most of these functions are provided through the set of R functions exposed by the Quantmod R library.

Additions under the hood

Below I am showing some of the salient additions done to the code over and above the code in the previous posts. Since the underlying program structure is in line with the explanations in the previous posts I am not going to delve again into detailed explanations. The code should be pretty self explanatory.

//My RFacade Class - note the new addition to load Quantmod Library
public RFacade()
{
     rconn = new STATCONNECTORSRVLib.StatConnector();
     rconn.Init("R");


     //load R Quantmod Library
     rconn.EvaluateNoReturn("library(quantmod)");
}


//Get data from yahoo finance
public void RGetData(String symbol)
{
     String RCommand = "getSymbols('"+symbol+"',src='yahoo')";
     rconn.EvaluateNoReturn(RCommand);
}


//Draw Candle Chart for specific company symbol and date range
public void RCandleChart(String symbol, DateTime from, DateTime to)
{
     String dateRange = FormatDateRange(from, to);
     String RCommand = "candleChart(" + symbol +dateRange+",multi.col=TRUE,theme='white')";
     rconn.EvaluateNoReturn(RCommand);
}

//Draw Bar Chart for specific company symbol and date range
public void RBarChart(String symbol, DateTime from, DateTime to)
{
     String dateRange = FormatDateRange(from, to);
     String RCommand = "barChart(" + symbol + dateRange + ")";
     rconn.EvaluateNoReturn(RCommand);
}


//Draw ChartSeries plot for specific company symbol and date range
public void RTimeSeries(String symbol, DateTime from, DateTime to)
{
     String dateRange = FormatDateRange(from, to);
     String RCommand = "chartSeries(" + symbol + dateRange + ")";
     rconn.EvaluateNoReturn(RCommand);
}


//Create new R grahics window (/device)
public void RNewChart()
{
     String RCommand = "windows()";
     rconn.EvaluateNoReturn(RCommand);
}


//Add Indicators
public void addIndicatorSMA()
{
     String RCommand = "addSMA(20)";
     rconn.EvaluateNoReturn(RCommand);
}


public void addIndicatorDPO()
{
     String RCommand = "addDPO()";
     rconn.EvaluateNoReturn(RCommand);
}


public void addIndicatorBBands()
{
     String RCommand = "addBBands()";
     rconn.EvaluateNoReturn(RCommand);
}


//Get Mean Return
public double RGetMeanReturn(String symbol, DateTime from, DateTime to)
{
     String dateRange = FormatDateRange(from, to);
     String RCommand = "logRet<-diff(log(" + symbol + "))";
     rconn.EvaluateNoReturn(RCommand);
     RCommand = "mean(logRet" + dateRange + "[,4])";
     return (double)rconn.Evaluate(RCommand);
}

How it Looks
As you can see from the screen shot below, with this approach one can quickly start to mash up interesting applications by benefeting from the rich R platform and the flexible C# front end.

Hope you found this series of articles on C# and R interfacing using R(D)COM interesting ... and please anyone who wishes to continue discussing or collaborate or share experiences just drop me an email  or post a comment.


Click to Enlarge

Comments

Anonymous said…
Vince,
What is the way to pass a table of time-series data of multiple stocks to R ? How do you pass a matrix ?

Thanks for your post.
Anonymous said…
Hi Vince,
Very nice blog and extremely useful! I am wondering if you have suggestions on how to capture the contents of a table using the GetSymbol function. For example, I have an R variable called 'locations' that has 150 entries and each row has 4 values (x,y,date,time). I'm trying to do something like:
object locs = RConn.GetSymbol("locations");
But locs only comes back with the first row. I've tried casting to a multidimensional object array:
object[,] locs = (object [,])RConn.GetSymbol("locations");
but that throws an error. Any ideas on how-to cast an R table into an equivalent C# object?
Thanks,
Jake
Unknown said…
Could you make your .NET solution available for download? It would be helpful in my efforts to recreate your work.
Unknown said…
Hi Vincent:
Do you by any chance know how can I populate a ms Access query or a listbox with data from R using StatConnector?
I am able to connect and send data
to R but I can't find the way to display it. This is what I am trying to do:
Dim myApp As New StatConnector

'initialize R server and transfer df array to R variable
myApp.Init ("R")
myApp.SetSymbol "df", myAccessTable
a = myApp.GetSymbol("df")
'Pseudo code below
listbox.rowsource=a
or
myquery.datasource=a
Thanks
Anonymous said…
Hi Vincent,

Many thanks to your blog& work!!

I use R in ASP.NET and it works apart from the code below.

s <- read.table("testfile.csv", header=TRUE, sep=",")

reg <- function(d){
reg.u <- unique(d$o)
reg.df <- data.frame(id=0,return=0)

for(i in 1:length(reg.u)){
reg.sub <- subset(d, o==reg.u[i])
x <- reg.sub$x
y <- reg.sub$y
z <- reg.sub$z
}

Maybe you know why subset is not working, I always get a: "Linked object's source class has changed (Exception from HRESULT: 0x80040008 (OLE_E_CLASSDIFF))"

Many thanks in advance Vincent
Unknown said…
Hi,

may I ask, where is the FormatDateRange function from?

Popular posts from this blog

Interfacing C# .Net and R - Integrating the best of both worlds

In specific software areas like in quantitative finance or else in other mathematical domains, data centric programming typically requires a good balance between three requirements - (1) a solid platform with rich mathematical/statistical functionality (2) having an easy to use, contemporary, programming environment which permits easy and flexible front end code development and (3) an easy to use interface between the two environments. In this artcile I am going to explain how such a balance can be attained by using two of the best products in their specific worlds - using the rich R library as the mathematical/statistical component but then interfacing with C# for the front end application design. As an interfacing option I banked on using R (D)COM which provides an easy to use interfacing method which keeps you away from spending hours identifying interfacing problems. The software required for this tutorial is the following: 1. R software ( download from here ) 2. R (D)COM Interf

Interfacing C# .Net and R - Integrating the best of both worlds (Part 2)

This post is a continuation from the previous post ( Part I ) focusing on interfacing C# with R using the R (D)COM. In this post I am going to enhance my previous exercise by creating a Facade .Net Class which facilitates access to specific functions in R. Creating the R Facade Class Creating a Facade Class (or a set of .Net classes) which acts as a .Net wrapper to R functions greatly facilitate the use of R functions and their integration within the .Net programming environment. Below I am showing an excerpt from the class RFacade that I have created in this example. using System; using System.Collections.Generic; using System.Linq; using System.Text; using StatConnectorCommonLib; using STATCONNECTORSRVLib; using System.Runtime.InteropServices; namespace R { class RFacade : IDisposable {      private StatConnector rconn;      private bool disposed = false;      public RFacade()      {           rconn = new STATCONNECTORSRVLib.StatConnector();           rcon

Simple moving average trading strategy using Python

Hi All, I am presenting simple boiler point code that can quickly be applied to test technical indicator strategies using Python. The code: 1. downloads daily stock data from google, 2. calculates the short and long moving averages 3. generates the trading signals 4. calculates the daily returns 5. runs the moving average strategy and calculates the cumulative return 6. plots cumulative return of our simple strategy Here is the code ... enjoy trying it out and extend it as required: import numpy as np import pandas_datareader as datar import datetime import matplotlib.pyplot as plt date_start = datetime.datetime( 2017 , 1 , 1 ) date_end = datetime.datetime( 2017 , 6 , 30 ) data = datar.get_data_google( 'AAPL' , date_start , date_end) short_ma = 5 long_ma = 20 data[ 'short_ma' ] = data[ 'Close' ].rolling(short_ma).mean() data[ 'long_ma' ] = data[ 'Close' ].rolling(long_ma).mean() data[ 'masig' ] = data[ 'short_ma'