Stock Market and US elections

Posted on 19th September 2012 in r-bloggers, Research

We made a very simple R file that historically gathers the period before and after the US elections. The inexperienced user has the ability to set the tickers of asset she wants to study and the look-back and look-forward periods. Most of the functions are wrapped up and can be found in a separate file here http://www.quantf.com/download2/US-elections-procs.R , so that all experienced users can open and edit the source file.

Looking at SP-500, NASDAQ-100 and RUSSELL-2000 graphs we see that in 1980, 1984, 1988, 1992, 2000, 2004 and 2008 there was rise in the market some weeks before the elections (something similar happened last week due to the QE Fed announcement). Then we have an decrease and as we approach to the elections the market goes up again. A similar decrease started last Friday at the end of day and continued on Monday and Tuesday.

Bottomline: pre-elections periods can be tricky so have it in mind and be prepared!

 

# Written by D. Thomakos and F. Papailias
#
# Contact Details: papailias@quantf.com
# dimitrios.thomakos@gmail.com, thomakos@quantf.com
#
# All material is provided for use as is, with no guarrantees, either expressed or implied.
# Copyright (C) under the authors' names Papailias, Fotis and Thomakos, Dimitrios for both
#
#-------------------------------------------------------------------------#
# Quantitative Finance & Technical Trading #
# http://www.quantf.com #
#-------------------------------------------------------------------------#
# 
# PLEASE MAINTAIN THIS HEADER IN ALL COPIES OF THIS FILE THAT YOU USE
# Remove everything to start from scratch
rm(list=ls(all=TRUE))
#------------------------ USER INPUT -----------------------------#
# Select the assets you need. Here we use SP-500, NASDAQ-100, RUSSELL-2000, TNA, TZA, FAZ, FAS
tickers.all <- c("^GSPC", "^NDX", "^RUT", "SPY")
ndays <- 60 # calendar days
nrows <- 60 # trading days
source("http://www.quantf.com/download2/US-elections-procs.R")
for(i in seq(1, length(tickers.all), 1))
{
 wrap.n.plot(prices, tickers.all[i], dates, ndays, nrows, ele)
}



		
		
		


													
comments: 0 »

Ichimoku Clouds R Code Trading

Posted on 9th April 2012 in forex-bloggers, r-bloggers, Research

Download the full program here

Here you can find an R Code for Ichimoku Clouds analysis and trading.

Have fun!

 

# The function for computing the Ichimoku cloud
ichimoku <- function(data,pars)
{

# REMEMBER THAT THE DATA SHOULD BE IN ORDER
#
# HIGH, LOW and CLOSE
#
# ==========================================

# Number of observations
Nobs <- NROW(data)

# Get the three parameters
p1 <- pars[1]
p2 <- pars[2]
p3 <- pars[3]

# The maximum of these should be p3, check
if ((p1 > p2) | (p1 > p3) | (p2 > p3))
{
stop(“parameters should enter in ascending order”)
}
# Set the max
maxp <- p3

# You will leave out maxp observations
cloud.lines <- matrix(0,nrow=Nobs-maxp,ncol=5)
colnames(cloud.lines) <- c(“Tenkan”,”Kijun”,”SenkouA”,”SenkouB”,”Chikou”)

# Run a loop to make the computations
for (i in seq(maxp+1,Nobs,1))
{
# Compute the cloud lines
tenkan <- (max(data[seq(i-p1,i,1),1])+min(data[seq(i-p1,i,1),2]))/2
kijun <- (max(data[seq(i-p2,i,1),1])+min(data[seq(i-p2,i,1),2]))/2
senkouA<- (tenkan+kijun)/2
senkouB<- (max(data[seq(i-p3,i,1),1])+min(data[seq(i-p3,i,1),2]))/2
chikou <- data[i,3]

# Save in appropriate places
cloud.lines[(i-maxp),] <- c(tenkan,kijun,senkouA,senkouB,chikou)
}

# OK, now align them correctly: SenkouA and SenkouB are moved p2 periods forward
# while Chikou is moved p2 periods backward…
A1 <- rbind(cloud.lines[,1:2],matrix(NA,p2,2))
A2 <- rbind(matrix(NA,p2,2),cloud.lines[,3:4])
A3 <- c(cloud.lines[(p2+1):(Nobs-maxp),5],matrix(NA,2*p2,1))
new.cloud.lines <- cbind(A1,A2,A3)
colnames(new.cloud.lines) <- colnames(cloud.lines)

# Align the data as well
new.data <- rbind(data[(maxp+1):Nobs,],matrix(NA,p2,3))
colnames(new.data) <- colnames(data)

# OK, return everything
return(list(data=new.data,cloud.lines=new.cloud.lines))
}

 

