% Add the RPNA data gateway jar file
javaaddpath('C:\Program Files (x86)\RavenPack\api\DataGatewayClient.jar')

%% RavenPack News Analytics example workflow.

% Connect to the RPNA gateway
c = ravenpack('testuser','5lyn33o8');

% Get RPNA entitlements
e = entitlements(c);

% Use the first symbol for data requests
symbol = e.NAME{1};

% Load an existing RPNA intraday data file into the workspace
histData = rploader('2014-11-equities.csv');

% Request approximately 2 1/2 hours of intraday data for all valid fields
recentData = timeseries(c,symbol,{now-.1,now});

% Example request for latest minute of intraday data for the given fields
essData = timeseries(c,symbol,{now-.001,now},{'ENTITY_NAME','GROUP','ESS'});

% Calculate event volume indicators
% Source: "Enhancing Short-term Stock Reversal Strategies With News
% Analytics, September 5, 2013
% RavenPack Quantitative Research

% Combine data and shift timestamps to whole date
allData = [histData; recentData];
allData.TIMESTAMP_UTC = dateshift(allData.TIMESTAMP_UTC,'start','day');

% Get events for Twitter
iCompany = eq('Twitter Inc.',allData.ENTITY_NAME);
companyData = allData(iCompany,:);

% Remove insider-trading and order-imbalance events
iIT = eq('insider-trading',companyData.GROUP);
companyData(iIT,:) = [];
iIT = eq('order-imbalances',companyData.GROUP);
companyData(iIT,:) = [];

% Total EVI's
EVI = 0;
eviData(1,1) = EVI;
essTimestamp = companyData.TIMESTAMP_UTC(1);
iEVI = 1;
for j = 1:length(companyData.ESS)
  % Discard neutral and empty scores
  if ~isempty(companyData.ESS(j)) && ~eq(companyData.ESS(j),'50')
    % Add new record for new day's event, otherwise increment existing count
    if essTimestamp(iEVI) ~= companyData.TIMESTAMP_UTC(j)
      essTimestamp(end+1,1) = companyData.TIMESTAMP_UTC(j); %#ok
      iEVI = length(essTimestamp);
      EVI = 0;
    else
      essTimestamp(end,1) = companyData.TIMESTAMP_UTC(j);
    end
    EVI = EVI + 1;
    eviData(iEVI,1) = EVI;  
  end
end

% Create table with EVI data
twitter = table(essTimestamp,eviData,'VariableNames',{'Timestamp','Twitter_EVI'});

% Clear temporary data
clear essTimestamp EVI eviData

% Listen to news events in realtime
%[status,lhandle] = realtime(c,symbol,@(~,evt)rpExampleListener(evt,{'ENTITY_NAME','GROUP','ESS'}));