The 一目均衡表 Ichimoku Kinko Hyo [cloud chart] consists of the following chart lines added to a candlestick chart:
転換線 Tenkan-sen [conversion line]: the mid-point of the highest high and lowest low for the past 9 periods (including the current period)
基準線 Kijun-sen [base line]: the mid-point of the highest high and lowest low for the past 26 periods (including the current period)
先行スパン 1 Senkou span A [leading span A]: the mid-point of Tenkan-sen and Kijun-sen plotted ahead 26 periods (including the current period)
先行スパン 2 Senkou span B [leading span B]: the mid-point of the highest high and lowest low for the past 52 periods (including the current period), plotted ahead 26 periods (including the current period)
遅行スパン Chikou span [lagging span]: the current period closing price plotted behind 26 periods (including the current period)
The 雲 kumo [cloud] is the area bounded by Senkou span A and Senkou span B (usually shaded on a chart).
Ichimoku Kinko Hyo can be translated as ‘one-glance equilibrium chart’. It is designed to allow the price action and market structure of financial securities to be determined visually ‘at-a-glance’.
For example in a strongly upwards-trending market, the candlesticks would be above the Tenkan-sen, which would be above the Kijun-sen, which in turn would be above the cloud, and the Chikou span may not have anything above it.
The lines and the cloud represent dynamic support and resistance zones relative to the price candles. Generally, the thicker the cloud, the tougher the support/resistance. In our previous example, if the price now reverts downwards, it can expect support first at the Kijun-sen, then the Tenkan-sen and finally the cloud itself.
When the price enters the cloud, i.e. it is between the cloud base and cloud top, it is an important area to gauge whether there is sufficient momentum for the price to break through the cloud or whether the cloud eventually provokes a reversal.
More subtle interpretations involve the Chikou span in particular and its action in relation to the cloud lines as well as the candles.
It is outside the scope of this vignette to provide a full tutorial on the use of Ichimoku Kinko Hyo.
Ichimoku analysis is the latest refinement in candlestick charting techniques, which also originated from Japan back in the 18th century. Actually developed during the mid-20th century, it gained popularity especially from the late 1990s onward, and is now used on trading floors worldwide.
The ichimoku time periods have traditionally been calculated as 9, 26 and 52 based on manual data analysis performed in Japan in a pre-computer age where there was a 6-day working week resulting in 26 average trading days in a month. Although this bears little relevance to the current day, the use of these time periods has persisted as an ‘industry norm’ or ‘accepted practice’. To use other periods would be meaningless in a sense as everyone uses these parameters and ‘market psychology’ can and often does create its own realities, independent of any fundamentals.
However, there is no reason for the technique not to evolve, and to reflect changing trading realities perhaps other parameters will become more relevant in the collective psychology. For this reason, the length of these periods can be freely set in the ‘ichimoku’ package. However please do so only with a strong sense of caution and note that using other periods invalidates the traditional interpretations of Ichimoku Kinko Hyo.
Finally, the use originated with daily candlesticks, and the most valid interpretation remains for daily data. However, it is equally used today for both shorter intra-day, e.g. 4-hour or hourly, and longer, e.g. weekly or monthly, charts.
library(ichimoku)
ichimoku works with data frames and tabular data, and interfaces well with other R packages providing financial price data. The ichimoku()
function is able to handle as input ‘xts’, ‘data.frame’, ‘data.table’, ‘tibble’, ‘ArrowTabular’, ‘matrix’, and possibly other ‘data.frame’ compatible objects. For further details see the section file formats.
# ichimoku is designed to interface well with other packages, for example:
<- ichimoku(quantmod::getSymbols("C")) cloud
ichimoku also has functions to return data for major currencies, metals, commodities, government bonds and stock indices directly from the OANDA fxTrade API. Please refer to the OANDA vignette.
The requirement on the input data is minimal, but it should contain an unambiguous date-time index and also at least High/Low/Close (HLC) price values for each time period. This is as the calculations of the cloud lines use variously the closing price as well as the midpoint between the highs/lows. It is not possible to calculate the ichimoku cloud correctly using just a single price per time period.
Full Open/High/Low/Close (OHLC) data should be used where available as this also allows accurate plotting of the candlesticks. If only HLC price data is available, ichimoku will take the opening price to be the closing price of the previous period, which may or may not be a good assumption depending on the type of security.
# Simulated OHLC price data is assigned to data frame 'TKR':
<- sample_ohlc_data
TKR head(TKR)
#> time open high low close
#> 1 2020-01-02 123.0 123.1 122.5 122.7
#> 2 2020-01-03 122.7 122.8 122.6 122.8
#> 3 2020-01-05 122.8 123.4 122.4 123.3
#> 4 2020-01-06 123.3 124.3 123.3 124.1
#> 5 2020-01-07 124.1 124.8 124.0 124.8
#> 6 2020-01-08 124.8 125.4 124.5 125.3
ichimoku recognises data in columns containing “open”, “high”, “low” and “close”, which do not have to be nicely-formatted as in the example above and could also contain other text such as the ticker name. For further details see the section data validation.
Note: aim to retrieve as much data as possible, or slightly further back than the period being analysed. Run ichimoku()
on the full dataset and then subset the data window when plotting to ensure that there is a full ichimoku cloud for all of the desired period. This is preferable to first subsetting the data and then calculating the ichimoku cloud as, given the cloud lines need several values to be calculated, there will be NAs and hence no cloud at the start of the data.
ichimoku()
is the main function of the ichimoku package. It takes the input data object and returns an ichimoku object, which inherits the classes ‘ichimoku’, ‘xts’ and ‘zoo’.
Optional arguments:
ticker
a ticker to identify the instrument, otherwise this is set to the name of the input objectperiods
[default c(9, 26, 52)] a vector defining the length of periods used for the cloud. This parameter should not normally be modified as using other values would be invalid in the context of traditional Ichimoku analysis...
additional arguments, for instance ‘holidays’, passed along to tradingDays()
for calculating the future cloud on daily dataAn ichimoku object is returned by calling ichimoku()
on the data:
<- ichimoku(TKR)
cloud
print(cloud[100:110,], plot = FALSE, digits = 4)
#> open high low close cd tenkan kijun senkouA senkouB chikou
#> 2020-04-27 122.7 122.7 121.8 122.4 -1 121.0 123.9 125.7 124.8 135.1
#> 2020-04-28 122.4 122.6 121.1 121.9 -1 121.0 123.9 125.7 124.8 135.6
#> 2020-04-29 121.9 123.7 121.7 123.3 1 121.4 123.8 125.7 124.8 134.5
#> 2020-04-30 123.3 124.0 123.0 124.0 1 121.5 123.8 125.7 124.8 134.3
#> 2020-05-01 124.2 124.3 124.0 124.1 -1 121.8 123.6 126.0 124.8 135.9
#> 2020-05-03 124.1 124.1 123.4 123.9 -1 122.2 123.6 126.5 124.8 135.2
#> 2020-05-04 123.9 124.7 123.7 124.5 1 122.9 123.6 126.6 124.8 135.7
#> 2020-05-05 124.5 124.7 123.9 124.2 -1 122.9 123.6 126.2 124.8 135.4
#> 2020-05-06 124.2 125.2 124.0 124.7 1 123.2 123.6 126.1 124.8 135.7
#> 2020-05-07 124.7 129.8 124.7 129.6 1 125.5 124.5 125.7 124.8 135.6
#> 2020-05-08 129.9 130.6 129.9 130.2 1 126.2 124.8 125.6 124.8 136.2
#> cloudT cloudB
#> 2020-04-27 125.7 124.8
#> 2020-04-28 125.7 124.8
#> 2020-04-29 125.7 124.8
#> 2020-04-30 125.7 124.8
#> 2020-05-01 126.0 124.8
#> 2020-05-03 126.5 124.8
#> 2020-05-04 126.6 124.8
#> 2020-05-05 126.2 124.8
#> 2020-05-06 126.1 124.8
#> 2020-05-07 125.7 124.8
#> 2020-05-08 125.6 124.8
A section (rows 100 to 110) of the ichimoku object is shown above. Note that print is called setting ‘plot = FALSE’ to return the data only. ichimoku objects employ a custom S3 print method which by default plots the cloud chart in the graphical device as well as returning the data to the console.
# to view chart as well as data, simply issue:
cloud
index(object)
- date-time index [POSIXct]object$open
- opening price$high
- high price$low
- low price$close
- closing price$cd
- candle direction (-1 = down, 0 = flat, 1 = up)$tenkan
- Tenkan-sen$kijun
- Kijun-sen$senkouA
- Senkou span A$senkouB
- Senkou span B$chikou
- Chikou span$cloudT
- cloud Top (max of senkouA, senkouB)$cloudB
- cloud Base (min of senkouA, senkouB)attributes(object)$periods
- parameters used to calculate the cloud [integer vector of length 3]$periodicity
- periodicity of the data in seconds [numeric]$ticker
- instrument identifier [character]The ticker is set by default to the input object name or can be overridden by specifying the ‘ticker’ argument to ichimoku()
.
ichimoku()
may be used on an ichimoku object to re-calculate the cloud values using the price data contained within. If ‘ticker’ is specified as an argument, this will overwrite the ticker stored in the original ichimoku object.
Calling ichimoku()
on an ichimoku object containing a strategy will return the ichimoku object to its original state without the strategy. See the strategies vignette for information on strategies.
As an ichimoku object inherits the ‘xts’ and ‘zoo’ classes, all the existing methods for these classes should work seamlessly. For convenience, the following functions are re-exported by ichimoku:
from ‘zoo’:
index()
to extract the index of an ichimoku objectcoredata()
to extract the columns of an ichimoku object as a numeric matrix (without the date index)from ‘xts’:
xts()
to create an ‘xts’ object from data and a date-time index, use xts(data, index)
If modifications have been made, call ichimoku()
on the modified object to re-create the ichimoku object according to the correct specification.
For additional functionality, you may consider loading the ‘xts’ package to access a wide range of methods available for ‘xts’ objects, for example changing the periodicity of the data.
When calculating the future cloud, ichimoku()
makes a call to the tradingDays()
helper function to ensure that future dates fall on trading days (i.e. not weekends or holidays). By default, New Year’s and Christmas day are defined as holidays as these are for all purposes universal across markets. These defaults should be acceptable for general use.
However, if a particular strategy relies on the specific timing of the future cloud, and for the market under consideration other holidays are non-trading days, additional custom holidays may be defined via a ‘holidays’ argument to ichimoku()
which is then passed on to the tradingDays()
function.
If the relevant market trades on a 24/7 basis with no non-trading days, the parameter noholidays
can specified. This will bypass the logic of tradingDays()
and include all dates for calculating the future cloud.
# Holidays can be specified directly via a vector of dates:
ichimoku(TKR, holidays = c("2020-01-13", "2020-02-11", "2020-02-24"))
# Or via a functions that returns a vector of dates (e.g. from the 'timeDate' package):
ichimoku(TKR, holidays = timeDate::holidayLONDON())
ichimoku(TKR, holidays = timeDate::holidayNYSE())
# For a market that trades 24/7:
ichimoku(TKR, noholidays = TRUE)
ichimoku offers the choice of 2 visualization systems: static (default) and interactive (reactive charts using R Shiny).
The default plot function produces static plots, which have the advantage of being easily exportable to pdf or image formats in high resolution.
ichimoku implements a custom S3 method for ggplot2’s autoplot()
function for objects of class ‘ichimoku’. Although autoplot can be called directly on an ichimoku object, it is more convenient to call plot()
instead, which prints the output of autoplot.
plot(cloud)
As the implementation is via ggplot2, the user is able to further amend or customise the resulting plot using any ggplot2 methods. The most straightforward method would be to assign the output of plot()
to a ‘ggplot’ object, after which further elements or layers can be added or modified using ggplot2’s +
operator.
# Example code for incrementally updating ggplot2 layers:
<- plot(cloud)
plot + ggplot2::theme_classic() plot
The ‘ggplot’ object can be further used to produce an interactive chart that can be embedded in HTML output created by R Markdown, by using the ‘plotly’ package as per the below:
# For a plotly interactive plot:
::ggplotly(plot) plotly
Interactive plots require the ‘shiny’ package to be installed. If Shiny is not available, ichimoku will issue an informational message, but not install the package automatically as it is recognised that Shiny may not be available in all environments.
To produce an interactive plot, use ichimoku’s iplot()
function. An R Shiny app will be launched, allowing full further customisation of the chart interactively, including selecting the time window etc.
In a live analysis environment, as opposed to creating charts for reports, it can be preferable to work with interactive plots. This is due to the ease of being able to customise the chart coupled with easy access to the data provided by the cursor infotip.
A plot with default parameters is shown above, but the plot functions contain built-in customisations to allow for most envisioned use cases. The example below demonstrates the arguments that can be supplied to customise the plot.
plot(cloud, window = "2020-05-01/2020-11-02", ticker = "TKR Co.", message = "一目均衡表", theme = "dark")
The following arguments for customisation are shared across plot()
and iplot()
:
window
(optional) indispensable in a proper workflow. ichimoku()
is run on a larger dataset than that of interest and at the visualization stage the data is subset to the window of interest. Supply as an ISO-8601 compatible range string in the format used for ‘xts’ objects, for example the range ‘2020-02-15/2020-08-15’ or ‘2020-02-15/’ (from 15 Feb 2020) or ‘/2020-08’ (until end-Aug 2020) or simply ‘2020’ to select all of the year 2020ticker
(optional) used to supply a different ticker to that stored in the ichimoku object, or alternatively a longer-form name or other text that will appear in the chart headingmessage
(optional) used to specify a chart message to display under the titletheme
[default ‘original’] the following themes are also available: ‘dark’, ‘solarized’ and ‘mono’strat
[default TRUE] if true, the periods for which a strategy results in a market position will be shaded (if the ichimoku object contains a strategy) with the strategy printed as the chart message (if a message is not already specified). See the strategies vignette for more information on working with strategies.plot()
takes additional parameters as follows:
...
additional arguments passed along to the print method for ‘ggplot’ objects.iplot()
takes the following additional parameters:
...
additional parameters passed along to the ‘options’ argument of shiny::shinyApp()
.launch.browser
[default TRUE] If TRUE, the system’s default web browser will be launched automatically after the app is started. The value of this argument can also be a function to call with the application’s URL. To use the default Shiny viewer in RStudio, please specify getOption("shiny.launch.browser")
.After completing an analysis, the resulting objects can be stored directly to disk. The function archive()
provides seamless translation between ichimoku objects in an R session with binary files stored in the Apache Arrow IPC file format.
archive()
for write operations will take 2 arguments: the ichimoku object to be written, and the file path/name of the file to be stored. A confirmation is printed to the console that the file has been written.
archive()
for read operations takes a single argument: the file path/name of the file to be read. The return value of the function can be assigned to an object. A confirmation is printed to the console once the file has been read.
Data integrity validation is performed by the cryptographic-grade sha256 hashing algorithm from the ‘openssl’ package. If ‘openssl’ is not available, the archive function still works in all respects but without the validation capability.
When an archive is written, a representation of the ichimoku object is hashed and stored in the archive. The sha256 hash value is printed to the console as confirmation.
When an archive is read back, the sha256 hash of the restored object is checked against the hash of the original stored in the archive. If identical, a ‘data verified’ message is printed to the console along with the matching sha256 hash.
Apache Arrow provides the backend to the archive functions and requires the ‘arrow’ package to be installed. Apache Arrow is a high-performance, standardised, and language-independent columnar memory format. This means that the Arrow files created by ichimoku can equally be accessed by programs utilising Arrow bindings in all major languages including C, C++, Java, Python, etc.
Note: the attributes of the ichimoku object are stored in the ‘r’ field of the Arrow schema metadata. This allows archived objects to be reconstructed faithfully, however this data is typically only read by R and ignored by other clients.
ichimoku()
is a generic function that provides S3 methods for objects of class ‘xts’, ‘data.frame’, ‘ArrowTabular’ and ‘matrix’. Other popular formats such as ‘data.table’ and ‘tibble’ that also inherit the class ‘data.frame’ should also work with ichimoku()
.
ichimoku has been designed to be fully pipeable and interfaces well with other R packages that return financial data. As an example, the quantmod::getSymbols()
function from the ‘quantmod’ package currently exhibit non-standard R behaviour which assigns the data into an object but returns a text string containing the name of the object. ichimoku is able to handle this automatically such that a chart can be created without the need to save intermediate objects:
# Using R 4.1's new pipe operator:
::getSymbols("C") |> ichimoku() |> plot()
quantmod# Or equally using the 'magrittr' pipe:
::getSymbols("C") %>% ichimoku() %>% plot() quantmod
For reading data in the ‘json’ format, which is commonly returned by web APIs, the fromJSON()
function from the ‘jsonlite’ package is fairly ubiquitous. The function takes json strings so any raw vectors should first be wrapped in rawToChar()
. ‘jsonlite’ is a dependency of ichimoku.
If an external data file employs a custom delimited format, the ‘data.table’ package contains the fread()
function, which is often successful on default settings. Otherwise, read_delim_arrow()
from the ‘arrow’ package may provide an even more performant alternative.
For csv files, read_csv_arrow()
from the ‘arrow’ package can be a more performant choice than using fread()
from ‘data.table’.
The ‘arrow’ package also contains the read_feather()
and read_parquet()
functions for reading in Apache Arrow IPC and Parquet file formats as either a ‘data.frame’ or Arrow Table, either of which can be handled directly by ichimoku()
.
Alternatively, the ‘datapasta’ package allows data copied from tables on webpages or in spreadsheets etc. to be pasted into R as a dataframe or tibble.
ichimoku performs the following data validation steps before attempting to compute the cloud values. Failure at any step causes ichimoku()
to halt.
Searches for HLC price data in columns with names containing ‘high’, ‘low’ and ‘close’ (not case-dependent) respectively
Checks that the dataset is longer than the medium cloud period. If this is not the case then none of the cloud lines can be calculated
Searches for opening price data in a column with name containing ‘open’ (not case-dependent)
There may however still be other issues with the input data that prevent cloud values from being computed, not handled explicitly by ichimoku()
. For example, if:
The date-time index is in a headerless column, or in a column where the name does not contain ‘index’, ‘date’ or ‘time’ (not case-dependent). Please rename the column to ‘index’ in such cases
The correct date-time index is in the row names, or index of an ‘xts’ object, but there are also columns that contains the word ‘index’, ‘date’ or ‘time’. Please rename the columns that do not serve as the date-time index so that the correct date-time index can be detected
There is more than one column that contains the word ‘index’, ‘date’ or ‘time’. Please either rename the columns that do not serve as the date-time index, or move the correct date-time column ahead of the other columns so that it is picked up first
HLC price data is contained in headerless columns or in columns labelled, for example, ‘Op’, ‘Hi’, ‘Lo’, ‘Cl’. Please rename the columns ‘open’, ‘high’, ‘low’ and ‘close’ in such cases
There are NA values within the price data. This will affect the algorithm calculating the cloud lines in the window immediately following such NA values. Please check the data and manually correct NA values before invoking ichimoku()
ichimoku()
on previously-created objects to re-create them according to the new specification (data is preserved)The dependency on other packages is designed to be minimised to the extent possible. ichimoku currently has the following external package dependencies:
Compile time:
Optional:
Sasaki, H. 佐々木 英信 (1996), 一目均衡表の研究 [ichimoku kinkouhyou no kenkyuu]. Tokyo, Japan: Toushi Radar.
Gao, C. (2021), ichimoku: Visualization and Tools for Ichimoku Kinko Hyo Strategies. R package version 1.0.0, https://CRAN.R-project.org/package=ichimoku.