# Set the ichimoku parameters
pars <- c(50,100,120)

out <- ichimoku(x,pars)

comments: 0 »

R-Code Yahoo Finance Data Loading

Posted on 17th January 2012 in r-bloggers, Research

Here is an R script that downloads Yahoo Finance Data without the need of additional packages/libraries.

In the .zip file is the code with an example on how to use it.

Download the code here: R Code - Yahoo Data Loading

You can also find it under the “Downloads” Section of our site.

# Function and example code for loading finance data from Yahoo
# without the need of any additional package.
#
# Written by Fotis Papailias & Dimitrios Thomakos on Dec. 31, 2011
# Contact Details: papailias@quantf.com
#                  dimitrios.thomakos@gmail.com, thomakos@quantf.com
#
# All material is provided for use as is, with no guarrantees, either expressed or implied.
# Copyright (C) under the authors' names Papailias, Fotis and Thomakos, Dimitrios for both
#
#-------------------------------------------------------------------------#
#             Quantitative Finance & Technical Trading                    #
#                     http://www.quantf.com                               #
#-------------------------------------------------------------------------#
#
# PLEASE MAINTAIN THIS HEADER IN ALL COPIES OF THIS FILE THAT YOU USE

###############################################################################################
# Main Function
#
# Input
# -----
#   tickers (text strings)
#   start.date (dates)
#   end.date (dates)
#
# Output
# -------
# 6 Double Matrices: Open, High, Low, Close, Volume, Adj. Close
###############################################################################################

data.loading <- function(tickers, start.date, end.date)
{
  # Change the locale
  sl <- Sys.setlocale(locale="US")

  # Create the universe of dates
  all.dates <- seq(as.Date(start.date), as.Date(end.date), by="day")
  all.dates <- subset(all.dates,weekdays(all.dates) != "Sunday" & weekdays(all.dates) != "Saturday")
  all.dates.char <- as.matrix(as.character(all.dates))

  # Create sparse matrices
  open <- matrix(NA, NROW(all.dates.char), length(tickers))
  hi <- open
  low <- open
  close <- open
  volume <- open
  adj.close <- open

  # Name the rows correctly
  rownames(open) <- all.dates.char
  rownames(hi) <- all.dates.char
  rownames(low) <- all.dates.char
  rownames(close) <- all.dates.char
  rownames(volume) <- all.dates.char
  rownames(adj.close) <- all.dates.char

  # Split the start and end dates to be used in the ULR later on
  splt <- unlist(strsplit(start.date, "-"))
  a <- as.character(as.numeric(splt[2])-1)
  b <- splt[3]
  c <- splt[1]

  splt <- unlist(strsplit(end.date, "-"))
  d <- as.character(as.numeric(splt[2])-1)
  e <- splt[3]
  f <- splt[1]

  # Create the two out of the three basic components for the URL loading
  str1 <- "http://ichart.finance.yahoo.com/table.csv?s="
  str3 <- paste("&a=", a, "&b=", b, "&c=", c, "&d=", d, "&e=", e, "&f=", f, "&g=d&ignore=.csv", sep="")

  # Main loop for all assets
  for (i in seq(1,length(tickers),1))
    {
      str2 <- tickers[i]
      strx <- paste(str1,str2,str3,sep="")
      x <- read.csv(strx)

      datess <- as.matrix(x[1])

      replacing <- match(datess, all.dates.char)
      open[replacing,i] <- as.matrix(x[2])
      hi[replacing,i] <- as.matrix(x[3])
      low[replacing,i] <- as.matrix(x[4])
      close[replacing,i] <- as.matrix(x[5])
      volume[replacing,i] <- as.matrix(x[6])
      adj.close[replacing,i] <- as.matrix(x[7])
  }

  # Name the cols correctly
  colnames(open) <- tickers
  colnames(hi) <- tickers
  colnames(low) <- tickers
  colnames(close) <- tickers
  colnames(volume) <- tickers
  colnames(adj.close) <- tickers

  # Return the ouput
  return(list(open=open, high=hi, low=low, close=close, volume=volume, adj.close=adj.close))
}
comments: 10 »

