<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
<channel>
<title>QuantShare</title>
<description>Trading software, sharing server and social network</description>
<link>http://www.quantshare.com/</link>
<copyright>Corporate Trading</copyright>




     <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/QuantShare" /><feedburner:info uri="quantshare" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
        <title> Learn how to create your own technical analysis indicators</title>
        <description>Today, we will show you how to implement custom functions in QuantShare by creating two popular trading indicators. &lt;br /&gt;
Custom functions can be implemented using C# programming language. The result is a function that can be used in the QuantShare programming language. You know, the easy language you use when creating charts, composites, trading systems...&lt;br /&gt;
&lt;br /&gt;
There are several reasons why someone would want to create a technical analysis indicator using C#. Here are few of them:&lt;br /&gt;
&lt;br /&gt;
- To have one single function to use instead of several lines of code&lt;br /&gt;
- To create advanced indicators that cannot be created using QuantShare programming language&lt;br /&gt;
- To protect the source code of your indicator&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Simple Moving Average&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The simple moving average (SMA) is a very popular trend following indicator that shows the direction of a trend. &lt;br /&gt;
&lt;br /&gt;
The SMA indicator is already built-in QuantShare, however, we wanted to show you how to implement it from scratch using the custom indicators tool.&lt;br /&gt;
&lt;br /&gt;
The SMA formula is as follows: Average of last N-bar values&lt;br /&gt;
&lt;br /&gt;
To create a new custom indicator:&lt;br /&gt;
- Select "Tools -&gt; Create Functions".&lt;br /&gt;
- Click on "Add", type the function name "SMA1" then click on "Save".&lt;br /&gt;
&lt;br /&gt;
Note that we cannot use "SMA" as a name for our function because this keyword is reserved (Remember that there is already a built-in function called "SMA").&lt;br /&gt;
&lt;br /&gt;
After you create the indicator/function, you can type the C# script in the right panel. Below that panel, you can define the parameters that will be passed to the function. In our case (Simple Moving Average), we only need one parameter, which is the lookback period.&lt;br /&gt;
&lt;br /&gt;
Let me show you now the C# code that you must copy in order to create the SMA indicator:&lt;br /&gt;
&lt;br /&gt;
- First of all, add one parameter (set "Period" as name)&lt;br /&gt;
- Type the following code:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;int p = (int)Period[0]; // All parameters are passed as vectors. Here we are passing a numeric value and thus we can get that value by getting the first element of the "Period" vector&lt;br /&gt;
VectorD close = cFunctions.Close; // Gets the close series&lt;br /&gt;
for(int i=p-1;i &lt; result.Length;i++) // Loops through each trading bar&lt;br /&gt;
{&lt;br /&gt;
	double sum = 0;&lt;br /&gt;
	for(int j=i-p+1;j &lt; =i;j++) // Loops through the last "p" elements of each trading bar&lt;br /&gt;
	{&lt;br /&gt;
		sum = sum + close[j]; // Sums previous close values&lt;br /&gt;
	}&lt;br /&gt;
	result[i] = sum / p; // Calculates the average of the past close values (SMA)&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each line of code is followed by a brief description that explains what exactly this line does.&lt;br /&gt;
Click on the "Save" button to compile and save your indicator.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Percentage Price Oscillator&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Percentage price oscillator is a momentum indicator that simply calculates the difference between two moving averages in percentage.&lt;br /&gt;
&lt;br /&gt;
The PPO formula is as follows: (Short Exponential Moving Average - Long Exponential Moving Average) / (Long Exponential Moving Average)&lt;br /&gt;
&lt;br /&gt;
In QS programming language, PPO (9, 26) can calculated as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;ppo2 = (ema(9) - ema(26)) / ema(26);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
But because we do want to replace this line by something like (&lt;span style="color:#1C74A8"&gt;ppo2 = ppo(9, 26);&lt;/span&gt;), let us create a custom function to calculate the PPO indicator.&lt;br /&gt;
&lt;br /&gt;
As usual, open the "Create Functions" tool and create a new function (PPO1). Do not use "PPO" keyword because the percentage price oscillator is already built-in QuantShare.&lt;br /&gt;
&lt;br /&gt;
Here is the C# formula of the PPO indicator:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;VectorD st = TA.Ema(p1);&lt;br /&gt;
VectorD lt = TA.Ema(p2);&lt;br /&gt;
result = (st - lt) / lt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
You must also add two parameters (below the script editor). &lt;br /&gt;
"p1": Short-term period&lt;br /&gt;
"p2": Long-term period. &lt;br /&gt;
These parameters will be passed to the function and as you can see, they are used to calculate the different exponential moving averages.&lt;br /&gt;
&lt;br /&gt;
In this example, we have used the "TA" class. This class contains several built-in functions and indicators.&lt;br /&gt;
&lt;br /&gt;
We could have implemented the first example (SMA) by simply typing:&lt;br /&gt;
result = TA.Sma(Period);&lt;br /&gt;
&lt;br /&gt;
Note that at any moment, you can use the CONTROL+SPACE shortcut to display the list of available functions/parameters.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to Reference a Custom  Indicator in QuantShare Programming Language&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let us see how to plot a custom indicator in a chart.&lt;br /&gt;
&lt;br /&gt;
- Right click on a chart then select "Create new pane"&lt;br /&gt;
- Right click on the new pane then select "Edit Formula"&lt;br /&gt;
- Type the following formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = ppo1(9, 26); // This is the call the previously created "ppo1" C# function&lt;br /&gt;
plot(a, "PPO", colorBlue);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Click on "Update Graph" to add the PPO indicator to the chart&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to Protect your Source Code&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/2ex_custom_indicators_1.gif" title="Learn how to create your own technical analysis indicators" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
- In "Create Functions" form, click on "Manage" button (Top bar)&lt;br /&gt;
- Select one or several indicator you want to protect/encrypt&lt;br /&gt;
- Select "Tools -&gt; Encrypt checked items" (If you do not see the "Tools" button on the top menu, click on "+" icon to expand the menu)&lt;br /&gt;
- Click "Yes"&lt;br /&gt;
- Enter your password then click on "OK"&lt;br /&gt;
&lt;br /&gt;
Now, each time you select that indicator in "Create Function" control, you will be prompted to enter a password. Otherwise, you will not be able to see the indicator C# code.&lt;br /&gt;
&lt;br /&gt;
Note that even if an indicator is encrypted, you can still use it in your charts, trading systems, composites, watchlists and any other tool.&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/zphpj3aIxdY" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/zphpj3aIxdY/sa-537-learn-how-to-create-your-own-technical-analysis-indicators</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-537-learn-how-to-create-your-own-technical-analysis-indicators</guid>
        <pubDate> Tue, 21 May 2013 11:28:22 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-537-learn-how-to-create-your-own-technical-analysis-indicators</feedburner:origLink></item>  
     <item>
        <title> How to Pick the Best Trend Indicators</title>
        <description>Trend  indicators are primarily used to identify the direction of a security by smoothing the volatility of the price action. These indicators are usually referred to as lagging indicators because their calculation is based on past price data.&lt;br /&gt;
&lt;br /&gt;
The most known trend indicator is the moving average; there are several types of moving averages such as the simple, exponential, double or weighted moving average. But there are also many other trend indicators used by technical analysts. &lt;br /&gt;
&lt;br /&gt;
These technical indicators usually get one or several periods for their internal calculations. Higher period values are used for long-term analysis while low period values are used for short-term analysis.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="https://en.wikipedia.org/wiki/Moving_average" target="_blank"&gt;Moving Average&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
As we previously said, the moving average is the best known indicator to detect trends. It is simply the average of the N-previous bars. &lt;br /&gt;
There are several ways to use the moving average; we could detect the crossover of a moving average with another one, or the crossover of a moving average with the price series...&lt;br /&gt;
&lt;br /&gt;
Example of rules using QuantShare:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;cross(close, sma(25))&lt;br /&gt;
cross(sma(25), sma(50))&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="http://daytrading.about.com/od/indicators/a/DMI.htm" target="_blank"&gt;Directional Movement Index (DMI)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
By comparing today's high and low prices against previous day's high and low, the DMI is a technical indicator that measures the direction and strength of a trend. DMI is based on the theory that says that an uptrend is formed by higher highs and a downtrend is formed by lower lows.&lt;br /&gt;
&lt;br /&gt;
Example of rule using QuantShare:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;cross(Plus_Dm(14), Minus_Dm(14))&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx" target="_blank"&gt;Average Directional Index (ADX)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The average directional index shows the strength of a trend. ADX indicates a moderate strength trend when its value is above 30. It shows a strong trend if the value is above 40. In that case, the trend is likely to continue.&lt;br /&gt;
Note that the ADX is part of the DMI indicator and as we said it shows the strength of a trend but it doesn't indicate the direction of the trend.&lt;br /&gt;
&lt;br /&gt;
Example of rules using QuantShare:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;adx(14) &gt; 40&lt;br /&gt;
adx(14) &gt; 40 and cross(Plus_Dm(14), Minus_Dm(14))&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="http://www.investopedia.com/articles/trading/06/aroon.asp" target="_blank"&gt;Aroon Indicator&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The aroon indicator is made up of two lines. The "Aroon up" measures the strength of the uptrend and the "Aroon down" measure the strength of the downtrend. Each line calculates, in percentage, the time it takes the price to reach the highest or lowest point in a given time period.&lt;br /&gt;
&lt;br /&gt;
Example of rules using QuantShare:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;cross(AroonUp(14), 50) &lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="http://www.alltrading.info/technical-analysis/44-indicators-technical-analysis/100-ppo-percentage-price-oscillator" target="_blank"&gt;Percentage Price Oscillator&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The percentage price oscillator or PPO shows the difference, in percentage, of two exponential moving averages.&lt;br /&gt;
It is very helpful particularly when comparing stocks together. You can for example use it to create market composites or to rank stocks in your trading system.&lt;br /&gt;
&lt;br /&gt;
Example of rules using QuantShare:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;ppo(14, 50, _MaSma) &gt; 5&lt;/span&gt;&lt;br /&gt;
=&gt; The short term moving average is 5% above the medium-term average.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to create a list of trading rules&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have listed few trend indicators, let us create a list of rules.&lt;br /&gt;
&lt;br /&gt;
To create a new list of rules, select "Analysis" then "Rules Manager".&lt;br /&gt;
In the new control, click on "Create", type the list of rules name then select that list from the "List of Rules" panel. Use, the right control to add trading rules. You can add the rules have described in the above examples and of course you can add trading rules based on other trend indicators.&lt;br /&gt;
&lt;br /&gt;
A list of rules containing the above example can be downloaded here:&lt;br /&gt;
&lt;ref&gt;1291&lt;/ref&gt;&lt;br /&gt;
&lt;br /&gt;
More technical indicators can be created by using masks and optimizing the different parameters. Here is how to do that:&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-57-how-to-create-and-backtest-thousands-of-trading-rules-in-less-than-10-minutes"&gt;How to create and backtest thousands of trading rules in less than 10 minutes&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to analyze each trading rule individually&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
While you are still using the "Rules Manager" control, select your list of rules then click on "Analyze the list".&lt;br /&gt;
Select the list of stocks or securities to analyze as well as the start/end dates and the time frame (daily, weekly or intra-day).&lt;br /&gt;
Click on "Continue" to start analyzing each trading rule individually.&lt;br /&gt;
&lt;br /&gt;
It is also important to define an exit rule. For this, select "Outputs" tab in "Rules Analyzer Settings" form, click on "Select Outputs/Exit rules".&lt;br /&gt;
To define an N-bar stop (For example: Enter when the rule is true and exit after 10 bars), select "Performance, use N-Bars stop", click on "Add" then set "10" under "Number of bars" column. Click on "OK" to save your settings.&lt;br /&gt;
&lt;br /&gt;
Note that you can define several exit rules. In that case, for each trading rule, you will get several reports; one for each exit rule. Each exit rule is analyzed individually.&lt;br /&gt;
&lt;br /&gt;
Once completed, you will have a better idea of which trading rule performs well. You can also create a new list of rules based on the top performing ones.&lt;br /&gt;
&lt;br /&gt;
More info: &lt;a href="http://www.quantshare.com/sa-91-introduction-to-the-trading-rules-analyzer"&gt;Introduction to the trading rules analyzer&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to select the best combination of trading rules for your trading system&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The last step would be to include one or several of these trading rules into your trading system. You can even perform an optimization looking for the best rule or combination of trading rules that has the best performance.&lt;br /&gt;
&lt;br /&gt;
The following blog posts show you how to add trading rules into a trading system and how to optimize them:&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-352-how-to-choose-which-technical-indicators-to-use-in-your-trading-system"&gt;How to choose which technical indicators to use in your trading system&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-289-how-to-turn-any-ordinary-trading-strategy-into-a-very-profitable-one"&gt;How to turn any ordinary trading strategy into a very profitable one&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The opposite of a trending market is referred to as a ranging market. In a future post, we will write about how to detect ranging markets and which indicators to use for that.&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/Axw1XnsBb2I" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/Axw1XnsBb2I/sa-532-how-to-pick-the-best-trend-indicators</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-532-how-to-pick-the-best-trend-indicators</guid>
        <pubDate> Fri, 10 May 2013 11:27:50 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-532-how-to-pick-the-best-trend-indicators</feedburner:origLink></item>  
     <item>
        <title> Update Chart Layout based on Active Ticker Symbol - Part 2</title>
        <description>In the &lt;a href="http://www.quantshare.com/sa-528-update-chart-layout-based-on-active-ticker-symbol"&gt;previous post&lt;/a&gt;, we created a script that runs on the background. The script function was to change the chart's layout depending on the active symbol. &lt;br /&gt;
&lt;br /&gt;
You can show different indicators depending on whether you are displaying on the chart a stock, a future, a small cap...&lt;br /&gt;
&lt;br /&gt;
Let us go further with this script and add the ability to associate a list of symbols to a specific layout. You will no longer have to type symbols one by one to associate them to a specific layout. You will be able to create a list of symbols and with one line of code associate all the symbols in this list to a specific layout.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Symbols List&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let us show you what is the list of symbols we are referring to.&lt;br /&gt;
Select "Symbol" then "Symbols View" to open a control that displays list of symbols (Also called Symbols Filter). Each list is based on one or several conditions. The securities that meet these conditions are included in the list.&lt;br /&gt;
Example: &lt;br /&gt;
- Securities whose ticker name starts with "A"&lt;br /&gt;
- Stocks that belong to a specific industry&lt;br /&gt;
- Stocks that are part of the S&amp;P 500 Index&lt;br /&gt;
- Securities that increased by more than 1% in the previous day&lt;br /&gt;
&lt;br /&gt;
To create a new list of symbols, right click on the control then select "Create a new symbols filter".&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Associate a list to a layout&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Now that you have created one or several lists, let me show you how to use these lists and associate them with a particular layout, so that each time you select one of the securities that belong to a list, its corresponding layout is automatically reflected on the chart.&lt;br /&gt;
&lt;br /&gt;
- Select "Tools -&gt; Script Editor"&lt;br /&gt;
- Click on "File -&gt; New" then enter a new name for our script&lt;br /&gt;
- Paste the script code (&lt;a href="http://www.quantshare.com/free/auto_change_layout_1.txt"  target="_blank"&gt;download it here&lt;/a&gt;)&lt;br /&gt;
- Click on "Execute" to run the script (Here is how to add the script to the bookmark panel: &lt;a href="http://www.quantshare.com/how-264-what-is-the-bookmark-panel"  target="_blank"&gt;Click here&lt;/a&gt;)&lt;br /&gt;
&lt;br /&gt;
Compared to the previous script we have uploaded few weeks ago, the current one has one additional method, which is:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;AddSymbol(string listName, string listCategory, string layout)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The function takes the category and name of a symbols list, retrieves all symbols in the list then associates each one of them to the layout you specified in the same function.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example of usage&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
At the beginning of the script, you can type the following line to associate stocks from "Gold List" to a layout named "gold".&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;AddSymbol("Gold List", "", "gold");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/layoutsymbol_2.gif" title="Update Chart Layouts based on Active Ticker Symbol" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to keep the same time frame when changing layout&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Besides all the visual settings, a layout also stores important data such as the ticker symbol, the number of bars to display and the chart's period. This means that each time you change a layout; the chart will be updated with the new layout's period. If you are using an EOD chart and the layout you are going to load was saved under a one-minute chart then the new chart will show one-minute data too. &lt;br /&gt;
&lt;br /&gt;
Many traders wouldn't want the period or time frame to change when switching layouts. This can be accomplished by following these steps:&lt;br /&gt;
&lt;br /&gt;
In the formula script, there are two calls to the following function: &lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;"App.Main.UpdateChartLayout"&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Before each call, type the following lines:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;int currentTimeframe = chart.TimeFrame;&lt;br /&gt;
bool isHistorical = chart.IsHistorical;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
[This is to save the current time frame]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
- After each call, type the following lines:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;chart.TimeFrame = currentTimeframe;&lt;br /&gt;
chart.IsHistorical = isHistorical;&lt;br /&gt;
chart.Update();&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
[This is to restore the old time frame and update the chart]&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://www.quantshare.com/free/auto_change_layout_2.txt"  target="_blank"&gt;You can find the complete code here&lt;/a&gt;.&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/BkZyuIUHYEQ" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/BkZyuIUHYEQ/sa-529-update-chart-layout-based-on-active-ticker-symbol-part-2</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-529-update-chart-layout-based-on-active-ticker-symbol-part-2</guid>
        <pubDate> Wed, 24 Apr 2013 12:24:13 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-529-update-chart-layout-based-on-active-ticker-symbol-part-2</feedburner:origLink></item>  
     <item>
        <title> Update Chart Layout based on Active Ticker Symbol</title>
        <description>You probably do not trade stocks like your trade futures or Forex currencies. It is also unlikely that you use the same indicators and rules for all assets.&lt;br /&gt;
&lt;br /&gt;
If you agree with that then you will find the following article very interesting. This post describes a script that is implemented in QuantShare. This script will run on background and it will automatically update the chart layout based on the active symbol and a predefined list of symbols/layouts.&lt;br /&gt;
&lt;br /&gt;
If you are still wondering what I am talking about, here is an example:&lt;br /&gt;
&lt;br /&gt;
Let us say that when displaying stock charts, you often want to display the RSI indicator and two moving averages on the main pane. This is our default pane.&lt;br /&gt;
When displaying Forex charts, you want to display the number of stock tweets per day as well the correlation with another currency.&lt;br /&gt;
Our script will automatically choose the right layout for you when you select an asset. If you choose a stock then the first layout (RSI + Moving averages) is displayed and when you choose a currency such as the EURUSD, the second layout (Tweets + Correlation) is displayed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;What is Layout?&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
A chart layout is a file that contains information about how to display a chart.&lt;br /&gt;
How many panes it contains? What are the different formulas of each pane? What is the template of each pane? What is the chart's period?...&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;How to create a new layout&lt;/u&gt;: &lt;br /&gt;
To save the current chart's layout, right click on the chart, select "Layout" then "Save Layout As".&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;How to set a new layout to a chart&lt;/u&gt;:&lt;br /&gt;
Right click on a chart, select "Layout" then select an existing layout from the list.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;How to set a default layout&lt;/u&gt;: &lt;br /&gt;
Right click on a chart, select "Layout" then "Set current layout as default". This layout will be used for example when you open a new chart using "View -&gt; New chart".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to Install the Script&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
- To open the script editor, select "Tools" then "Script Editor".&lt;br /&gt;
- Click on "File" then "New" to create a new script&lt;br /&gt;
- Type the script name then click on "OK"&lt;br /&gt;
- Paste the script (&lt;a href="http://www.quantshare.com/free/auto_change_layout.txt"  target="_blank"&gt;Click here to get the complete script&lt;/a&gt;)&lt;br /&gt;
- Click on "Execute" to run the script&lt;br /&gt;
&lt;br /&gt;
It is preferable to add the script to the &lt;a href="http://www.quantshare.com/how-264-what-is-the-bookmark-panel"  target="_blank"&gt;bookmark panel&lt;/a&gt;. This allows you to run it quickly from the main window. Here is how to accomplish this:&lt;br /&gt;
- In the "Script Editor"&lt;br /&gt;
- Select "Settings" then "Add current script to bookmark panel"&lt;br /&gt;
&lt;br /&gt;
You may also instruct QuantShare to run this script when QuantShare trading software starts by creating a task using the task manager (Tools -&gt; Task Manager).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How the Script Works?&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The script contains several functions, which will be described later.&lt;br /&gt;
&lt;br /&gt;
First, it loops indefinitely. In the loop, it gets the active chart and check if there is a layout associated with the chart's symbol.&lt;br /&gt;
If it does not find any layout, it uses the default layout as specified in the variable "defaultLayout", which of course you can change anytime by updating the script.&lt;br /&gt;
If it finds a layout, it checks if the current chart has a different layout and updates that chart with the layout associated with the active symbol (The symbol selected for the active chart).&lt;br /&gt;
&lt;br /&gt;
The different functions created by the script are:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;AddSymbol(string symbol, string layout)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Associates a symbol with a specific layout.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;AddSymbol(string[] symbols, string layout)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Associates a list of symbols with a specific layout. Instead of calling the first function several times, you can create a list of symbols and then associate all these symbols to a single layout.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;AddSymbol(Symbol[] symbols, string layout)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Associates a list of symbols (represented by "Symbol" class) with a specific layout.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;GetLayoutFromSymbol(string symbol)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Returns the layout that was associated with the provided symbol. Returns "NULL" if the symbol is not associated with any layout.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;RegisterChart(long id, string layout)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Informs QuantShare that the chart with the specified ID is associated with the specific layout. This prevents the script from updating the chart if its layout is already the right one.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;IsUpdate(long id, string layout)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Gets whether to update the chart or not (changing its layout).&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/layoutsymbol_1.gif" title="Update Chart Layouts based on Active Ticker Symbol" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Update Layout based on Watchlists&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Did you know that you could associate a watchlist to a layout? &lt;br /&gt;
&lt;br /&gt;
For example, let us say that you have a watchlist that displays stocks that have a PER (Price earnings ratio) higher than 15.&lt;br /&gt;
You can create a layout that displays historical PER data as well as other fundamental and instructs the watchlist to use that layout anytime you choose a symbol from that watchlist.&lt;br /&gt;
&lt;br /&gt;
To associate a layout to a watchlist:&lt;br /&gt;
- Right click on the watchlist&lt;br /&gt;
- Select "Settings"&lt;br /&gt;
- Type the "Layout" name&lt;br /&gt;
- Click on "OK"&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/Kcw9KXIghLg" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/Kcw9KXIghLg/sa-528-update-chart-layout-based-on-active-ticker-symbol</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-528-update-chart-layout-based-on-active-ticker-symbol</guid>
        <pubDate> Mon, 15 Apr 2013 12:25:14 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-528-update-chart-layout-based-on-active-ticker-symbol</feedburner:origLink></item>  
     <item>
        <title> Using Average True Range to Measure Intraday Volatility</title>
        <description>Volatility is a measure that allows you to estimate the "risk" of an asset.&lt;br /&gt;
&lt;br /&gt;
There are different types of volatility:&lt;br /&gt;
&lt;u&gt;Implied volatility&lt;/u&gt;: This is the estimated volatility of an asset's price. &lt;br /&gt;
&lt;u&gt;Historical volatility&lt;/u&gt;: This is the realized volatility of an asset over a specific time period. It is also called the statistical volatility.&lt;br /&gt;
&lt;br /&gt;
For intraday traders and those looking for an easier way to measure volatility, you can use the true range to measure intraday volatility.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;True Range&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The True range indicator was developed by J. Welles Wilder Jr. in the 1970's. It is a better measure of the intraday volatility than the "Range" (which the difference between the session/period high and low) because the latter understates the volatility since it only measures volatility that occurs during a bar/session and ignores overnight volatility.&lt;br /&gt;
To fix this, the True Range uses the bar's high, low and previous bar's close. By combining these variables, the true range considers both the intraday and overnight part of the price's volatility.&lt;br /&gt;
&lt;br /&gt;
The true range is calculated by taking the greatest of the following variables:&lt;br /&gt;
- High (current bar) less low&lt;br /&gt;
- High (current bar) less previous bar's close&lt;br /&gt;
- Previous bar's close less low (current bar)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Implementing the Average True  Range Indicator&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let us implement the different variables described in the previous paragraph then find which one is the greatest (true range).&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = high - low;&lt;br /&gt;
b = high - close[1];&lt;br /&gt;
c = close[1] - low;&lt;br /&gt;
&lt;br /&gt;
tr = max(a, max(b, c));&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To calculate the average true range (ATR), we simply apply a moving average to the true range.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;d = sma(tr, 10);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
This will return the 10-bar average true range.&lt;br /&gt;
&lt;br /&gt;
Note that QuantShare already has a built-in function ("Atr") that calculates the average true range.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example&lt;/u&gt;:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;d = Atr(10);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How Day Traders Measure Intraday Volatility&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let us say you are working with one-minute data and you want to calculate the intraday volatility (Average true range based on session high, low and close).&lt;br /&gt;
As you might have guessed, the calculation of the intraday volatility must be based on daily data. &lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
&lt;br /&gt;
- Change the time frame to daily&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;TimeframeSet(-1);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
We use negative time frame to reference daily data when working with intraday data (1 = 1-day period = daily)&lt;br /&gt;
&lt;br /&gt;
- Calculate the average true range of the previous 10 trading days&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = atr(10);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Restore the default time frame (one-minute data)&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;TimeframeRestore();&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Decompress the result so that daily data is synchronized with the one-minute data&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = timeframedecompress(a);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;The complete formula is as follows&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;TimeframeSet(-1);&lt;br /&gt;
a = atr(10);&lt;br /&gt;
TimeframeRestore();&lt;br /&gt;
a = timeframedecompress(a);&lt;br /&gt;
plot(a, "ATR");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/volatr_1.gif" title="Using Average True Range to Measure Intraday Volatility" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
There is also another way to implement the same thing. Here is the formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;b = TimeframeApply(-1, atr(10));&lt;br /&gt;
b = timeframedecompress(b);&lt;br /&gt;
plot(b, "ATR", colorGreen);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The "TimeframeApply" function calculates a specific series in a different time frame. It replaces the "TimeframeSet" and "TimeframeRestore" functions.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Example of Strategy Using the True Range Indicator&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let us implement the following trading system:&lt;br /&gt;
&lt;br /&gt;
- Buy when the intraday volatility as measured by ATR is increasing and when price crosses above 10-bar moving average&lt;br /&gt;
- Sell at the end of the trading session&lt;br /&gt;
&lt;br /&gt;
Here is how to create a trading system:&lt;br /&gt;
&lt;a href=http://www.quantshare.com/how-273-how-to-create-a-trading-system&gt; How to create a trading system&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
And here is the formula that you should use to implement the above strategy:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;rule1 = TimeframeApply(-1, atr(1) &gt; ref(atr(1), 1)); // Ref: Reference previous bar's value&lt;br /&gt;
rule1 = timeframedecompress(rule1);&lt;br /&gt;
buy = rule1 and cross(close, sma(10));&lt;br /&gt;
sell = hour() &gt;=16;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/scVIi0fUKw8" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/scVIi0fUKw8/sa-527-using-average-true-range-to-measure-intraday-volatility</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-527-using-average-true-range-to-measure-intraday-volatility</guid>
        <pubDate> Thu, 21 Mar 2013 11:43:41 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-527-using-average-true-range-to-measure-intraday-volatility</feedburner:origLink></item>  
     <item>
        <title> How to Backtest Your Trading System for Each Industry</title>
        <description>Some trading systems, particularly fundamental-based ones, may perform very well on stocks that belong to some particular industries and perform badly on other industries.&lt;br /&gt;
Just like backtesting a trading system for each asset individually, you can use QuantShare to implement a system then perform a backtest for each industry. The system will be optimized and each optimization shows the result of a backtest on stocks belonging to one particular industry.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Industry Data&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Is your QuantShare database populated with industry data?&lt;br /&gt;
&lt;br /&gt;
To make sure it is, select "Symbol -&gt; Auto Manage Symbols", check one or several exchanges you are interested in, check "Force the update of symbol information" then click on "Save".&lt;br /&gt;
After few seconds, QuantShare will update your symbols list and add if necessary industry information (Industry of each stock in your database)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Trading System&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The following is the description of the trading system that is used as an example in this article.&lt;br /&gt;
&lt;br /&gt;
Buy when price crosses above 25-bar simple moving average&lt;br /&gt;
Sell when price crosses below 25-bar simple moving average&lt;br /&gt;
&lt;br /&gt;
How to implement this trading system:&lt;br /&gt;
- Select "Analysis -&gt; Simulator"&lt;br /&gt;
- Click on "New" to create a new trading system&lt;br /&gt;
- Select "Create trading system using the formula editor" tab&lt;br /&gt;
- Type the following formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;buy = cross(close, sma(25));&lt;br /&gt;
sell = cross(sma(25), close);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
"Close" gets the stock's price series&lt;br /&gt;
"SMA" calculates the simple moving average&lt;br /&gt;
"Cross" function detects when the first array crosses above the second array&lt;br /&gt;
&lt;br /&gt;
- Click on "Create Trading System" to save your strategy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Count the Number of Industries&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let us count the number of industries we have in the database.&lt;br /&gt;
Select "Symbol -&gt; Categories", click on "Industry" tab to display all industries. There are probably several hundred of industries there so we have to use the script editor to count these.&lt;br /&gt;
Open the script editor (Tools -&gt; Script Editor), create a new script then type the following formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;MessageBox.Show("Industry Count: " + Symbols.GetIndustryList().Length.ToString());&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Click on "Execute" the display the number of industries.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Backtest Each Industry&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Select the previously created trading system then click on "Update".&lt;br /&gt;
We have to use a custom function (IndustryPosition) to get the index position based on its name. The function can be downloaded here: &lt;ref&gt;1253&lt;/ref&gt;.&lt;br /&gt;
&lt;br /&gt;
In the formula editor, type the following lines:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Optimize("a", 0, 256, 1);&lt;br /&gt;
b = IndustryPosition(industry());&lt;br /&gt;
rule1 = a == b;&lt;br /&gt;
buy = cross(close, sma(25)) and rule1;&lt;br /&gt;
sell = cross(sma(25), close);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The first line instructs QuantShare to optimize the trading system by varying the variable "a" from 0 to the total number of industries (We used 256 here).&lt;br /&gt;
The second line gets the industry position within industry list.&lt;br /&gt;
The third line compares the optimizable variable and the industry position. This means that the trading system will buy only stocks that belong to the industry that are in the position defined by the variable "a".&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/opt_industry_1.gif" title="How to Backtest Your Trading System for Each Industry" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After updating your trading system, click on "Optimize" to start the optimization process.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Adding Industry Name to the Report&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
As you can see from the earlier backtesting, the report shows only the industry position within the list. It does not show the industry name directly in the report table.&lt;br /&gt;
There is no way to see for which industry a simulation was based unless you open the report then select "S.I.M.I -&gt; Avg. Trade Performance" tab.&lt;br /&gt;
&lt;br /&gt;
In order to add the industry name to the report, we have to use the money management script.&lt;br /&gt;
&lt;br /&gt;
- Select the trading system then click on "Update"&lt;br /&gt;
- Select "Money Management" tab&lt;br /&gt;
- Click on "Add a new money management script"&lt;br /&gt;
- Select "OnStartSimulation" event then type the following line:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Functions.AddReportMetric("Industry", "");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Select "OnEndSimulation" event then type the following lines:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;MMPosition[] pos = Portfolio.GetAllPositions();&lt;br /&gt;
if(pos.Length &gt; 0)&lt;br /&gt;
{&lt;br /&gt;
Symbol sym = Data.GetSymbolInfo(pos[0].Symbol);&lt;br /&gt;
Variables.SetVariable("Industry", sym.Industry);&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Run the optimization again to display the industry name in a separate column in the backtesting report.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/opt_industry_2.gif" title="How to Backtest Your Trading System for Each Industry" /&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/veYjBp-lZ8k" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/veYjBp-lZ8k/sa-526-how-to-backtest-your-trading-system-for-each-industry</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-526-how-to-backtest-your-trading-system-for-each-industry</guid>
        <pubDate> Wed, 13 Mar 2013 11:24:10 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-526-how-to-backtest-your-trading-system-for-each-industry</feedburner:origLink></item>  
     <item>
        <title> Create Profitable Trading Strategies with Exchange Traded Funds (ETFs)</title>
        <description>&lt;strong&gt;ETFs Selection (Correlation matrix)&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
One way to select exchange-traded funds (ETFs) to include in your trading systems is by using a correlation matrix.&lt;br /&gt;
&lt;br /&gt;
The idea is to pick two or three ETFs then select the remaining (depends on the number of exchange traded funds you want to use in your trading strategy) by choosing the ones that are less correlated with the first ETFs you have chosen.&lt;br /&gt;
&lt;br /&gt;
Here is how to create the correlation matrix: &lt;br /&gt;
&lt;a href="http://www.quantshare.com/how-254-how-to-create-a-correlation-matrix-of-several-securities"&gt;How to create a correlation matrix of several securities&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the next paragraphs, we will show you how to implement and optimize a trading system based on ETFs. This system will include the following ETFs:&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;SPY: SPDR S&amp;P 500 ETF&lt;/u&gt;&lt;br /&gt;
=&gt; Represents the stock market of the world's largest economy&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;IWM: iShares Russell 2000 Index&lt;/u&gt;&lt;br /&gt;
=&gt; Small caps often behave differently from large cap stocks. One average, the annual return of small cap stocks exceeds the return of large cap stocks.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;EFA: iShares MSCI EAFE Index ETF&lt;/u&gt;&lt;br /&gt;
=&gt; Represents developed economies of several countries (Europe, Australia, Asia...)&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;EEM: iShares MSCI Emerging Markets&lt;/u&gt;&lt;br /&gt;
=&gt; Emerging countries are very important because they are major contributors to the global economic growth. They have higher volatility (riskier) but they also offer great potential for higher returns.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;AGG: iShares Barclays Aggregate Bond ETF&lt;/u&gt;&lt;br /&gt;
=&gt; The Bond market is usually less volatile than the stock market and thus could reduce the drawdown and volatility of our strategies&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;VNQ: Vanguard REIT ETF&lt;/u&gt;&lt;br /&gt;
=&gt; To add further diversification, it is important to include REITs (real estate investment trusts) investments.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;GLD: SPDR Gold Shares&lt;/u&gt;&lt;br /&gt;
=&gt; This ETF allows us to invest in a very attractive market: the gold market&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;DBC: PowerShares DB Commodity Index Tracking Fund&lt;/u&gt;&lt;br /&gt;
=&gt; Based on the  DBIQ Optimum Yield Diversified Commodity Index Excess Return, this fund invests in commodities futures, including light, Sweet Crude Oil (WTI), Heating Oil, RBOB Gasoline, Natural Gas, Brent Crude, Gold, Silver, Aluminum, Zinc, Copper Grade A, Corn, Wheat, Soybeans, and Sugar.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;ETFs-based Trading System&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The trading system consists of a buying the top four ETFs based on their momentum (or any other measure) and rebalance monthly. This means that each month, we will sell all active positions and buy the new top four ETFs.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Implementing the Trading System&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Select "Analysis -&gt; Simulator" then create a new trading system.&lt;br /&gt;
&lt;br /&gt;
In order to buy the top 4 exchange traded funds, we will use the "comp" function. This function ranks securities, each trading bar, based on a specific criterion. In our case, we want to rank ETFs based on momentum and thus we will use the 25-bar (one month) rate of return to do this.&lt;br /&gt;
We should exit any position on the beginning of a new month only if it is not on the new buy list (top 4).&lt;br /&gt;
&lt;br /&gt;
Here is the trading system formula:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;buy = comp(roc(25), "rank") &lt;= 4;&lt;br /&gt;
sell = month() != ref(month(), 1) and !buy;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Now, select "Symbols &amp; Dates" tab, add a "Custom Symbols" condition under "Symbols" then copy the symbol names of the different exchange traded funds (see above).&lt;br /&gt;
&lt;br /&gt;
Don't forget to set "The number of positions" field of the trading system to "4".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Momentum or any other measure&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The next lines will show you how to choose a better measure to rank ETFs. We have previously used momentum as a measure but we can use QuantShare optimizer to analyze hundreds of measures and choose the one that performs best in our trading system.&lt;br /&gt;
&lt;br /&gt;
This technique consists of creating several trading rules (measures in this case) then use the "ApplyRule" function to create several trading systems each one using a rule from the trading rules list.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Steps&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
- Select "Analysis" then "Rules Manager"&lt;br /&gt;
- Click on "Create" to add a new list&lt;br /&gt;
- Select your list then add several measures&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;roc(25)&lt;br /&gt;
roc(100)&lt;br /&gt;
rsi(2)&lt;br /&gt;
rsi(14)&lt;br /&gt;
close - sma(30)&lt;br /&gt;
hhv(30) - llv(30)&lt;br /&gt;
sharpe(close, 25)&lt;br /&gt;
stddev(25)&lt;br /&gt;
...&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is how to create thousands of trading rules using the "Rules Manager" tool:&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-57-how-to-create-and-backtest-thousands-of-trading-rules-in-less-than-10-minutes"&gt;How to create and backtest thousands of trading rules in less than 10 minutes&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-434-10-masks-to-create-thousands-of-rules-to-use-into-your-trading-system"&gt;10 masks to create thousands of rules to use into your trading system&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Optimize your trading system&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have created the initial trading system and a list of measures, let us combine them to create and backtest several trading systems in order to find the most profitable ones.&lt;br /&gt;
&lt;br /&gt;
Update the original trading system then replace its formula by this one:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;nbRules = ApplyRule("", "MyList", -1);&lt;br /&gt;
Optimize("m", 0, nbRules - 1, 1);&lt;br /&gt;
measure1 = ApplyRule("", "MyList", m);&lt;br /&gt;
buy = comp(measure1, "rank") &lt;= 2;&lt;br /&gt;
sell = month() != ref(month(), 1) and !buy;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Explanation&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
Line 1: Get the total number of rules/measures in your trading rules list "MyList" by specifying "-1" as last argument of the "ApplyRule" function&lt;br /&gt;
Line 2: Create an optimizable variable "m"&lt;br /&gt;
Line 3: Calculates the measure that is located at index (m) in the trading rules list "MyList"&lt;br /&gt;
Line 4: Use that measure when ranking ETFs&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/strategy_etf_1.gif" title="Create Profitable Trading Strategies with Exchange Traded Funds (ETFs)" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Save your trading system then click on "Optimize" to backtest the different variations of the trading system. Pick the most profitable one or choose one given your own metrics.&lt;br /&gt;
&lt;br /&gt;
After selecting the best trading system, note the "m" index value, open the "Rules Manager", select your list of rules then select "Tools -&gt; Display All Rules".&lt;br /&gt;
In the new form that appears, you can get the measure formula that corresponds to the "m" index.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/strategy_etf_2.gif" title="Create Profitable Trading Strategies with Exchange Traded Funds (ETFs)" /&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/NTCMnO_sQ_8" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/NTCMnO_sQ_8/sa-523-create-profitable-trading-strategies-with-exchange-traded-funds-etfs</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-523-create-profitable-trading-strategies-with-exchange-traded-funds-etfs</guid>
        <pubDate> Thu, 28 Feb 2013 12:31:42 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-523-create-profitable-trading-strategies-with-exchange-traded-funds-etfs</feedburner:origLink></item>  
     <item>
        <title> 3 Market Indicators based on Fundamental Data</title>
        <description>There are tons of market indicators based on prices and technical indicators. We have already created several blog posts about how to create some these market indicators:&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-340-4-original-breadth-indicators-you-should-consider-in-your-market-timing-strategy"&gt;4 original breadth indicators you should consider in your market timing strategy&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-508-4-market-composite-indicators-based-on-industry-data"&gt;4 Market Composite Indicators Based on Industry Data&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-511-how-to-select-the-best-market-indicator-for-your-trading-system"&gt;How to Select the Best Market_Indicator for your Trading_System&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
However, no one is based on fundamental data. The idea is to create an indicator that shows the state of the market based on one or several fundamental items or ratios. As an example, we could create a market indicator that displays the number of stocks whose price earnings ratio is above 12. The time series that results could be used as an indicator for your market timing system or it could be used to detect potential market corrections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Downloading historical fundamental data&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Historical fundamental data is required in order to calculate past values of our market indicators. The following downloader (&lt;ref&gt;1181&lt;/ref&gt;) gets yearly data of more than 80 fundamental item/ratio. &lt;br /&gt;
&lt;br /&gt;
Among these ratios, we can cite:&lt;br /&gt;
Net Margin %&lt;br /&gt;
Debt/Equity&lt;br /&gt;
Quick Ratio&lt;br /&gt;
Free Cash Flow/Sales %&lt;br /&gt;
Return on Equity %&lt;br /&gt;
Payout Ratio %&lt;br /&gt;
Gross Margin %&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;How to download data&lt;/u&gt;:&lt;br /&gt;
- Select "Download -&gt; Download Manager"&lt;br /&gt;
- Select "Morningstar Historical Fundamentals"&lt;br /&gt;
- Click on "Open Selected Downloader" then click on "Start Downloading"&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;How to display the data&lt;/u&gt;:&lt;br /&gt;
- Select "Data -&gt; Edit Databases"&lt;br /&gt;
- Choose "Custom" database then choose "morningstar_fundamentals"&lt;br /&gt;
- Select the symbol for which you want to display the data on the right panel&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Access fundamental data using QS language&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The downloader we have introduced in the previous paragraph gets data for each U.S. symbol and stores this data into a custom database "morningstar_fundamentals".&lt;br /&gt;
&lt;br /&gt;
The QuantShare language has several functions to access custom database data and create time series from this data.&lt;br /&gt;
For example, the "GetData" function retrieves historical data of any database field.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = GetData("morningstar_fundamentals", "return_on_assets_pct_profitability", Last);&lt;br /&gt;
plot(a, "Return on Assets");&lt;br /&gt;
SetHatchBrush("DiagonalCross", colorRed);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/fundamental_composites_1.gif" title="3 Market Indicators based on Fundamental Data" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As you can see from this picture, the above formula, when added to a chart, plots the changes of the Return on Assets ratio over several years.&lt;br /&gt;
&lt;br /&gt;
Of course, the "GetData" function can also be used to create trading systems, composites, watchlists, screens, neural network models...&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Number of Stocks with Positive Return on Equity&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The market indicator we will implement first returns the number of stocks that have a positive return on equity.&lt;br /&gt;
&lt;br /&gt;
Return on equity or ROE is the rate of return on the shareholders' equity. It measures the capacity of a company to use its investment funds to generate earnings growth.&lt;br /&gt;
The ROE fundamental ratio is located under the "return_equity_pct_profitability" field of the "morningstar_fundamentals" database.&lt;br /&gt;
&lt;br /&gt;
To get the return on equity, simply type:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = GetData("morningstar_fundamentals", "return_equity_pct_profitability");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;To create this composite&lt;/u&gt;:&lt;br /&gt;
- Select "Tools -&gt; Composites"&lt;br /&gt;
- In the composites form, click on "Add" to create a new composite&lt;br /&gt;
- Select the symbols that you want to include in the composite. Either select all symbols or select stocks from a specific market or index (such as S&amp;P 500 stocks)&lt;br /&gt;
- Click on "Next" then type the following formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = GetData("morningstar_fundamentals", "return_equity_pct_profitability");&lt;br /&gt;
composite = a &gt; 0;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Select "The sum of the values added to the composite" as calculation method&lt;br /&gt;
- Click on "Next" twice, set up a name then click on "Next" to create the composite and start the calculation process.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/fundamental_composites_2.gif" title="Number of Stocks with Positive Return on Equity" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Number of Stocks with Increasing Free Cash Flow/Sales Ratio&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This market indicator returns the number of stocks whose free cash flow to sales ratio increased compared to the previous year.&lt;br /&gt;
&lt;br /&gt;
The free cash flow to sales is a fundamental ratio that shows how well the revenue of a company is transformed into cash. This ratio is stored under the "free_cash_flow_to_sales_pct" field.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Here is the formula that you can use to create this composite&lt;/u&gt;:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = GetData("morningstar_fundamentals", "free_cash_flow_to_sales_pct", Zero);&lt;br /&gt;
composite = a &gt; 0;&lt;br /&gt;
// Calculation Method: The sum of the values added to the composite&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Earnings-per-Share ratio of S&amp;P 500 Stocks&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Here, we calculate the number of S&amp;P 500 stocks with positive EPS (Earning per share) and subtract the result by the number of S&amp;P 500 stocks with negative EPS.&lt;br /&gt;
&lt;br /&gt;
The earnings-per-share ratio shows the portion of a company's profit for each outstanding share. This ratio is stored under the "earnings_per_share_usd" field.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;The formula is&lt;/u&gt;:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = GetData("morningstar_fundamentals", "earnings_per_share_usd");&lt;br /&gt;
pos1 = a &gt; 0;&lt;br /&gt;
neg1 = a &lt; 0;&lt;br /&gt;
composite = pos1 &#xfffd; neg1;&lt;br /&gt;
// Calculation Method: The sum of the values added to the composite&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As you can see from the three market indicators we created in this article, it is very easy to create fundamental-based composites. You can even create more advanced ones by using several fundamental ratios or combining technical and fundamental indicators.&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/LvGOqLFNqKA" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/LvGOqLFNqKA/sa-518-3-market-indicators-based-on-fundamental-data</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-518-3-market-indicators-based-on-fundamental-data</guid>
        <pubDate> Fri, 15 Feb 2013 12:34:17 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-518-3-market-indicators-based-on-fundamental-data</feedburner:origLink></item>  
     <item>
        <title> How to Send Commands to QuantShare from Excel or Other Applications</title>
        <description>There are probably tons of reasons, why someone would want to manipulate QuantShare from another application. Here are some examples:&lt;br /&gt;
&lt;br /&gt;
- You have an excel sheet with ticker symbols and some custom data. You would like to display the symbol's chart in QuantShare when clicking on the ticker symbol cell&lt;br /&gt;
&lt;br /&gt;
- Click on a button in excel to instruct QuantShare to do a scan and return a list of symbols that meet your criteria&lt;br /&gt;
&lt;br /&gt;
- You want to get a list of trades from your QuantShare portfolios in your own application&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to send commands to QuantShare from Excel&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let us take the first example described above and implement it.&lt;br /&gt;
&lt;br /&gt;
What we want is that when a user clicks on a button or cell in excel, QuantShare automatically updates the active chart with a specific ticker symbol.&lt;br /&gt;
&lt;br /&gt;
There are several ways to implement this (files, sockets...). We will use here a technique that consists of running "QuantShare.exe" file with some specific arguments. In these arguments, we will define an existing task to execute.&lt;br /&gt;
&lt;br /&gt;
- First, let us open QuantShare and create a script by selecting "Tools -&gt; Script Editor".&lt;br /&gt;
- Select "File -&gt; New" then type "ChangeSymbol" as file name&lt;br /&gt;
- In the script editor, type the following formula to update the active chart then save the script:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;string symbol = (string)Global.GetVariable("newsymbol");&lt;br /&gt;
Chart chart = Charts.GetSelectedChart();&lt;br /&gt;
if(chart != null)&lt;br /&gt;
{&lt;br /&gt;
chart.SymbolName = symbol;&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
In the first line, we got the new symbol from a global variable. We will see later how to set that global variable "newsymbol" from excel.&lt;br /&gt;
&lt;br /&gt;
The second step consists of creating a new task:&lt;br /&gt;
- Select "Tools -&gt; Task Manager"&lt;br /&gt;
- Click on "Click here to add a task"&lt;br /&gt;
- Select "App based task" tab (We just need to create a task that is never executed by the application without instructions from us)&lt;br /&gt;
- In "Add Task" control and under "Scripts to be executed", click on "Add" then select "ChangeSymbol" script we have just created&lt;br /&gt;
- Next to "Task Name", type "ChangeSymbol" then click on "OK" to save the task&lt;br /&gt;
&lt;br /&gt;
The third step would be to open Excel and implement the QuantShare call.&lt;br /&gt;
&lt;br /&gt;
- Open Excel and create a new document&lt;br /&gt;
- Create a new button then associate a function to it (click event)&lt;br /&gt;
&lt;br /&gt;
More info can be found here:&lt;br /&gt;
&lt;a href="http://office.microsoft.com/en-001/excel-help/add-a-button-and-assign-a-macro-to-it-in-a-worksheet-HP010236676.aspx" target="_blank"&gt;Add a button and assign a macro to it&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
- Type the following code (macro):&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;res = Shell("E:\Program Files\CTrading\QuantShare5\QuantShare.exe TaskManager ChangeSymbol newsymbol:" + Range("A2"), 1)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/excel_qs_1.gif" title="How to Send Commands to QuantShare from Excel or Other Applications" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Explanation:&lt;br /&gt;
- The "Shell" function executes a specific file (QuantShare.exe for instance)&lt;br /&gt;
- "TaskManager" is the first argument and it instructs QuantShare to use the task manager plug-in to execute the task specified in the second argument (ChangeSymbol)&lt;br /&gt;
- The third argument instructs QuantShare to create a global variable "newsymbol" and set its value with the content of cell A2 (Range function)&lt;br /&gt;
&lt;br /&gt;
Now, you can type a ticker symbol in the cell "A2" and click on the button to update QuantShare's active chart.&lt;br /&gt;
&lt;br /&gt;
Note that you can define several global variables by separating them with a semi-colon. Example:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;newsymbol:GOOG;var2:Test&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
This command instructs QuantShare to create two global variables (newsymbol and var2) and associates them with the following values (GOOG and Test).&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/X7h9l-30gUg" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/X7h9l-30gUg/sa-515-how-to-send-commands-to-quantshare-from-excel-or-other-applications</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-515-how-to-send-commands-to-quantshare-from-excel-or-other-applications</guid>
        <pubDate> Tue, 22 Jan 2013 10:42:40 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-515-how-to-send-commands-to-quantshare-from-excel-or-other-applications</feedburner:origLink></item>  
     <item>
        <title> How to make sure your Historical Price Data is Split Adjusted</title>
        <description>In order to update your historical EOD database, you must download new quotes every day. You can use the default downloader (&lt;ref&gt;463&lt;/ref&gt;) or any item that gets data by symbol (one request per ticker symbol). However, the biggest issue with these items is that the downloading process takes some time. &lt;br /&gt;
&lt;br /&gt;
One solution would be to use downloaders that get data by date. Instead of sending a request for each symbol, these downloaders send a request per date (Quotes of all symbols on that date). &lt;br /&gt;
Since you are updating your database every day, you will only need one request to get latest data. &lt;br /&gt;
&lt;br /&gt;
The problem with these kind of downloaders is that if a stock split or dividend occurs, you will end up with up/down gaps in your data. This is problematic particularly for those who perform backtests and analysis and those who require split and dividend adjusted data.&lt;br /&gt;
&lt;br /&gt;
The idea of this blog post is to get daily stock updates (quickly), detect stocks with recent up or down gaps then download complete history data for those stocks only.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Historical Stock Market Data&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
If you are new to QuantShare or if you want to create a new fresh account, the first thing you must do it download the complete historical data for all your stocks.&lt;br /&gt;
This can be accomplished using the default downloader (&lt;ref&gt;463&lt;/ref&gt;) for example. The downloading process may take few hours but you have to do it only once. &lt;br /&gt;
&lt;br /&gt;
- Select "Download" then "Download Manager"&lt;br /&gt;
- Select "Historical Stock Market Data" item then click on "Open Selected Downloader" button&lt;br /&gt;
- Select a start and end date and uncheck "Last Download Date" and "Last Symbol Date"&lt;br /&gt;
- Select "Symbols" tab then remove any existing condition to instruct QuantShare to download data for all available stocks&lt;br /&gt;
- Click on "Start Downloading"&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Daily Quotes&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
To get latest quotes for U.S. stocks, you can use the following downloader: &lt;ref&gt;1111&lt;/ref&gt;. You should run this downloader once a day to get yesterday's quotes.&lt;br /&gt;
&lt;br /&gt;
The download process is quick but you can end up with unadjusted data because only the most recent quote is added to your database.&lt;br /&gt;
In order to fix this, you must run the historical downloader again for stocks that recently had a stock split.&lt;br /&gt;
&lt;br /&gt;
There are two solutions:&lt;br /&gt;
- Either you download or import stock splits data, detect stocks that recently had a split then download data for these stocks (most complicated solution)&lt;br /&gt;
- Or, you can search for stocks that recently had an up and down gap and download historical price data for these stocks. Up and down gaps could be caused by an increase in the volatility of a stock or by a stock split.&lt;br /&gt;
&lt;br /&gt;
The second solution will be explained in details in the next paragraph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Detecting Recent Up and Down Gaps&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
QuantShare creates and stores pre-defined variables in an internal database. These variables are calculated for each symbol and the calculation takes place each time new data is saved.&lt;br /&gt;
&lt;br /&gt;
For example, if you download historical data for Google then QuantShare will automatically calculate the following measures:&lt;br /&gt;
- Number of quotes&lt;br /&gt;
- Date of last quote&lt;br /&gt;
- Date of first quote&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
These variables can be used later to quickly select stocks in any QuantShare plug-in (for backtesting, screening, downloading...)&lt;br /&gt;
&lt;br /&gt;
Here, we are particularly interested in one variable, which is: "Max %Gap in last 5 bars".&lt;br /&gt;
This variable calculates the maximum up or down gap for any stock in the last five bars.&lt;br /&gt;
We can use that variable in the historical downloader to get stocks that recently had a gap up or down higher than 10% for example.&lt;br /&gt;
&lt;br /&gt;
First, let us create a new historical downloader. To do that, go to the following item (&lt;ref&gt;463&lt;/ref&gt;), download it, install it then when prompted to confirm the item name, rename that item so that you can have two historical downloaders in your account; one to get historical price data for all stocks and one to get historical price data for those with recent gap.&lt;br /&gt;
&lt;br /&gt;
After creating the second downloader, follow the next steps to complete the setup:&lt;br /&gt;
- Open the new downloader in the download manager&lt;br /&gt;
- Select "Symbols" tab&lt;br /&gt;
- Remove any existing conditions&lt;br /&gt;
- Click on "Add a Condition" then select "Quotes"&lt;br /&gt;
- Click on the cell under "Values" column then select "Max %Gap in last 5 bars"&lt;br /&gt;
- Next to "Interval" select "-100" as minimum value and "-10" as maximum value (Down Gaps)&lt;br /&gt;
- Click on "Add a Condition" then select "Union"&lt;br /&gt;
- Click on "Add a Condition" again then select "Quotes"&lt;br /&gt;
- Click on the cell under "Values" column then select "Max %Gap in last 5 bars"&lt;br /&gt;
- Next to "Interval" select "10" as minimum value and "1000000" as maximum value (Up Gaps)&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/download_gap_1.gif" title="How to make sure your Historical Price Data is Split Adjusted" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You have now instructed your downloader to get historical data for stocks that have increased more than 10% or decreased more than -10% in the past 5 bars. This allows you to get historical data price for every company that recently issued a stock split.&lt;br /&gt;
&lt;br /&gt;
To summarize the process:&lt;br /&gt;
- Download historical price data for all stocks (only once)&lt;br /&gt;
- Use the daily downloader to get latest quotes (every day)&lt;br /&gt;
- Use the second downloader to get historical data for companies that may have issued a stock split recently (every day)&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/vXUrcU8B200" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/vXUrcU8B200/sa-514-how-to-make-sure-your-historical-price-data-is-split-adjusted</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-514-how-to-make-sure-your-historical-price-data-is-split-adjusted</guid>
        <pubDate> Wed, 16 Jan 2013 10:58:24 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-514-how-to-make-sure-your-historical-price-data-is-split-adjusted</feedburner:origLink></item>  
     <item>
        <title> How to Select the Best Market Indicator for your Trading System</title>
        <description>The following technique consists of adding market indicators to a trading system to prevent it from entering new positions when the market is bearish or is likely to start a bearish trend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to create market indicators&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
One way consists of creating these indicators using the composite tool. Each indicator is then associated with a ticker symbol.&lt;br /&gt;
&lt;br /&gt;
Another way is to calculate composites on fly using the "comp" function of the QuantShare programming language. The advantage is that we can easily and quickly change and optimize composites in our trading system. For example we can calculate the number of stocks trading above their 10 bar moving average, add it as a rule in our trading system then optimize the period or number of bars used by our moving average.&lt;br /&gt;
&lt;br /&gt;
The formula of the above indicator would be:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = comp(close &gt; sma(10), "sum");&lt;/span&gt;&lt;br /&gt;
More information regarding the "comp" function can be found here:&lt;br /&gt;
&lt;a href="http://www.quantshare.com/sa-140-how-to-create-market-indicators-using-the-composite-function-part-1"&gt;How to create market indicators using the composite&amp;nbsp;function - Part 1&lt;/a&gt;, &lt;a href="http://www.quantshare.com/sa-144-how-to-create-market-indicators-using-the-composite-function-part-2"&gt;Part 2&lt;/a&gt;, &lt;a href="http://www.quantshare.com/sa-160-how-to-create-market-indicators-using-the-composite-function-part-3"&gt;Part 3&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Here are some examples of market indicators:&lt;br /&gt;
Number of stocks trading in an overbought RSI area&lt;br /&gt;
Percentage of stocks making 10 bar new highs&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Create a list of composites&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Because we want to try different composites in our trading strategy, we must save composite rules in a list of rules and reference that rule later in our trading system.&lt;br /&gt;
&lt;br /&gt;
- Select "Analysis" then "Rules Manager"&lt;br /&gt;
- Click on "Create" to create a new list of rules&lt;br /&gt;
- Type the list name (Example: Composites) then click on "OK"&lt;br /&gt;
- In the right panel, add as many rules as you want&lt;br /&gt;
- After you add a rule, click on "Add" button to add it to the list&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example of rules&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
- Asset trading in an overbought RSI area&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;rsi(14) &gt; 70&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Asset trading in an oversold RSI area&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;rsi(14) &lt; 30&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Asset making 10 bar new high&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;close == hhv(close, 10)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Asset making 10 bar new low&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;close == llv(close, 10)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Asset increased two days in a row&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;istrue(close &gt; close[1], 2)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Asset increased three days in a row&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;istrue(close &gt; close[1], 3)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Asset trading above its 5-bar moving average&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;close &gt; sma(5)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You can even create many variations of any trading rule by optimizing one or several of its variables.&lt;br /&gt;
&lt;br /&gt;
Let us take the "Asset making 10 bar new high" rule for example. By tying the following rule "&lt;span style="color:#1C74A8"&gt;close == hhv(close, a)&lt;/span&gt;", a table will appear under "Optimization Grid". Next to the "a" variable, you can define a min, max and increment values. By optimizing the "a" variable, your trading rule will use different high periods.&lt;br /&gt;
&lt;br /&gt;
Now that we have prepared our list, we can create an even better list by removing certain rules based on some specific criteria.&lt;br /&gt;
&lt;br /&gt;
- Select your list of rules&lt;br /&gt;
- Click on "Analyze the list" button&lt;br /&gt;
- Select a list of symbols, period and start &amp; end dates&lt;br /&gt;
- Select "Outputs" from the left panel&lt;br /&gt;
- Click on select "Outputs/Exits"&lt;br /&gt;
- Uncheck existing items&lt;br /&gt;
- Check for example, "Performance use N-Bar Stop -&gt; Buy then sell after 50 bars"&lt;br /&gt;
- Click on "OK" then "Continue" to start the backtesting/analyzing process&lt;br /&gt;
&lt;br /&gt;
You can remove any rules by checking all rules then un-checking the ones that you want to ignore.&lt;br /&gt;
After that, click on "Create a new list from the checked rules".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Create a trading system&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
If you already have a trading system that you want to improve using market indicators, please continue to the next section. In the other case, follow the next steps to create a basic trading system:&lt;br /&gt;
&lt;br /&gt;
- Select "Analysis -&gt; Simulator"&lt;br /&gt;
- Click on "New" to create a new trading system&lt;br /&gt;
- Select "Symbols &amp; Dates" tab to choose the symbols to include in your trading system and define the start &amp; end dates.&lt;br /&gt;
- Click on "Strategy" tab, choose "Create trading system using the formula editor" then type this basic formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;buy = rsi(14) &gt; 70;&lt;br /&gt;
sell = rsi(14) &lt; 30;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The strategy consists of entering long if RSI is above 70 and exiting any position if its RSI drops below 30.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;The best market indicator for your trading system&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Update the previous or one of your trading systems then select the formula editor.&lt;br /&gt;
&lt;br /&gt;
The idea consists of optimizing this trading system by adding each time a different market indicator rule to exit existing positions (For example when the number of stocks trading below RSI 30 reaches a high). The rule is selected from the list of rules we have created previously.&lt;br /&gt;
To calculate the result of a trading rule, we can use the "ApplyRule" function. This function gets the list of rules name and an index. The index tells QuantShare which trading rule to use to return the result.&lt;br /&gt;
The total number of rules (and variations) can be obtained by specifying "-1" in the index parameter.&lt;br /&gt;
&lt;br /&gt;
Here are the lines to add after your original strategy formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;ct = ApplyRule("", "Composites", -1);&lt;br /&gt;
Optimize("a", 0, ct - 1, 1);&lt;br /&gt;
rule1 = ApplyRule("", "Composites", a);&lt;br /&gt;
rule1 = comp(rule1, "sum");&lt;br /&gt;
rule1 = sma(rule1, 25);&lt;br /&gt;
rule1 = (rule1 == hhv(rule1, 250));&lt;br /&gt;
&lt;br /&gt;
sell = sell or rule1;&lt;br /&gt;
buy = buy and !rule1;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Explanation&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
Line 1: Gets the number of trading rules in our list of rules&lt;br /&gt;
Line 2: Optimizes the variable "a". The value of this variable will vary from zero to (ct - 1) during the optimization&lt;br /&gt;
Line 3: Calculates the result of the trading rule that is located at index (a)&lt;br /&gt;
Line 4: Creates a composite. This composite calculates the number of stocks whose rule value is true, for each trading bar&lt;br /&gt;
Line 5: Returns the simple moving average of the composite&lt;br /&gt;
Line 6: Returns true if the composite (its moving average) reaches a new year high&lt;br /&gt;
Line 7: Sells an asset if the above composite value is true&lt;br /&gt;
Line 8: Buys an asset only if the above composite value is false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After you update your formula and save your trading system, click on "Optimize" button to start the optimization process. &lt;br /&gt;
To get the rule formula from its index, open the rules manager, select your list of rules then select "Tools -&gt; Display all rules".&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/best_mi_1.gif" title="How to select the best market indicator for your trading system" /&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/zyypCMUHpdU" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/zyypCMUHpdU/sa-511-how-to-select-the-best-market-indicator-for-your-trading-system</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-511-how-to-select-the-best-market-indicator-for-your-trading-system</guid>
        <pubDate> Fri, 28 Dec 2012 10:22:50 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-511-how-to-select-the-best-market-indicator-for-your-trading-system</feedburner:origLink></item>  
     <item>
        <title> 4 Market Composite Indicators Based on Industry Data</title>
        <description>In the previous blog post, we talked about how to download industry data and associate industries with stocks. We then created a chart displaying stock quotes with its corresponding industry data and implemented a basic trading system that uses the industry relative strength indicator.&lt;br /&gt;
&lt;br /&gt;
If you haven't read yet that post, please click on the next link (&lt;a href="http://www.quantshare.com/sa-507-industry-analysis-how-to-compare-stocks-with-their-industries"&gt;Industry Analysis - How to Compare Stocks with their Industries&lt;/a&gt;) to learn how to download industry data and install the function that allows you to associate stocks with industries. When done, come back here to learn how to create 4 market indicators based on industry data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Number of stocks that are outperforming their industry&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let me show you how to create a composite.&lt;br /&gt;
&lt;br /&gt;
The composite manager, which contains all the composites you have created or downloaded from the sharing server, can be opened by selecting "Tools -&gt; Composites".&lt;br /&gt;
&lt;br /&gt;
To create a new composite, click on "Add" button.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Steps&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Define symbols&lt;/u&gt;: Using the symbols filter control, add one or several conditions to filter the symbols that will be included in the composite calculation&lt;br /&gt;
&lt;u&gt;Formula&lt;/u&gt;: Type your composite formula; the composite time series will be constructed using that formula&lt;br /&gt;
&lt;u&gt;Calculation Method&lt;/u&gt;: Define what to do with symbol's values for each trading bar.&lt;br /&gt;
&lt;br /&gt;
Example: If you choose "Calculate the sum of the values added to the composite" and your composite contains 50 symbols, then each trading bar will have approximately 50 values (returned by computing the formula for each symbol). The composite value on each bar will be the sum of all symbols values.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Period &amp; Time frame&lt;/u&gt;: Define the calculation start and end dates as well as the period or time frame to use in the calculation. You can create EOD or Intraday composites.&lt;br /&gt;
&lt;br /&gt;
Ok, now that I have explained how to create a composite, let us start with our first industry market indicator.&lt;br /&gt;
&lt;br /&gt;
The "Number of stocks that are outperforming their industry", is a composite that counts the number of stocks that are performing better than their industry. The performance here is measure for the previous 25 bars (One month approximately).&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Steps&lt;/u&gt;:&lt;br /&gt;
- Create a new composite&lt;br /&gt;
- Include all your stocks or the ones that have "industry" field filled&lt;br /&gt;
&lt;br /&gt;
To do this, create a new "Symbols Info" condition in symbols filter. &lt;br /&gt;
Click on the cell under "Values" and choose "industry". Type "([a-z]|[A-Z])*" next to "Search:".&lt;br /&gt;
&lt;br /&gt;
- In the composite formula editor, type:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;perfStock = perf(close, 25);&lt;br /&gt;
i = GetSeries("^INDUSTRY_".IndustryIndex(), close, LastData);&lt;br /&gt;
perfIndustry = perf(i, 25);&lt;br /&gt;
composite = perfStock &gt; perfIndustry;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Formula Explanation&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
Line 1: Here, we calculate the performance of the stock for the previous 25 bars (return).&lt;br /&gt;
Line 2: The industry price series is obtained using the "GetSeries" function.&lt;br /&gt;
Line 3: Calculates the performance of the industry for the previous 25 bars.&lt;br /&gt;
Line 4: Compares the performance of the stock with its industry. Return "1" if the stock's performance is higher than its industry's performance.&lt;br /&gt;
&lt;br /&gt;
- For the calculation method, use "Calculate the sum of the values added to the composite"&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Advancing-declining industries&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This is the number of industries that are advancing minus the number of industries that are declining. It is much like the advancing/declining indicator for stocks.&lt;br /&gt;
&lt;br /&gt;
This market indicator is created by adding all symbols whose name start with "^INDUSTRY" and then typing the following formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;&lt;br /&gt;
adv = close &gt; close[1]; // close compared to the close of the previous bar&lt;br /&gt;
dec = close &lt; close[1];&lt;br /&gt;
composite = adv - dec;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The calculation method is: Sum of the values added to the composite.&lt;br /&gt;
&lt;br /&gt;
To add symbols, whose name start with "^INDUSTRY", create a new "Symbol Info -&gt; Name" condition in the "Symbols Filter" of the composite (first screen) then type "^INDUSTRY*".&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/industrycomposite_1.gif" title="Advancing-declining industries" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Number of stocks performing 5% better than their industry&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This composite calculates the number of stocks whose performance is 5% above the performance of their industry.&lt;br /&gt;
&lt;br /&gt;
The composite formula is as follow:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;perfStock = perf(close, 25);&lt;br /&gt;
i = GetSeries("^INDUSTRY_".IndustryIndex(), close, LastData);&lt;br /&gt;
perfIndustry = perf(i, 25);&lt;br /&gt;
composite = perfStock &gt; 1.05 * perfIndustry;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The formula looks like the formula of the first composite. In this one, we have multiplied the industry performance by "5%" (1.05).&lt;br /&gt;
&lt;br /&gt;
The calculation method is: "Calculate the sum of the values..."&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Ratio of stocks outperforming/underperforming their industry&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This market indicator is calculated by dividing the number of stocks outperforming their industry by the number of stocks underperforming their industry.&lt;br /&gt;
&lt;br /&gt;
This is the most advanced composite, as it requires that we calculate two composites and use a C# script to create the ratio.&lt;br /&gt;
&lt;br /&gt;
The formula is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;perfStock = perf(close, 25);&lt;br /&gt;
i = GetSeries("^INDUSTRY_".IndustryIndex(), close, LastData);&lt;br /&gt;
perfIndustry = perf(i, 25);&lt;br /&gt;
composite = perfStock &gt; perfIndustry; // Outperform&lt;br /&gt;
AddComposite("underperfom", perfStock &lt; perfIndustry, _CompSum);&lt;br /&gt;
&lt;br /&gt;
// Calculation Method: The sum of the values added to the composite&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The first four lines are the same as in the "Number of stocks that are outperforming their industry" composite.&lt;br /&gt;
The last function (AddComposite) creates a second internal composite for stocks underperforming their industry.&lt;br /&gt;
&lt;br /&gt;
The next step would be to create the script.&lt;br /&gt;
&lt;br /&gt;
- Click on the "Script" button under the formula editor (located at right), then type the following script:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;double[] outperform = Functions.GetVariable("composite");&lt;br /&gt;
double[] underperfom = Functions.GetVariable("underperfom");&lt;br /&gt;
&lt;br /&gt;
for(int i=0;i &lt; outperform.Length;i++)&lt;br /&gt;
{&lt;br /&gt;
	double ratio = outperform[i]; // Default in case there are no underperforming stocks&lt;br /&gt;
	if(underperfom[i] != 0)&lt;br /&gt;
	{&lt;br /&gt;
		ratio = outperform[i] / underperfom[i];&lt;br /&gt;
	}&lt;br /&gt;
	outperform[i] = ratio; // Replace outperform value with ratio value&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Functions.SetCompositeData(outperform); // Set ratio array&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Basically, the script gets the underperforming and outperforming composites. It then loops through each trading bar and divide the former by the latter. The result is returned using the "Functions.SetCompositeData" function.&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/Lw9Kf3WzLsI" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/Lw9Kf3WzLsI/sa-508-4-market-composite-indicators-based-on-industry-data</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-508-4-market-composite-indicators-based-on-industry-data</guid>
        <pubDate> Fri, 14 Dec 2012 11:00:52 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-508-4-market-composite-indicators-based-on-industry-data</feedburner:origLink></item>  
     <item>
        <title> Industry Analysis - How to Compare Stocks with their Industries</title>
        <description>If you want to use a stock and its industry data on the same chart, strategy or composite, then keep reading. The technique I am presenting here will show you how to associate a stock with an industry index. After completing it, you will be able to display the performance of a stock and its industry on the same chart, calculate the relative strength of a stock compared to its industry, calculate the number of stocks that are outperforming their industries and so on.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Downloading Industry Data&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Of course, the first thing you have to do is to download historical EOD data for the different U.S. industries.&lt;br /&gt;
&lt;br /&gt;
Fortunately, we already have such downloader in the sharing server. &lt;ref&gt;452&lt;/ref&gt; item downloads historical quotes for more than 90 industries.&lt;br /&gt;
&lt;br /&gt;
Simply download the trading item and start it from the download manager to get the data. You will end up having +90 new ticker symbols, all starting with "^INDUSTRY_" keyword.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;For example&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;^INDUSTRY_TELEPHONE SYS.&lt;br /&gt;
^INDUSTRY_TEXTILE MILL&lt;br /&gt;
^INDUSTRY_WASTE MGT.&lt;br /&gt;
^INDUSTRY_WATER COMPANIES&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to associate a stock with the industry index&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Before implementing the function that will associate an industry with its corresponding ticker symbol, you have to make sure the industry field is filled for each of your stocks. You can do that manually but why bother when there is an automatic way to do so.&lt;br /&gt;
&lt;br /&gt;
- Select "Symbol -&gt; Auto Manage Symbols"&lt;br /&gt;
- Make sure you have US exchanges checked (New York Stock Exchange, NASDAQ and American Stock Exchange). You might also add "Over the counter" for OTC stocks.&lt;br /&gt;
- Check "Force the update of symbol information"&lt;br /&gt;
- Click on "Save"&lt;br /&gt;
&lt;br /&gt;
Within few seconds, symbols information of each of your stocks will be updated and you will have the industry name of each stock.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, everything should be set up correctly.&lt;br /&gt;
&lt;br /&gt;
The indicator that will perform the association contains a hash table (sort of dictionary) that stores the industry names and their corresponding ticker symbols. When the indicator is called, it will perform the following actions:&lt;br /&gt;
&lt;br /&gt;
- Get current symbol name&lt;br /&gt;
- Get industry name for that symbol&lt;br /&gt;
- Check the table and extract the corresponding ticker symbol (From the symbols that were added by the previous downloader)&lt;br /&gt;
&lt;br /&gt;
This indicator can be downloaded here: &lt;ref&gt;1215&lt;/ref&gt;&lt;br /&gt;
&lt;br /&gt;
You can check its code by selecting "Tools -&gt; Creation Function" then clicking on the indicator (IndustryIndex) in the left panel.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Stock and industry data on the same chart&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Now, let us display a stock and its corresponding industry on the same chart.&lt;br /&gt;
&lt;br /&gt;
- Select "View -&gt; New Chart" to open a new chart&lt;br /&gt;
- Right click on the chart and select "Create new pane"&lt;br /&gt;
&lt;br /&gt;
In this pane, we are going to display industry graph&lt;br /&gt;
- Right click on the new pane then select "Edit Formula"&lt;br /&gt;
- Type the following formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;b = IndustryIndex();&lt;br /&gt;
a = "^INDUSTRY_".b;&lt;br /&gt;
a = GetSeries(a, close, LastData);&lt;br /&gt;
Plot(a, b, colorGreen, ChartLine, StyleSymbolNone);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Interpretation&lt;/u&gt;:&lt;br /&gt;
Line 1: Get industry name as defined by the industry data downloader (see above)&lt;br /&gt;
Line 2: Create the industry ticker symbol&lt;br /&gt;
Line 3: Get industry price series&lt;br /&gt;
Line 4: Plot industry data&lt;br /&gt;
&lt;br /&gt;
- Click on "Update Graph" to save changes&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/industrystrength_1.gif" title="Industry Analysis - How to Compare Stocks with their Industries" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
There is another way to display the industry graph. It consists of creating another trading indicator (Example: IndustryEquity) and use something similar to the above code directly within the formula. Once the indicator is completed, you can display the same industry graph by typing:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = IndustryEquity();&lt;br /&gt;
Plot(a, industry(), colorGreen, ChartLine, StyleSymbolNone);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The "IndustryEquity" indicator can be created using "Tools -&gt; Create Functions" and its C# code would be:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;VectorS b = cFunctions.CompileFormula("b = IndustryIndex();").GetVectorString("b");&lt;br /&gt;
b = "^INDUSTRY_" + b;&lt;br /&gt;
result = cFunctions.GetTimeframeData(b[0], cFunctions.Timeframe, "close").ToVectorD();&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
You can download this indicator from the sharing server here: &lt;ref&gt;1216&lt;/ref&gt;.&lt;br /&gt;
&lt;br /&gt;
Once your chart is ready, you can save the layout for later use. Right click on the chart, Select "Layout" then "Save Layout As".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Simple trading system based on relative strength&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The strategy we are going to develop will be called "Industry Relative Strength Trading System". It consists of buying the top 20 stocks that have the best relative strength compared to their industries.&lt;br /&gt;
&lt;br /&gt;
First, you should know that industry relative strength has nothing to do with the relative strength indicator (RSI). The term indicates the relative performance of a stock compared to the performance of its industry.&lt;br /&gt;
&lt;br /&gt;
The strategy formula is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = close; // Stock value&lt;br /&gt;
b = GetSeries("^INDUSTRY_".IndustryIndex(), close, LastData); // Industry value&lt;br /&gt;
&lt;br /&gt;
a1 = perf(a, 25); // Performance of stock for the last month&lt;br /&gt;
b1 = perf(b, 25); // Performance of industry for the last month&lt;br /&gt;
&lt;br /&gt;
ratio = (a1 - b1); // Industry Relative Strength which consist of the difference of stock return and industry return over the previous month&lt;br /&gt;
&lt;br /&gt;
buy = ratio &gt; 0 and close &gt; 5; // Buy only stocks that are outperforming their industry&lt;br /&gt;
SetSimLongRank(ratio); // Rank stocks by their industry relative strength value&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;To create this trading system&lt;/u&gt;:&lt;br /&gt;
- Select "Analysis -&gt; Simulator"&lt;br /&gt;
- Click on "New" to create a new trading system&lt;br /&gt;
- Select "20" in "Number of Position" (top)&lt;br /&gt;
- At the bottom, set an N-Bar stop with "25" as value&lt;br /&gt;
- Select "Create trading system using the formula editor" tab&lt;br /&gt;
- Type the above strategy formula&lt;br /&gt;
- Click on "Create Trading System"&lt;br /&gt;
&lt;br /&gt;
This trading system is already available in the sharing server. You can download it here: &lt;ref&gt;1217&lt;/ref&gt;.&lt;br /&gt;
&lt;br /&gt;
Any questions?&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/j8dJ1FxuGt4" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/j8dJ1FxuGt4/sa-507-industry-analysis-how-to-compare-stocks-with-their-industries</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-507-industry-analysis-how-to-compare-stocks-with-their-industries</guid>
        <pubDate> Thu, 06 Dec 2012 11:46:02 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-507-industry-analysis-how-to-compare-stocks-with-their-industries</feedburner:origLink></item>  
     <item>
        <title> How to Backtest Each Stock or Asset Individually</title>
        <description>QuantShare simulator is a &lt;a href=http://www.quantshare.com/sa-42-true-portfolio-simulation-applied-to-trading-systems&gt;true portfolio backtester&lt;/a&gt;. This means that the backtesting or simulation generates trading orders by taking into account things such as the available cash, pending orders, open positions, margin, equity... at any moment during the process.&lt;br /&gt;
&lt;br /&gt;
Some traders want to backtest their trading system for each stock or security in their list and have individual report for each stock. How each stock would have performed if it were the only security allowed to be bought by the trading system?&lt;br /&gt;
&lt;br /&gt;
In this post, I will show you how to create to create a trading system and optimize it so that each optimization backtests a single stock. After that, I will show you how to get a single page report of each individual stock backtest.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Prepare your list of stocks&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let us prepare the list of stocks or securities that we want to backtest individually.&lt;br /&gt;
This list must contain one ticker symbol per line and it must be saved under a file.&lt;br /&gt;
&lt;br /&gt;
Using the watchlist tool, create your watchlist, right click on the table then click on "Copy all symbols to clipboard"&lt;br /&gt;
Using the screener too, create a scan, run it then click on the "Copy symbols to clipboard button"&lt;br /&gt;
&lt;br /&gt;
Now, using any text editor, open a new file then paste the symbols list using CONTROL+V shortcut. This will copy the data contained in the clipboard to the text editor.&lt;br /&gt;
&lt;br /&gt;
Save the file under a specific location (Example: c:\mylist.txt)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Custom trading indicator&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This trading indicator reads the previous list we have created and returns true or "1" if the symbol corresponds to the index in the list. Note that both the symbol and the index are passed to the function.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
Our list:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;ARL&lt;br /&gt;
ARO&lt;br /&gt;
ARSD&lt;br /&gt;
ART&lt;br /&gt;
ARW&lt;br /&gt;
ARX&lt;br /&gt;
ASH&lt;br /&gt;
ASI&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Function:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = SymbolIndex("ARO", 1); // Returns true&lt;br /&gt;
a = SymbolIndex("ARO", 0); // Returns false&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is how to implement this custom indicator:&lt;br /&gt;
&lt;br /&gt;
- Select "Tools -&gt; Create Functions"&lt;br /&gt;
- Click on "Add" to create a new indicator/function&lt;br /&gt;
- Type "SymbolIndex" then click on "Save"&lt;br /&gt;
- In "Parameters" panel (bottom/right), add two parameters:&lt;br /&gt;
&lt;br /&gt;
Format: Name/Type:&lt;br /&gt;
1/ Symbol/String&lt;br /&gt;
2/ Index/Number&lt;br /&gt;
&lt;br /&gt;
- Type the following code in the right panel then click on "Save"&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;string fileLocation = @"c:\mylist.txt";&lt;br /&gt;
string[] lines = System.IO.File.ReadAllLines(fileLocation);&lt;br /&gt;
&lt;br /&gt;
int index1 = (int)index[0];&lt;br /&gt;
string symbol1 = symbol[0].ToLowerInvariant();&lt;br /&gt;
&lt;br /&gt;
if(index1 &lt; 0)&lt;br /&gt;
{&lt;br /&gt;
result.Assign(lines.Length);&lt;br /&gt;
}&lt;br /&gt;
else if(index1 &lt; lines.Length)&lt;br /&gt;
{&lt;br /&gt;
string symbol2 = lines[index1].Trim().ToLowerInvariant();&lt;br /&gt;
if(symbol1 == symbol2)&lt;br /&gt;
{&lt;br /&gt;
result.Assign(1);&lt;br /&gt;
}&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
This trading indicator is already available in the sharing server: &lt;ref&gt;1209&lt;/ref&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Create the trading system&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
You probably already have the trading system you want to backtest for each stock individually.&lt;br /&gt;
&lt;br /&gt;
If you don't then create a new one (Analysis -&gt; Simulator -&gt; New), select "Create a trading system using the formula editor" then type these simple buy and sell rules:&lt;br /&gt;
&lt;br /&gt;
buy = rsi(14) &gt; 70;&lt;br /&gt;
sell = rsi(14) &lt; 30;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now that we have our trading system, we must do three things:&lt;br /&gt;
&lt;br /&gt;
- &lt;u&gt;Maximum number of symbols&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
Set the number of positions field to "1". It is important if we want to invest 100% of the portfolio cash in a single asset.&lt;br /&gt;
&lt;br /&gt;
- &lt;u&gt;Set the list of symbols&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
In the trading system editor, select "Symbols &amp; Dates" tab at the top, remove all symbols filters, add a new "Custom Symbols" condition, click on the cell under "Values" then paste the symbols list (Copy it from the text file CONTROL+C and paste it here CONTROL+V).&lt;br /&gt;
&lt;br /&gt;
- &lt;u&gt;Update the buy/short rule&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
In the strategy formula editor of your trading system, we must add an additional rule that instructs the simulator to analyze only one stock on each run.&lt;br /&gt;
&lt;br /&gt;
The additional rule is as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Optimize("sindex", 0, SymbolIndex(name(), -1), 1);&lt;br /&gt;
buy = buy and SymbolIndex(name(), sindex);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
It adds up to the original buy rule and returns true only if the symbol name (name() function) corresponds to the "sindex" index. Here, "sindex" is an optimizable variable that vary from 0 to the number of symbols in the text file (minus 1 set as second parameter of the 'SymbolIndex' function).&lt;br /&gt;
&lt;br /&gt;
Save your trading system before reading the next paragraph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Backtest Stocks Individually&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In the "Simulator Manager" (Analysis -&gt; Simulator), select the previously updated trading system then click on "Optimize" to backtest the trading system N-times, each time using a different stock or security. &lt;br /&gt;
&lt;br /&gt;
In the simulation report, each row contains the backtest results of a different stock. &lt;br /&gt;
The unique problem here is that the symbol being backtested is not displayed.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/backtest_indiv_1.gif" title="How to Backtest Each Stock or Asset Individually" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Here is how to fix this&lt;/u&gt;:&lt;br /&gt;
- Update the trading system&lt;br /&gt;
- Select "Money Management" tab&lt;br /&gt;
- Click on "Add a new money management script"&lt;br /&gt;
- Select "OnStartSimulation" event then type:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Functions.AddReportMetric("Symbol", "");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Select "OnEndSimulation" event then type:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;MMPosition[] pos = Portfolio.GetAllPositions();&lt;br /&gt;
if(pos.Length &gt; 0)&lt;br /&gt;
{&lt;br /&gt;
Variables.SetVariable("Symbol", pos[0].Symbol);&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Optimize your trading system again to display the symbol name in the simulation report table.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/backtest_indiv_2.gif" title="How to Backtest Each Stock or Asset Individually" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Backtest Report&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
After the individual stock backtesting is completed, select your trading system in the simulator manager and click on "Tools -&gt; Optimization Report" to display different statistics of each backtest.&lt;br /&gt;
&lt;br /&gt;
You can export the data by selecting it then using CONTROL+C. Use CONTROL+V to paste the previously copied data.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/backtest_indiv_3.gif" title="How to Backtest Each Stock or Asset Individually" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After reading and using the technique described here, you may want to combine two or more securities and backtest the different combinations. We have a nice tutorial about how to accomplish this: &lt;a href="http://www.quantshare.com/sa-291-select-the-best-etfs-combination-to-maximize-your-return-and-reduce-your-investment-risk"&gt;Select the best ETFs combination to maximize your return and reduce your investment risk&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/zJh2M1_YgaU" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/zJh2M1_YgaU/sa-502-how-to-backtest-each-stock-or-asset-individually</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-502-how-to-backtest-each-stock-or-asset-individually</guid>
        <pubDate> Thu, 15 Nov 2012 11:37:01 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-502-how-to-backtest-each-stock-or-asset-individually</feedburner:origLink></item>  
     <item>
        <title> QuantShare Programming Language Tutorial</title>
        <description>The QS programming language allows you to do different things in QuantShare. It can be used to:&lt;br /&gt;
&lt;br /&gt;
- Plot candlesticks and indicators on a chart&lt;br /&gt;
- Define a trading system buy, sell, short and cover rules&lt;br /&gt;
- Create trading indicators&lt;br /&gt;
- Create a composite indicator&lt;br /&gt;
- Scan stocks&lt;br /&gt;
- Create watchlists&lt;br /&gt;
- Implement fitness functions for the PBIL and genetic algorithm optimizers&lt;br /&gt;
- And more...&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
A QuantShare formula is a collection of statements or commands, which tells QuantShare what to do and what to calculate.&lt;br /&gt;
&lt;br /&gt;
Commands usually contain variables and functions:&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Variables&lt;/u&gt;: The variables are at the core of any program. Their role is store information, so that the program can use that information later.&lt;br /&gt;
Not all variables are the same. Each variable can store a particular type of data. In QuantShare, we have two types of data: Numeric and Text.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
- Create two variables: The first one stores the moving average data and the second one stores the close price.&lt;br /&gt;
- Compare the value of these variables. In other words, we are comparing the close price with the moving average.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Functions&lt;/u&gt;: A function is something you call in a program to perform a specific task. There are two different types of functions: &lt;br /&gt;
Function that performs a task and returns a value&lt;br /&gt;
Function that performs a task and do not return a value&lt;br /&gt;
&lt;br /&gt;
Examples:&lt;br /&gt;
- The "SMA" function calculates the moving average of a stock and returns the moving average data.&lt;br /&gt;
- The "Plot" function plots an indicator on a chart. This function returns not values.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Different Elements of a QS formula&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
As we said above, a QuantShare formula is composed of a collection of statements. &lt;br /&gt;
Each statement must end with a semi-colon ";". This how the program recognizes that a statement ends.&lt;br /&gt;
Each statement is composed of several tokens. A token is the minimal lexical element of a programming language.&lt;br /&gt;
&lt;br /&gt;
Here is a list of the different tokens:&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Identifiers&lt;/u&gt;: Composed of variables and functions&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Literals&lt;/u&gt;: Literals or constants are values that cannot be changed. The value of a literal is obvious because it is written in the program literally. There are two types of literals in QuantShare: Numeric (double) or Text (string).&lt;br /&gt;
&lt;br /&gt;
Examples:&lt;br /&gt;
Numeric constant: 10&lt;br /&gt;
Text constant: "Hello"&lt;br /&gt;
&lt;br /&gt;
Note that that "string" constants are always enclosed in quotes or single quotes. Otherwise, the program will think that this is a variable name or a function.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Operators&lt;/u&gt;: An operator is a symbol that represents a specific action.&lt;br /&gt;
&lt;br /&gt;
The plus sign (+) is an operator that represents addition.&lt;br /&gt;
The basic mathematic operators are:&lt;br /&gt;
(+) =&gt; Addition&lt;br /&gt;
(-) =&gt; Subtraction&lt;br /&gt;
(*) =&gt; Multiplication&lt;br /&gt;
(/) =&gt; Division&lt;br /&gt;
(+) =&gt; Addition&lt;br /&gt;
-&gt; Make these appears in a table&lt;br /&gt;
&lt;br /&gt;
Relational and equality Operators:&lt;br /&gt;
&lt; =&gt; Less than&lt;br /&gt;
&gt; Greater than&lt;br /&gt;
&lt;= Less than or equal to&lt;br /&gt;
&gt;= Greater than or equal to&lt;br /&gt;
== Equal to&lt;br /&gt;
!= Not equal to&lt;br /&gt;
&lt;br /&gt;
Assignment operator:&lt;br /&gt;
= Store the value returned by the expression after the "=" in the variable specified before "=".&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = 5 + 2;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Here is how it works:&lt;br /&gt;
&lt;br /&gt;
The program finds the assignment operator (=) and then understands that it must store the value returned by the expression located at the right in the variable "a".&lt;br /&gt;
It then calculates that expression, which is a simple mathematical addition that returns (7).&lt;br /&gt;
It stores (7) in the variable (a).&lt;br /&gt;
&lt;br /&gt;
Let us create another instruction:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;b = a / 2;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
When calculating the expression (a / 2). The program already knows that the variable "a" is equal to 7 and thus returns (3.5), which is equal to (7 / 2).&lt;br /&gt;
The value (3.5) is stored in the variable (b).&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Punctuators&lt;/u&gt;: They are used to separate line of codes, variables etc. They are also called separators.&lt;br /&gt;
&lt;br /&gt;
As we said previously, each statement must end with a semi-colon and therefore the semi-colon is a punctuator.&lt;br /&gt;
&lt;br /&gt;
Other punctuators: ; , = ()&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;QuantShare Language Basics&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
As we said previously, identifiers are composed of variables and functions.&lt;br /&gt;
&lt;br /&gt;
QuantShare has some built-in variables that identify specific price fields and which are: close, open, high, low, volume and openint.&lt;br /&gt;
&lt;br /&gt;
Example using the assignment operator:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = close;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
// the variable "a" contains now the same data as the "close" built-in variable.&lt;br /&gt;
&lt;br /&gt;
A QuantShare variable in fact does not store a single value (such as 18), it stores an array or a list of numeric/text values. This list contains the values that correspond to each trading bar.&lt;br /&gt;
&lt;br /&gt;
Let us take the "close" variable as an example:&lt;br /&gt;
&lt;br /&gt;
Here is how to the "close" variable looks like (Just an example):&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__index.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Each index corresponds to a trading bar. If we are working with daily data, then each index correspond to a date.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__index1.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__date.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
For instance, the second index (1) corresponds to the date (1/11/2012) and the close price at that date is "10.6".&lt;br /&gt;
&lt;br /&gt;
Using one-minute data, each index/bar correspond to a date/time.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__index1.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__datetime.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Basic Operations&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
Operations, whether they are mathematical or relational are performed on each index.&lt;br /&gt;
&lt;br /&gt;
If you add the value of two variables:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = open + close;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__open.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__plus.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
Then for each index, the value of "open" and "close" will be added and a new array is associated to the "a" variable.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Another Example:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = open &gt; close;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__open.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__higher.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
"1" for true and "0" for false.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;QuantShare Functions&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
A function is something you call in a program to perform a specific task.&lt;br /&gt;
&lt;br /&gt;
For example, the "SMA" function calculates a simple moving average.&lt;br /&gt;
&lt;br /&gt;
Function Syntax:&lt;br /&gt;
FunctionName([Parameters])&lt;br /&gt;
&lt;br /&gt;
Each function has zero, one or more parameters. Parameters are variables or statements specified after the function name, inside the parentheses. They are passed to the function so that this function can use them to perform its calculation. Parameters are separated by colons ",".&lt;br /&gt;
&lt;br /&gt;
For example, you can pass a period to the "SMA" function to specify the number of bars to use to calculate the moving average.&lt;br /&gt;
A 5-Bar simple moving average can be called as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = sma(5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Here, we use the assignment operator to save the result of the "sma" function in the "a" variable.&lt;br /&gt;
&lt;br /&gt;
The "a" variable now contains the moving average data.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__sma.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
Nan: Not a number&lt;br /&gt;
Because in the above example, the SMA function requires 5 elements to perform its calculation, it cannot calculate the moving average of the first four elements and this is why it sets the "NaN" value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Popular Functions&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Here are some of the most popular functions in QuantShare:&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Ref&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
References a previous or subsequent element in a ARRAY. A negative period references X periods in the future; a positive period references X periods ago&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = ref(close, 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__ref.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Hhv&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
For each trading bar, calculates the highest value over a specified period.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = hhv(close, 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__hhv.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Llv&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
For each trading bar, calculates the lowest value over a specified period.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = llv(close, 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__llv.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Sum&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
Calculates a cumulative sum of the ARRAY for the specified period&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = sum(close, 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__sum.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that there are more than 200 built-in functions in QuantShare. In the formula editor, type a variable name, the assignment operator (a = ) then click on CONTROL+SPACE to display the list of available function.&lt;br /&gt;
&lt;br /&gt;
After you type the indicator name and the first parentheses (Example: "a = sma(" ), you will see a tooltip above the function name. This tooltip shows a brief description of that function and it also shows you the parameters that are required by that function. &lt;br /&gt;
&lt;br /&gt;
Besides, you can sometimes see something like "1 of 2" or "1 of 3" before the function name. This means that the function can accept several combinations of parameters. Click on the tooltip to display the other parameter combinations.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
Type: &lt;span style="color:#1C74A8"&gt;a = sma(&lt;/span&gt;&lt;br /&gt;
In the tooltip, you can see:&lt;br /&gt;
&lt;br /&gt;
1 of 2  Number  Sma(~Number timeperiod)&lt;br /&gt;
&lt;br /&gt;
This means that the "Sma" function has two different parameter combinations. &lt;br /&gt;
The first "Number" means that it returns a numeric variable (array) and that it accepts only one parameter (numeric) that corresponds to the time period.&lt;br /&gt;
&lt;br /&gt;
After you click on that tooltip, you will see:&lt;br /&gt;
&lt;br /&gt;
2 of 2  Number  Sma(~Number close, ~Number timeperiod)&lt;br /&gt;
&lt;br /&gt;
This is the second definition of the "Sma" function. It accepts two parameters (close and timeperiod) and returns a numeric variable.&lt;br /&gt;
In the second definition, you can specify the time-series that will be used to calculate the moving average. In the first definition, the "close" series is used by default. In the second one, you can specify a custom time-series.&lt;br /&gt;
&lt;br /&gt;
Definition 1: &lt;span style="color:#1C74A8"&gt;a = sma(5);&lt;/span&gt;&lt;br /&gt;
Definition 2: &lt;span style="color:#1C74A8"&gt;a = sma(close, 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The above instructions return the same data.&lt;br /&gt;
&lt;br /&gt;
Here is another example based on the second definition:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = sma(sma(10), 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The above instruction calculates the 5-bar moving average of the 10-bar moving average.&lt;br /&gt;
&lt;br /&gt;
It is the same as the following formula:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = sma(10);&lt;br /&gt;
a = sma(a, 5);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Instead of passing the 10-bar sma function directly in the first parameter, we store the data in the variable "a" and pass it to the second "sma" function.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Difference between Assignment and Equality&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The assignment operator is something very important. It lets us assign the result of the expression on the right side of the operator to the variable on the left side.&lt;br /&gt;
&lt;br /&gt;
In the example below, the value of the moving average is assigned to variable "a" and the variable "a" is assigned to variable "b".&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = sma(10);&lt;br /&gt;
b = a;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
At the end, the value of "b" is equal to "a" and it is equal to SMA (simple moving average).&lt;br /&gt;
&lt;br /&gt;
The equality operator (==) is used to check whether the two expressions on both sides are equal or not. It compares each element of the array individually and returns true (or  &lt;br /&gt;
"1") of they are equal, and false (or "0") if they are not.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = close == 10;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The above function uses both the assignment and the equality operators.&lt;br /&gt;
It first compares the close array with the value (10) then assigns the result of that expression to the variable (a)&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__close.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/qs_formula__equal.gif" title="QuantShare Programming Language Tutorial" /&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/yNgvlovdIPI" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/yNgvlovdIPI/sa-499-quantshare-programming-language-tutorial</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-499-quantshare-programming-language-tutorial</guid>
        <pubDate> Thu, 08 Nov 2012 10:04:44 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-499-quantshare-programming-language-tutorial</feedburner:origLink></item>  
     <item>
        <title> Sentiment Analysis: How to measure the sentiment score of your stock tweets</title>
        <description>This post is for advanced traders. Today, I will show you how to measure the sentiment of stock tweets (or any other asset's tweets) and to give them a score depending on how positive or negative they are.&lt;br /&gt;
&lt;br /&gt;
The sentiment of each tweet and its score will be saved in a custom database so that you can use them later to create charts, composites, trading systems or neural network models.&lt;br /&gt;
&lt;br /&gt;
For example, let us take the following tweets:&lt;br /&gt;
GOOG stock is bullish&lt;br /&gt;
GOOG stock is bearish&lt;br /&gt;
&lt;br /&gt;
The former tweet will get these results: Positive (score: 0.46918)&lt;br /&gt;
The latter tweet will get: Negative (score: -0.55188)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Downloading Stock Tweets&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let us download some stock tweets to analyze them and give them a sentiment score.&lt;br /&gt;
&lt;br /&gt;
- Download the following item: &lt;ref&gt;86&lt;/ref&gt;&lt;br /&gt;
- Install the downloader (&lt;a href="http://www.quantshare.com/how-276-how-to-download-a-trading-item-from-the-sharing-server"&gt;Instructions&lt;/a&gt;)&lt;br /&gt;
- Select it in QuantShare (Download -&gt; Download Manager)&lt;br /&gt;
- Click on "Open Selected Downloader" then on "Start Downloading" button&lt;br /&gt;
&lt;br /&gt;
Once the data is downloaded, you can display it by selecting "Tools -&gt; Database Data" then "Stocktwits" database.&lt;br /&gt;
The tweets displayed there are the ones that belongs to the active symbol (Symbol from the selected chart)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Alchemy API&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Alchemy API is an application capable of identifying positive and negative sentiment within a text. It supports both English and German content.&lt;br /&gt;
&lt;br /&gt;
Before using this API, you should &lt;a href="http://www.alchemyapi.com/api/register.html"&gt;open a free account&lt;/a&gt; @ www.alchemyapi.com to get the API Key. You can use that key free of cost and make a maximum of 1000 API calls a day, which should be sufficient to measure the sentiment of our tweets. You may also choose the commercial option to get more API calls.&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://www.alchemyapi.com/api/sentiment/textc.html"&gt;Here is how to measure the sentiment of a specific text&lt;/a&gt;:&lt;br /&gt;
http://access.alchemyapi.com/calls/text/TextGetTextSentiment?apikey=[API KEY]&amp;text=[TEXT]&lt;br /&gt;
&lt;br /&gt;
Replace "[API KEY]" by your API key (sent to you by email) and "[TEXT]" by the text you want to analyze&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Updating the Stocktwits database&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
After measuring the sentiment of each tweet, we would like to store the sentiment and its score in a custom database. We can do that by creating a new database or we can add two new fields to the existing "stocktwits" database.&lt;br /&gt;
&lt;br /&gt;
Here, we will implement the second solution:&lt;br /&gt;
&lt;br /&gt;
- Select "Data -&gt; Edit Databases"&lt;br /&gt;
- Select "Custom" next to "Choose database" then choose the "stocktwits" custom database&lt;br /&gt;
- At the bottom of the control, click on "Add Field" then add the following fields:&lt;br /&gt;
&lt;br /&gt;
-&gt; Field Name: Sentiment&lt;br /&gt;
-&gt; Field Type: Double&lt;br /&gt;
&lt;br /&gt;
-&gt; Field Name: Score&lt;br /&gt;
-&gt; Field Type: Double&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Updating the Stocktwits downloader&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In order to access the newly created "sentiment" and "score" fields, we must update the "stocktwits" downloader so that it updates these fields with empty values ("0").&lt;br /&gt;
&lt;br /&gt;
- Select "Download -&gt; Download Manager" then select "StockTwits" item&lt;br /&gt;
- Click on "Update" at the top of the control&lt;br /&gt;
- Click on "Parser" button (under "Parser" column)&lt;br /&gt;
- Click on "Next" then add two columns by clicking twice on the "Add Column" button&lt;br /&gt;
- In the column grid, update the last two columns we have just created by setting the following values:&lt;br /&gt;
&lt;br /&gt;
=&gt; Database -&gt; Field -&gt; Default&lt;br /&gt;
&lt;br /&gt;
stocktwits -&gt; sentiment -&gt; 0&lt;br /&gt;
stocktwits -&gt; score -&gt; 0&lt;br /&gt;
&lt;br /&gt;
- Click on "Next" twice then on "Finish" to close the parser control&lt;br /&gt;
- Click on "OK" to save the download item&lt;br /&gt;
- Run the downloader (It is important you run the downloader after performing these changes)&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/sentiment_alchemy_1.gif" title="Sentiment Analysis: How to measure the sentiment score of your stock tweets" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Note&lt;/u&gt;: In the "sentiment" column, "1" means "Positive", "-1" means "Negative" and "0.1" means "Neutral".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;QuantShare Script&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have downloaded tweets data, updated the database and opened a free account at Alchemy API, let us create a script that will loop through all our tweets and measure the sentiment score of each one.&lt;br /&gt;
&lt;br /&gt;
- Open the script editor by selecting "Tools -&gt; Script Editor -&gt; File -&gt; New" then enter a name for the script&lt;br /&gt;
- Copy the &lt;a href="http://www.quantshare.com/free/sentiment_alchemy_api.txt"&gt;script from here&lt;/a&gt; then paste it in the script editor&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Brief explanation of how this script works&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
- Get all symbols and loop through each one&lt;br /&gt;
- For each symbol, get stock tweets data&lt;br /&gt;
- Loop through each tweet&lt;br /&gt;
- Perform the API call to get the sentiment analysis score of each tweet&lt;br /&gt;
- Parse the returned data&lt;br /&gt;
- Save the data&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Note&lt;/u&gt;: &lt;br /&gt;
- When the number of API calls exceeds 1000, the script will automatically stop. In this case, you have reached your API call limit and thus you should run the script the next day to calculate the sentiment measure of the remaining tweets.&lt;br /&gt;
- You must update the first line of the script by entering your own API (see above for how to get an API key)&lt;br /&gt;
- The script output can be found under "View -&gt; List Output".&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/sentiment_alchemy_2.gif" title="Sentiment Analysis: How to measure the sentiment score of your stock tweets" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Charting the Sentiment Score&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Everything is in place; our tweets as well as their sentiment score are stored in a custom database. This database can be accessed easily from the QuantShare and C# languages.&lt;br /&gt;
&lt;br /&gt;
- Open a new intraday chart then add a pane&lt;br /&gt;
- Select a symbol for which you have tweets and sentiment score data&lt;br /&gt;
- Click on the first icon to add an indicator&lt;br /&gt;
- Select "Databases / Fields" tab to add custom databases data&lt;br /&gt;
- Select "StockTwits" database then "score" field&lt;br /&gt;
- In the right panel, under "Get a value", select "Set missing values to zero" then click on "OK"&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/sentiment_alchemy_3.gif" title="Sentiment Analysis: How to measure the sentiment score of your stock tweets" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Trading System based on Tweets Sentiment&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
If you can access a custom database data with the QuantShare language then you can use that data to create charts, composites, screens, watchlists, trading systems, neural network models...&lt;br /&gt;
&lt;br /&gt;
Here is how to create basic trading systems with the tweets sentiment data:&lt;br /&gt;
&lt;br /&gt;
The first strategy consists of buying a stock if its score is higher than 0.5&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;score = GetData('stocktwits', 'score', Zero); // Access "score" data within the "stocktwits" database&lt;br /&gt;
buy = score &gt; 0.5;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The second one consists of buying a stock if it has at least two positive scores in the last hour&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;score = GetData('stocktwits', 'score', Zero);&lt;br /&gt;
buy = sum(score &gt; 0, 60) &gt;= 2; // Sum of previous 60 bars; assuming you are backtesting the trading system with a 1-minute period&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With minor tweaks, the same logic can be applied to any other data including stock news, commodities news, Forex commentaries and forum posts.&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/n2dUN5Dkvbk" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/n2dUN5Dkvbk/sa-496-sentiment-analysis-how-to-measure-the-sentiment-score-of-your-stock-tweets</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-496-sentiment-analysis-how-to-measure-the-sentiment-score-of-your-stock-tweets</guid>
        <pubDate> Thu, 01 Nov 2012 11:06:05 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-496-sentiment-analysis-how-to-measure-the-sentiment-score-of-your-stock-tweets</feedburner:origLink></item>  
     <item>
        <title> Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals</title>
        <description>&lt;div align="center"&gt;&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_1.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
A big thanks to Touini, who send us this case study on how to run QuantShare on the cloud (Amazon's EC2 Instance) and use that instance to generate signals for your trading strategies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Part1: Setting up QS on EC2&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
What is Amazon's EC2 and why would one want to run QuantShare "on the cloud"?&lt;br /&gt;
&lt;br /&gt;
Setting up an EC2 instance is like setting up a small PC on the cloud. You can install anything on this PC. You can choose the base OS (Windows, Linux, etc.) and then configure this virtual PC as needed. We will be using Windows OS and installing Quantshare.&lt;br /&gt;
&lt;br /&gt;
Potential reasons why it could be beneficial to run QuantShare on the cloud are:&lt;br /&gt;
1.	Have access to QuantShare from your ipad or iphone, anywhere in the world. &lt;br /&gt;
&lt;br /&gt;
2.	Schedule the downloaders and build the databases on the cloud without human intervention. Use SugarSync or Dropbox to "sync" the updated database to all home and office computers. &lt;br /&gt;
&lt;br /&gt;
3.	Automate generation of Buy/Sell signals. This includes e-mailing oneself the trading signals, running a trading advisory service or generating orders to sites like &lt;a href="http://collective2.com/" target="_blank"&gt;collective2.com&lt;/a&gt;. All without being at home and worrying about power/internet failures.&lt;br /&gt;
&lt;br /&gt;
4. 	Auto-trade an account. This is the most interesting application for real time traders. Especially mid-budget traders that are located outside the U.S., or suffer from bad internet connectivity and cannot afford to co-locate.&lt;br /&gt;
 &lt;br /&gt;
Let's start by setting up a virtual PC. There are many providers for cloud computing. We will be taking advantage of the Amazon current offer of one year &lt;a href="http://aws.amazon.com/free/" target="_blank"&gt;free access to a basic micro instance&lt;/a&gt; to new users.&lt;br /&gt;
&lt;br /&gt;
The micro instance is the smallest instance running at a virtual 1 Ghz, 613 MB Ram. It's not a lot of power but it's enough to run QuantShare and perform some basic tasks.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Steps:&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
1.	You need to sign up for an account with &lt;a href="http://aws.amazon.com/" target="_blank"&gt;Amazon.com&lt;/a&gt; unless you already have one. Even if you run the free micro instance, you will need to give out your credit card to Amazon. Please review Amazon's &lt;a href="http://aws.amazon.com/free/" target="_blank"&gt;offering&lt;/a&gt;. It should be enough to run free for a year.&lt;br /&gt;
&lt;br /&gt;
If you exceed the quota they give you, you will be charged. 2.&lt;br /&gt;
&lt;br /&gt;
Set up the instance. I used the Windows 2008 32bit AMI, but I guess you can use the Windows 2008 64bit R2 one. The lighter the package, the better since the micro instance has minimal RAM and CPU power.&lt;br /&gt;
&lt;br /&gt;
I will not go through the basic setup. This video will guide you through the steps:  &lt;a href="http://www.youtube.com/watch?v=ZAB8wCg9MyE" target="_blank"&gt;http://www.youtube.com/watch?v=ZAB8wCg9MyE&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
(Start from the middle of the video where he sets up the actual instance). If you don't like videos you can read this "how to guide":&lt;br /&gt;
&lt;a href="http://docs.amazonwebservices.com/AWSEC2/latest/WindowsGuide/EC2Win_GetStarted.html" target="_blank"&gt;http://docs.amazonwebservices.com/AWSEC2/latest/WindowsGuide/EC2Win_GetStarted.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
keep in mind, the default Security Group does not allow for a Remote Desktop Connection.&lt;br /&gt;
&lt;br /&gt;
When you get at the part of setting security groups, edit the default group and add port 3389 inside the "Port Range". Press "Add Rule'. This will open up the port for Remote Desktop Connection which is the non-programmer's way of controlling your remote PC. You can leave Source as is unless you have a static IP and are concerned over security.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_2.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Once you have set up port 3389 access you have the minimum to continue. Optionally you can open additional ports (SSH, FTP, etc).&lt;br /&gt;
&lt;br /&gt;
Assuming you have followed the video tutorial you have now a micro instance running on EC2.&lt;br /&gt;
&lt;br /&gt;
2. 	Connect to the instance using Remote Desktop Connection. Best way is to go to the AWS control panel, right click on the instance and choose Connect. This will download a file and fire up RDC with the right settings. Alternatively, start RDC (Start---&gt;search "remote") and point it to the instance's public IP address.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_3.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Choose "options" and type "Administrator" under User. Connect. Type in your instance's administrator password when asked. A window should open with your new desktop.&lt;br /&gt;
&lt;br /&gt;
3.	At this point, I was asked to setup my network as Home, Work or Public. I chose Public. That brought problems and caused Internet Explorer to refuse to download stuff... So... I downloaded Firefox. &lt;br /&gt;
&lt;br /&gt;
4.	(optional) Get Firefox: Start Internet Explorer from the Start Menu. Navigate to "http://www.mozilla.org/en-US/" and download Firefox. If IE refuses, try adding www.mozilla.org to the trusted sites. &lt;br /&gt;
&lt;br /&gt;
Now if you want to transfer a few files from your computer to your instance, the easiest way is by copy/paste. Select a file (or folder) in your computer desktop and right-click "Copy". Now go to the instance desktop, right-click "Paste". That simple.&lt;br /&gt;
&lt;br /&gt;
If you have large files/folders to transfer, copy /paste takes forever. A better way is to set up&lt;br /&gt;
a &lt;a href="http://db.tt/7Vgs8kOi" target="_blank"&gt;Dropbox&lt;/a&gt; or &lt;a href="https://www.sugarsync.com/referral?rf=bcxre3tw72xx2&amp;utm_source=website&amp;utm_medium=web&amp;utm_campaign=referral&amp;shareEvent=15629" target="_blank"&gt;SugarSync&lt;/a&gt; account and upload files there. Then from the Instance, we turn our browser to the SugarSync (or Dropbox) site, log in and download the larger files into the instance (at a faster speed since you are using Amazon's 100MB bandwidth ). Keep in mind that incoming traffic seems to be free, but you do get charged for outward traffic, after a certain quota is reached.&lt;br /&gt;
&lt;br /&gt;
You can set up QuantShare with Dropbox or SugarSync so that your home computer QS and the EC2 cloud QS are in sync. I will not go into that here. You are welcome to try.&lt;br /&gt;
&lt;br /&gt;
Either way, open QuantShare folder, find QuantShare.exe, make an alias and place it on the Desktop for easy access. Launch QuantShare. Type in your user name and password, choose auto log in and hit ok.&lt;br /&gt;
&lt;br /&gt;
If everything went well, Quantshare is running.&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_4.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We can reach our virtual PC from our IPad, too. There are many Remote Clients for the IPad. I use &lt;a href="http://www.irdesktop.com/" target="_blank"&gt;Irdesktop&lt;/a&gt;.&lt;br /&gt;
 &lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_5.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Part2: Automate Trading Signals from Portfolio Strategies&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will create 4 scripts:&lt;br /&gt;
&lt;br /&gt;
Go to Tools--&gt;Scripts Editor and write a script that calls a downloader to update today's quotes. I use the Daily Stock Quotes downloader.You should edit the script according to your needs. The script has only one line.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Downloader.StartDownloader("Daily  Stock  Quotes");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Save the script. Let's call it "UpdateQuotes".&lt;br /&gt;
We then create a new script. Also has   one line:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;App.Main.Quit();&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Keep in mind that when we create a task from this script, we do NOT tick the "Run even if app is not&lt;br /&gt;
Loaded" box. We want to Quit QS only if it is running...&lt;br /&gt;
&lt;br /&gt;
The next step is to setup retrieving and emailing of trading signals.&lt;br /&gt;
&lt;br /&gt;
Let's assume you have a portfolio based on a strategy. We will call it "MySystem". We will make a new Script (Tools--&gt;Script Editor)&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;PortfolioTask task1 = Portfolio.Run("", "MySystem"); &lt;br /&gt;
while(!task1.IsCompleted) // Wait/Sleep until task is completed&lt;br /&gt;
{&lt;br /&gt;
	App.Main.Sleep(1000);&lt;br /&gt;
}&lt;br /&gt;
string  txt1="";&lt;br /&gt;
for  (int  i=0;  i&lt;  task1.Orders.Length;i++)&lt;br /&gt;
{&lt;br /&gt;
	txt1=txt1+task1.Orders[i].Symbol+","+task1.Orders[i].OrderOrigin+","+task1.Orders[i].Share s+","+task1.Orders[i].OrderType+"\n";&lt;br /&gt;
}&lt;br /&gt;
App.Net.SendEmail("QS  Cloud  Service",txt1) ;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Save this script as &#xfffd;RetrieveSignals&#xfffd;.&lt;br /&gt;
&lt;br /&gt;
One more script:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Order[] orders1=Portfolio.GetOrders("MySystem"); &lt;br /&gt;
for (int i=0; i&lt; orders1.Length;i++)&lt;br /&gt;
{&lt;br /&gt;
	orders1[i].SubmitOrder();&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Call this "SubmitOrders".&lt;br /&gt;
&lt;br /&gt;
Note: For email to be send, you will have to go to Quantshare's settings menu and add your e-mail account details. If you are using Gmail set port to 25 (or try 587) and Authentication to SSL.&lt;br /&gt;
&lt;br /&gt;
So now we should have 4 scripts. We should schedule them in this order: &lt;br /&gt;
1.	Run RetrieveSignals.&lt;br /&gt;
2.	Run UpdateQuotes. &lt;br /&gt;
3.	Run SubmitSignals &lt;br /&gt;
4.	Run Quit_QS&lt;br /&gt;
 &lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_6.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Go "Tools"--&gt;Task Manager to add a Task. We create a task for each Script and schedule it according to the previous logic. Remember to tick the "Run even if app is not Loaded" box in all tasks except the &#xfffd;Quit_QS&#xfffd; task.&lt;br /&gt;
 &lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_7.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/casestudy_touini_8.gif" title="Running QuantShare on Amazon's EC2 Cloud &amp; Automate Strategies Signals" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
So now, you have QS updating quotes, keeping track of portfolios and emailing signals, all by itself.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/hkGd07WV4g0" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/hkGd07WV4g0/sa-492-running-quantshare-on-amazon-s-ec2-cloud-automate-strategies-signals</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-492-running-quantshare-on-amazon-s-ec2-cloud-automate-strategies-signals</guid>
        <pubDate> Fri, 26 Oct 2012 21:51:38 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-492-running-quantshare-on-amazon-s-ec2-cloud-automate-strategies-signals</feedburner:origLink></item>  
     <item>
        <title> Money Management: Optimize the scale-in strategy</title>
        <description>If you have read my previous blog post then you certainly know how to create a basic money management script. If this is not the case then you must first read that post, because this is the second part. Here is the link of the first post: &lt;a href="http://www.quantshare.com/sa-484-money-management-scale-in-trading-strategy"&gt;Money Management: Scale-in Trading Strategy&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
In this second part, I will show you how to:&lt;br /&gt;
&lt;br /&gt;
- Define an optimizable variable&lt;br /&gt;
- Optimize a money management variable&lt;br /&gt;
- Backtest several variations of a money management strategy&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Different Types of Variables&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In the money management tool of QuantShare, you can define two types of optimizable variables: &lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Numeric&lt;/u&gt;: This allows you to optimize a numeric value by specifying a start, end and step values. The variations begin at "Start" and then move to the next value by adding "Step" value until the "End" limit is reached.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example&lt;/u&gt;:&lt;br /&gt;
Start: 10&lt;br /&gt;
End: 20&lt;br /&gt;
Step:5&lt;br /&gt;
&lt;br /&gt;
This will generate 3 variations: 10, 15 and 20.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Text&lt;/u&gt;: This defines a list of variations in text format.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example&lt;/u&gt;:&lt;br /&gt;
Yes&lt;br /&gt;
No&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Define an Optimizable Variable&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In a money management script, optimizable variables are defined in the "OnStartSimulation" event using either the "Optimize.OptimizeDouble" function or the "Optimize.OptimizeText" function.&lt;br /&gt;
&lt;br /&gt;
To optimize a numeric variable:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Optimize.OptimizeDouble("Name1", 10, 20, 5); // Vary variable "Name1" from 10 to 20 with a 5 increment&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
To optimize a text variable:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;string[] values = new string[2]; // Create an array&lt;br /&gt;
values[0] = "Yes"; // Set the first element of the array&lt;br /&gt;
values[1] = "No"; // Set the second element&lt;br /&gt;
Optimize.OptimizeText("Name2", values);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
There is another way to optimize variables. It consists of creating an input variable (A variable that can be dynamically updated from the simulation control) then specifying optimization settings for this variable from the simulator control.&lt;br /&gt;
&lt;br /&gt;
Example with a numeric variable; Add the following line in the "OnStartSimulation" event:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Functions.SetNumericInput("Name1", 10, "Description");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Save your trading system then select it the simulator manager.&lt;br /&gt;
Here is what you get:&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/scalein_ts_1.gif" title="Money Management: Optimize the scale-in strategy" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To update a variable value, simply change it with its value in the editor then click on "Save Money Management Inputs".&lt;br /&gt;
To optimize a variable, click on the "+" icon then set the optimization parameters.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Optimize the Scale-in Strategy&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Back to the scale-in trading system we have created in the previous post. Update it from the simulator manager then select "Money Management" tab. Click on "Update Script".&lt;br /&gt;
&lt;br /&gt;
Even if the script code is small, we can optimize many variables here. Let me show you how to perform a basic optimization of the "Scale-In Bars" variable. This variable defines the number of bars to wait before checking the position return and performing the scale-in operation.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
- Open your trading system then go to the money management tab&lt;br /&gt;
- Update the script then go to the "OnStartSimulation" event&lt;br /&gt;
- Add the "Functions.SetNumericInput" line to create an input variable&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;Functions.SetNumericInput("Scale-in Bars", 2, "Scale-in position after the number of bars specified here");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Go to the "OnEndPeriod" event then type the following line at the beginning:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;double sbars = (double)Variables.GetVariable("Scale-in Bars");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
// This instruction allows us to get the "Scale-in Bars" value that the user (or the optimizer) has defined.&lt;br /&gt;
&lt;br /&gt;
- Now, instead of comparing the variable "pos.BarsSinceEntry" to "2", we simply replace the value "2" by "sbars":&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;if(pos.BarsSinceEntry == sbars)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Done. You have just created a user-defined variable (that you can optimize later).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let us practice again by creating the second user-defined variable. This time, we will create the "Entry %" variable, which defines the percentage of shares to enter with the first buy order. This example is a little bit more complicated because it consists of changing the formula of two events: "OnNewPosition" and "OnEndPeriod".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;OnNewPosition&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
- As we did with the previous variable (Scale-In Bars), we must first get the value of "Entry %" by calling the "Variables.GetVariable" function.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;double perc = (double)Variables.GetVariable("Entry %");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Now, let us calculate the number of shares to buy based on the percentage of shares specified in the above line.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;int halfShares = (int)(NewPosition.NbShares * (perc / 100));&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
// The "(int)" cast is used to change the type of the value returned by the above mathematical operation, from "double" to "int".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;OnEndPeriod&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
- By now, you already know that the first thing we must do is to retrieve the value of the "Entry %" variable:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;double perc = (double)Variables.GetVariable("Entry %");&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
- Just before the "Orders.AddLongPosition" instruction, calculate the number of shares to enter by adding these lines:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;double totalShares = (pos.NbShares / perc) * 100; // First, we calculate the total number of shares based on the current position size and the "Entry %" variable&lt;br /&gt;
double sharesScale = ((100 - perc) / 100) * totalShares; // Here we calculate the number of shares to scale-in the position&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This money management script is already available in the sharing server. You can download it here:&lt;br /&gt;
&lt;ref&gt;1196&lt;/ref&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/lYNdbhM5V40" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/lYNdbhM5V40/sa-491-money-management-optimize-the-scale-in-strategy</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-491-money-management-optimize-the-scale-in-strategy</guid>
        <pubDate> Tue, 23 Oct 2012 13:06:49 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-491-money-management-optimize-the-scale-in-strategy</feedburner:origLink></item>  
     <item>
        <title> Money Management: Scale-in Trading Strategy</title>
        <description>To get full control of the backtester or simulator tool, you must implement your own the money management script in C#. This post aims to help you create your own money management script in QuantShare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Introduction to Money Management Scripts&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The goal of the money management tool is to allow you to create any kind of trading strategy, whether it is a simple or an advanced one. &lt;br /&gt;
A trading system can be implemented using the QS language or the wizard.&lt;br /&gt;
&lt;br /&gt;
For example, a simple RSI-based trading system may consist of two trading rules:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;buy = rsi(14) &gt; 70; // Buy when RSI is higher than 70&lt;br /&gt;
sell = rsi(14) &lt; 30; // Exit when RSI is lower than 30&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Now, image you want to create the same strategy but with an additional rule, which is buy 50% when RSI is higher than 70 and the other half if the position is profitable after 2 trading days.&lt;br /&gt;
&lt;br /&gt;
We cannot create this kind of rule with the QS language and this for one simple reason:&lt;br /&gt;
&lt;br /&gt;
The "buy" and "sell" signals of a QS formula are calculated before the backtesting process starts and thus at that time, we do not have any information about the performance of our positions.&lt;br /&gt;
&lt;br /&gt;
The backtester tool generates buy and sell signals for each trading day and for each security from the QS formula before even starting the true portfolio backtesting process.&lt;br /&gt;
&lt;br /&gt;
When the backtest starts, these signals are used to generate orders. Depending on orders execution, cash available, maximum number of positions..., some signals will be used and other not.&lt;br /&gt;
&lt;br /&gt;
A money management script allows you to interact with the backtester by sending instructions dynamically during the simulation process.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Examples&lt;/u&gt;:&lt;br /&gt;
- Short a position if a buy order is initiated by the backtester&lt;br /&gt;
- Scale-in a trade if a condition is met&lt;br /&gt;
- Pause trading for few days if the portfolio's return decreases by 10%&lt;br /&gt;
- Set the maximum number of positions to 10&lt;br /&gt;
- Update the number of shares to buy depending on some rules&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Money Management Events&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Money management events are scripts called by the backtester on specific situations. You can send instructions or control backtester behavior within these events.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example&lt;/u&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;OnNewPosition&lt;/u&gt;: This event is called (which means its corresponding script is executed) each time a new order is created (just before the order is sent/executed).&lt;br /&gt;
&lt;u&gt;OnEndPeriod&lt;/u&gt;: This event is called on each new bar (Each day when simulating a daily trading system).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Money Management: Scale-in Trading Strategy&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The strategy we are going to implement with the money management script is the one described above.&lt;br /&gt;
It consists of entering 50% of any position if RSI is higher than 70 and the remaining 50% after 2 days if the trade is profitable (2-day return positive).&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Create a trading system&lt;/u&gt;:&lt;br /&gt;
- Select "Analysis -&gt; Simulator"&lt;br /&gt;
- Click on "New" to create a new trading system&lt;br /&gt;
- Select the "... formula editor" tab&lt;br /&gt;
- Let us now define the buy and sell rules&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;buy = rsi(14) &gt; 70;&lt;br /&gt;
sell = rsi(14) &lt; 30;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Easy. Buy when RSI is higher than 70 and sell when it is lower than 30.&lt;br /&gt;
&lt;br /&gt;
The default position sizing method of QuantShare is "Percent of current equity". In the case, we have 5 maximum allowed positions in our portfolio and if a buy order is initiated and at the same time we have a $100,000 equity then the order size will be $20,000. Of course, this amount may vary depending on the available cash.&lt;br /&gt;
&lt;br /&gt;
Our money management script will catch every new order (OnNewPosition) and cut its size by 2, so that only 50% of the expected size is initiated.&lt;br /&gt;
Next, we will track the "OnEndPeriod" event and calculates the return of each position on its second day.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Back to the trading system we have just created&lt;/u&gt;:&lt;br /&gt;
- Select "Symbols &amp; Dates" tab&lt;br /&gt;
- Select the stocks or securities you want to backtest by defining one or several symbol's conditions&lt;br /&gt;
- Select "Money Management" tab&lt;br /&gt;
- Click on "Add a new money management script"&lt;br /&gt;
- Update the "OnNewPosition" and "OnEndPeriod" events. Don't know how? Please read the next lines.&lt;br /&gt;
&lt;br /&gt;
Click on the "OnNewPosition" event then type the following lines:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;int halfShares = NewPosition.NbShares / 2;&lt;br /&gt;
Functions.UpdateNumberOfShares(halfShares);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The first line creates a new variable (halfShares) that contains half the number of shares of the original order size.&lt;br /&gt;
The second line instructs QuantShare trading software to update the number of shares of the active order.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, select the "OnEndPeriod" event then type:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;MMPosition[] positions = Portfolio.GetOpenPositions(); // Get open positions&lt;br /&gt;
for(int i=0;i &lt; positions.Length;i++) // Loop through open positions&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;MMPosition pos = positions[i]; // Get position at index (i)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;if(pos.BarsSinceEntry == 2) // Verify that position was created two bars ago&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;double perf = pos.Performance; // Get the position return&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if(perf &gt; 0) // Verify that the return is positive&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Orders.AddLongPosition(pos.Symbol, pos.NbShares, null); // Scale-in (Add buy order with the same size as the previous order)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;
}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The description of each line is added after the instructions (&lt;span style="color:#1C74A8"&gt;//&lt;/span&gt;).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, we must update a setting in our MM script to ensure that no new position gets more than the average expected position size.&lt;br /&gt;
This is because when we reduce the size of an order, the next order tends to have a bigger size (there is more cash available) and thus we must ensure that this next order doesn't get the cash left by the first order. This cash may be used later by the first order when performing a scale-in.&lt;br /&gt;
&lt;br /&gt;
Select "OnStartSimulation" event then type:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;TradingSystemSettings.MaxWeight = 1;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;img src="http://www.quantshare.com/Images/blog/mm_scalein_1.gif" title="Money Management: Scale-in Trading Strategy" /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Optimize a Money Management Script&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In the next post, we will show you how to create optimizable variables in a money management script and how to create and backtest several trading systems based on these variables. For example, in the script you have implemented today, you can optimize:&lt;br /&gt;
- The number of bars since an order was filled&lt;br /&gt;
- The position return threshold&lt;br /&gt;
- The number of shares to scale-in&lt;br /&gt;
&lt;br /&gt;
To be continued.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Update&lt;/strong&gt;:&lt;br /&gt;
Here is the link of the next post: &lt;a href="http://www.quantshare.com/sa-491-money-management-optimize-the-scale-in-strategy"&gt;Money Management: Optimize the scale-in strategy&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/ZBEucjfT3Kc" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/ZBEucjfT3Kc/sa-484-money-management-scale-in-trading-strategy</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-484-money-management-scale-in-trading-strategy</guid>
        <pubDate> Wed, 10 Oct 2012 11:59:38 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-484-money-management-scale-in-trading-strategy</feedburner:origLink></item>  
     <item>
        <title> How to measure market strength with the composite tool</title>
        <description>&lt;div align="center"&gt;&lt;img src="http://www.quantshare.com/Images/blog/market_strenght_comp_1.gif" title="How to build and backtest a robust stock trading system" /&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt;A big part of stock movements could be explained by the movement of the entire stock market. If the Dow Jones declines by 1%, it is likely that your medium or small cap stock will decline too simply because the movement of the majority of stocks are highly correlated with one another and with the market as a whole. It is important that you do not underplay the importance and the impact of the whole market on individual stocks. &lt;br /&gt;
&lt;br /&gt;
This is a reason to include and use measures of the market strength as part of your investment strategy. Before investing in stocks, it is often advised to measure and estimate the whole market strength. This could be done by analyzing broader indices such as the S&amp;P 500, Russell 2000 or it could be done using market breadth indicators or better your own composites.&lt;br /&gt;
&lt;br /&gt;
Creating your own composites seems like a very hard task but thanks to QuantShare, you can now create simple and advanced composites very easily. Here are some examples of market indicators you can create to measure market strength:&lt;br /&gt;
&lt;br /&gt;
- Number of stocks trading above their 100-day moving average&lt;br /&gt;
- Ratio of stocks trading in overbought area compared to those trading in an oversold area&lt;br /&gt;
- Number of stocks whose RSI(2) value is above 70&lt;br /&gt;
- Average return of up trending stocks minus return of down trending stocks&lt;br /&gt;
- Number of stocks with positive analysts recommendations&lt;br /&gt;
- Average PEG ratio of all stocks that compose the S&amp;P 500&lt;br /&gt;
- Percentage of stocks trading above their resistance line&lt;br /&gt;
&lt;br /&gt;
The number of composites you can create is infinite. Now, let me show you how to create your first market composite with QuantShare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Number of stocks trading above their 100-day moving average&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
First, let us open the composite control. To do this, select "Tools" then "Composites" from QS trading software menu.&lt;br /&gt;
&lt;br /&gt;
In the composites control, click on "Add" to create a new market composite.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Step 1&lt;/u&gt;: Define symbols&lt;br /&gt;
&lt;br /&gt;
We have to specify the stocks that will included in the composite calculation.&lt;br /&gt;
If you want to create a composite based on all stocks then keep the symbols selection control empty and click on "Next". Otherwise, click on "Add Condition", and specify one or several conditions to select your symbols.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Step 2&lt;/u&gt;: Specify the composite formula and calculation method&lt;br /&gt;
&lt;br /&gt;
The formula is the most important part of a composite and it tells QuantShare how the composite is calculated.&lt;br /&gt;
&lt;br /&gt;
To count the number of stocks trading above their 100-day moving average, type this:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;composite = close &gt; sma(100);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
And use the following calculation method: "Calculate the sum of the values added to the composite".&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;How it works?&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
- QuantShare calculates the composite variable for each stock included in the composite (for each trading bar)&lt;br /&gt;
- For each date, it calculates the sum (specified in the calculation method) of the composite values (for all stocks)&lt;br /&gt;
- It creates a new ticker symbol for that composite and associates it with the new data.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Step 3&lt;/u&gt;: Finish&lt;br /&gt;
&lt;br /&gt;
Click on "Next", specify start &amp; end dates and period, click on "Next" again, type the composite name then click on "Next" one more time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to add a market indicator in your trading system&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let us say we have a trading system that enters a long position when a stock decreases by 10% and exits that position after 10 bars.&lt;br /&gt;
&lt;br /&gt;
Follow the next steps to create this strategy:&lt;br /&gt;
- Select "Analysis -&gt; Simulator"&lt;br /&gt;
- Create on "New" to create a new trading system&lt;br /&gt;
- Select the formula editor&lt;br /&gt;
- Set a "10 bars" N-Bar stop&lt;br /&gt;
- Type the next formula:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;buy = perf(close, 30) &lt; -10;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, let us add our previously created market indicator. The idea is to constantly measure market strength using the moving average composite and prevent our trading system from entering any new positions if the number of stocks trading above their moving average is decreasing.&lt;br /&gt;
&lt;br /&gt;
Let us say that the name of the previously created composite is "^Stocks_Above_M100" (All composite symbols start with "^" character).&lt;br /&gt;
&lt;br /&gt;
You can reference this symbol by calling the "GetSeries" function.&lt;br /&gt;
&lt;br /&gt;
Just add the following line to the strategy formula:&lt;br /&gt;
&lt;span style="color:#1C74A8"&gt;a = GetSeries("^Stocks_Above_M100", close, LastData);&lt;br /&gt;
buy = buy and perf(a, 10) &gt; 0;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Explanation: Buy only if the 10-bar return of the market indicator is positive&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Main advantages of creating market composites with QuantShare&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
- Composites are automatically updated when you download new data. You can enabled/disable this option by selecting "Tools -&gt; Composites", selecting "Settings" tab then checking or un-checking the "Automatically update composites..." option.&lt;br /&gt;
&lt;br /&gt;
- Ability to use C# programming language to create advanced composites&lt;br /&gt;
&lt;br /&gt;
- Ability to create end-of-day and intraday (any time frame) composites&lt;br /&gt;
&lt;br /&gt;
- Ability to create composites based on other composites&lt;br /&gt;
&lt;br /&gt;
Finally yet importantly, you can use your custom composites with any other QuantShare tools, this includes: charting, trading system, trading rules, neural network, genetic algorithms, portfolio&#xfffd;&lt;br /&gt;
&lt;br /&gt;&lt;img src="http://feeds.feedburner.com/~r/QuantShare/~4/DleKrIk8Hls" height="1" width="1"/&gt;</description>
        <link>http://feedproxy.google.com/~r/QuantShare/~3/DleKrIk8Hls/sa-479-how-to-measure-market-strength-with-the-composite-tool</link>
		<guid isPermaLink="false">http://www.quantshare.com/sa-479-how-to-measure-market-strength-with-the-composite-tool</guid>
        <pubDate> Wed, 03 Oct 2012 11:33:51 +0400 </pubDate>
     <feedburner:origLink>http://www.quantshare.com/sa-479-how-to-measure-market-strength-with-the-composite-tool</feedburner:origLink></item>  
  

</channel>
</rss>