Improved Moving Average using intra-day EUR/USD FOREX

Posted on 10th December 2011 in forex-bloggers, r-bloggers, Research

(Fotis, Reason for Edit: Sample Dates Added)

Hi everyone,

Here we present the graphical illustrations from two cases that our improved moving average method provides better results compared to the rest.

You can find the R-code here (is the same version).

In both cases we are using the Exponential Moving Average.  The figure on the left illustrates EMA(20,60) as fast and slow weights, whereas the figure on the right is using the ouput of an EMA(45,120).

Green line is the cumulative return using the method we suggest in the papers, red line is the method we suggest in the papers when once exit one can re-enter (as long as the current price is greater compared to the last entry price) , the black line is the cumulative return using the standard EMA and the blue line is the cumulative return of the Buy & Hold strategy. (for more information on how to read the graphs click here)

Here you can download the full set of experiment where we use a 0% exit threshold (as above), a 3% threshold and a 5% threshold.

If you want to see applications in more currencies or if you have in mind another couple of MA weights you ‘d like to see in action, reply to this post with your suggestions.

The exact number of trades for each method follows.

GDE Error: Unable to load profile settings

Download here the .pdfs with all figures.

EMA(20, 60) (9.6 MB)

EMA(45, 120) (9.4 MB)

 

The data is minute-by-minute, start on Oct. 20, 2012 at 09:00 and ends on Dec. 7, 2012 at 12:07. Sample size is 50482 observations. It was collected using Bloomberg Services.

I am thankful to the School of Economics and Finance, Queen Mary University of London, for providing me all the necessary tools needed for my research.

comments: 0 »

Improved Moving Average Code is available for download!

Posted on 7th December 2011 in forex-bloggers, r-bloggers, Research

Hi everyone,

in the last few days we have received great feedback from you. Due to increasing demand we have made a short version of the original code available for personal use. Please let us know of your comments, thoughts and suggestions.

http://www.quantf.com/ima-code

The main function that does most of the things follows. Here is an output on SPY.

The green line denotes our improved rule in its original form we have used in the papers.

Graphs and full downloads can be found in the above link.

[sourcecode language="r"]</pre>
<pre class="brush: python; gutter: true; first-line: 1"># Explicit code for improved MA signals
ma.trading.improved {
# Keep attributes for later use, need next day as well,
# although this is done for convenience, it does not
# have to be the next trading day and its not used for
# anything thereafter…
dates

# Pass the data as a matrix; this strips all other attributes
x

# Select correctly the closing price if OHLC is loaded
if(NCOL(x) &gt; 1) x

# Cross-checks
# Fotis ok, Dec. 07, 2011
if ((k1 k2) &amp; (k2 &gt; 0))) { stop("k1,k2 must both be positive and k1 &lt; k2") }

# Full sample
Nobs

# Daily return
ret

# Initialize moving average values
ma.values

# Initialize signal storage
signals.ma1 signals.ma2 signals.mac signals.im1 signals.im2 signals.imc signals.iv1 signals.iv2signals.ivc

# Initialize markers of entries for improved MA
mark1 mark2 markc pentry1 pentry2pentryc

# Do things via a standard loop to maintain consistency
for (i in seq(k2,Nobs,1)) # fotis change/edit
{
# Compute the moving averages # fotis change/edit
if (mtype == "simple")
{
ma1ma2

# Save the MA values # fotis change/edit
ma.values[i,]

}
if (mtype == "weighted")
{
ma1ma2

# Save the MA values # fotis change/edit
ma.values[i,] }

# fotis add, Dec. 07, 2011
if (mtype=="exponential")
{
# Get the starting signal to be used in the EMA calc., fotis
if(i==k2)
{
ma1ma2

# Save the MA values # fotis change/edit
ma.values[i,] }
else
{
ma1ma2

# Save the MA values
ma.values[i,] }
}

# Get the last observed price
plast

# Version AB of improved MA: once you exit you wait for next signal;
# exiting is controlled by the exit threshold
#
# Stay
# Fotis ok, Dec. 07, 2011
if ((mark1 &gt; 0) &amp; (pentry1 &gt; 0) &amp; (plast &gt;= pentry1)) { signals.im1[i+1] if ((mark2 &gt; 0) &amp; (pentry2 &gt; 0) &amp; (plast &gt;= pentry2)) { signals.im2[i+1] if ((markc &gt; 0) &amp; (pentryc &gt; 0) &amp; (plast &gt;= pentryc)) { signals.imc[i+1] # Exit
# Fotis check, Dec. 06, 2011
if ((pentry1 &gt; 0) &amp; (plast &lt; pentry1*(1-exitt))) { signals.im1[i+1] if ((pentry2 &gt; 0) &amp; (plast &lt; pentry2*(1-exitt))) { signals.im2[i+1]if ((pentryc &gt; 0) &amp; (plast &lt; pentryc*(1-exitt))) { signals.imc[i+1]

# Version BB of improved MA: once you exit you can re-enter when above the current
# entry price; exiting is controlled by the exit threshold
#
# Fotis ok, Dec. 07, 2011
# Stay
if ((pentry1 &gt; 0) &amp; (plast &gt;= pentry1) &amp; (plast &gt; ma1)) { signals.iv1[i+1] if ((pentry2 &gt; 0) &amp; (plast &gt;= pentry2) &amp; (plast &gt; ma2)) { signals.iv2[i+1] if ((pentryc &gt; 0) &amp; (plast &gt;= pentryc) &amp; (ma1 &gt; ma2)) { signals.ivc[i+1] # Exit
# Fotis ok, Dec. 07, 2011
if ((pentry1 &gt; 0) &amp; (plast &lt; pentry1*(1-exitt))) { signals.iv1[i+1] if ((pentry2 &gt; 0) &amp; (plast &lt; pentry2*(1-exitt))) { signals.iv2[i+1]if ((pentryc &gt; 0) &amp; (plast &lt; pentryc*(1-exitt))) { signals.ivc[i+1]

# Here are the standard MA signals
if (plast &gt; ma1) { signals.ma1[i+1] if (plast &gt; ma2) { signals.ma2[i+1]if (ma1 &gt; ma2) { signals.mac[i+1]

# Here are the initializations of the improved MAs, both versions
# Fotis ok, Dec. 07, 2011
if (signals.ma1[i+1] &gt; signals.ma1[i]) { pentry1 if (signals.ma2[i+1] &gt; signals.ma2[i]) { pentry2if (signals.mac[i+1] &gt; signals.mac[i]) { pentryc

}

# Bind together and correctly aling things and returns
bind1 signals.im1,signals.im2,signals.imc,signals.iv1,signals.iv2,signals.ivc,c(ret,NA,NA))
bind2 matrix(c(ret,NA,NA),nrow=Nobs+1,ncol=9),c(ret,NA,NA))
colnames(bind1)colnames(bind2)

bind3# Fotis ok, Dec. 07, 2011

# Convert to zoo objects
bind1 bind2bind3

# Done!
return(list(values=bind1,returns=bind2,cumulative=bind3))
}
[/sourcecode]

comments: 2 »