Technical Analysis Scanner TAS FlexSoft 7172 Regional Street, #276 Dublin, CA 94568 U.S.A. Voice 510-829-9733 FAX 510-829-9733 BBS 510-829-2293 This document and all accompanying written and disk based notes and specifications are copyrighted by FlexSoft. January 18, 1992 Introduction "Technical Analysis Scanner" (TAS) is a software program that lets you analyze your MetaStock, Computrac, Investograph Plus or ChartPro data base using technical analysis indicators and conditional relationships to "scan" all, or a portion, of your data files. TAS also contains a Profit Testing Facility with which you can "back test" your historical data using nearly any trading strategy to see how profitable it would have been. TAS is a generalized technical analysis "tool box". It is not a "black box" system where you have no knowledge of the rules or control over its decision making process. With TAS, you have complete control over the indicators chosen, their interpretation, and the output formatting of your reports. With TAS, you can combine over 60 built-in technical indicators, compare their values against other indicators or values, make decisions based on the result of those comparisons, and ultimately, create a report which shows you what you want to see. TAS is designed to enable you to go beyond the MetaStock Pro "Custom Formulas" by applying similar analysis to all, or any part of, the data in your Metastock (or ChartPro) Data Base. If you have a trading strategy that relies on technical indicators or price action, but you do not have the time to chart all of your stocks everyday, then TAS is the tool you need. It runs your own customized formula on selected groups of your stocks, and can notify you if your buy or sell condition is reached. TAS can also be used to create custom reports on your stocks. For example, you can use it to notify you when a particular stock has reached a certain price, volume or technical indicator value. And with the Profit Tester feature you can confirm the profitability of your trading system. TAS goes back through your historical data, a day at a time, applying your trading rules to the indicators and conditions you specify. It keeps track of the days you bought, sold or were stopped out of positions, tabulating the results on a daily basis, or in a summary report which tells you how your system performed. Technical Analysis Scanner (TAS) Page 2 System Requirements In order to use TAS, you should have the following software and hardware configuration. Hardware Any IBM PC processor type (8088, 8086, 80x86) A CGA, EGA, or VGA Monitor (EGA or VGA required for Charts) Hard Disk (optional) Microsoft or Logitech Mouse (optional) 512K minimum memory (640K better) Expanded Memory (XMS) will be used on 286/386/486 class machines if there is an Expanded Memory System (EMS) driver or actual LIM 4.0 EMS memory installed. Software DOS 2.1 or later "Computrac" Format historical data files used by Metastock, Investograph Plus, and Computrac, among others or ChartPro or MegaTech data files Technical Analysis Scanner (TAS) Page 3 Support and Upgrades Support You can get support for TAS problems or questions by contacting FlexSoft at its mailing address below: FlexSoft 7172 Regional St, #276 Dublin, CA 94568 or by telephone at 510-829-9733 or by Email on the following services: OnLine Service Userid GEnie M.MOORE41 Prodigy JBMD65A FlexSoft BBS (510-829-2293) SYSOP Compuserve 76447,2367 Updates to TAS (Upgrades) New releases of TAS may be defined as "upgrade releases". An Upgrade Release will require a new Registration Code and an Upgrade Registration Fee. When a major feature is added to TAS, there will be a "Feature Upgrade" cost as well. Update versions of TAS are available , on the FlexSoft BBS at 510-829-2293. The FlexSoft BBS has an online order system which you can use to purchase your new TAS update. You will need a VISA , Mastercard, or American Express credit card number to order your update to TAS when using the online order system. Once your order is confirmed, you will be given access to the "area" of the BBS that contains the TAS update version. You can also obtain updates to TAS by U.S. Mail. If you need an update by U.S. Mail, please send $5 for shipping and handling in addition to the Update and/or Upgrade Registration Fee. Methods of payment are by check, money order, or VISA, Mastercard, or Technical Analysis Scanner (TAS) Page 4 American Express credit card number (include expiration date). Redistribution of TAS You may not re-distribute TAS to BBS systems or other public locations, nor may you copy it for other than your own use. You may not redistribute your registration code , nor may you transfer it or give it away to anyone else. Other FlexSoft Products FlexSoft also has two companion products for users who wish to order them. The first product is called PML and the second is called PDL. With the combination of TAS, PML and PDL, you have "end to end" access to your stock market data. PDL downloads the quotes, PML updates the database, and TAS allows you to search, analyze, report, and chart the data. PML and PDL are described below. Each of these programs can be ordered from FlexSoft or downloaded from GEnie or Compuserve. PDL (Prodigy Down Loader) PDL is a program that downloads, or captures, daily quote data and market indices from the Prodigy Information Service. PDL can download up to 1,000 daily quotes in a single run. If you need to download more quotes, then you can run PDL several times. It uses the Quote Check and Market Close features of Prodigy to obtain the quotes, so there is no need to go into Prodigy and enter the quotes by hand, as some systems require you do. The creation of the ticker list of quotes to download can be done with a simple TAS script. PDL also has a "vacation mode" that will enable you to go on vacation or leave town for extended periods and still gather daily quote data. PML (Prodigy Metastock Loader) PML converts quotes from GEnie, DowJones, Prodigy and Compuserve into MetaStock data files and an ASCII format for input to spreadsheets. PML produces summary reports on all your Metastock Technical Analysis Scanner (TAS) Page 5 files whether you update the files with PML or not. Colors are used to highlight those stocks which exceed either PRICE or VOLUME limits you set in the installation procedure. PML also creates a Summary Report file. Credits MetaStock Professional is a stock charting program from Equis Inc. ChartPro is a stock charting program written by David Rettger. GEnie is a trademark of General Electric Co. Prodigy is a trademark of Prodigy Services Co. Disclaimers The author claims no responsibility for any damages caused by the use or misuse of this product. This product is distributed "as is" with no warranty expressed or implied. The author will not be responsible for any losses incurred, either directly or indirectly, by the use of this product. The author reserves the right to make modifications at any time. Prices are subject to change without notice. Technical Analysis References The Encyclopedia of Technical Market Indicators, Colby & Meyers, Dow Jones Irwin Press, 1988, ISBN 1-55623-049-4 New Concepts in Technical Trading Systems, J. Welles Wilder Jr., Trend Research, 1978, ISBN 0-89459-027-8 The New Commodity Trading Systems and Methods, Perry J. Kaufman, John Wiley and Sons 1987, ISBN 0-471-87879-0 Metastock Professional Users Guide, Equis International Technical Analysis Scanner (TAS) Page 6 Installing TAS TAS is distributed as an LHARC compressed collection of files. The name of the .EXE file will be based on the version and release level of TAS. For version 4, release 08, the name will be 'TAS408.EXE', and in general, the name will be 'TASvrr.EXE' where 'v' is the Version and 'r' is the Release. Quick Start Installation The following "quick start" documentation shows how to get TAS up and running on your system initially. The file name for the TAS file is referred to as "TASvrr.EXE". In order to install TAS, you should perform the following steps 1. Create a directory to contain TAS software. It can be any name you choose. The following instructions assume the subdirectory name is "\TAS". To create a directory named \TAS on your C: drive, type "MD C:\TAS" 2. If you received TAS on a floppy disk, copy TASvrr.EXE into directory \TAS by typing COPY A:\TAS\TASvrr.EXE C:\TAS 3. CD \TAS 4. Type TASvrr, e.g, if the file is TAS408.EXE, type 'TAS408' 5. Type TAS and press ENTER. 6. You will be presented with an initial screen which tells you that you have not run TAS before. There are flashing areas at the bottom to remind you that the F1-key is the Help key. Hit the ESC key after reading the message. You will see another message indicating you have a trial version of TAS. Once again, hit the ESC key to move to the next screen. 7. You will now be placed in the "Configure TAS" menu screen. Fill in the MetaStock or Chartpro directory names you want to scan. You can enter up to 10 subdirectories and then hit F3 to save the directories you named. TAS is now installed . The following section shows how to do a build and run a simple selection that will perform the same function as the Metastock Utility Rank feature. Technical Analysis Scanner (TAS) Page 7 Creating and Running a Sample Selection 1. Go to the Define Ticker List Menu by either typing "T" or moving the cursor bar down to that selection and pressing ENTER. If you have a mouse, you can click on the menu item. 2. Select New Ticker List from the next prompt. 3. Give the name "MYTICKS" . This will be the name of a ticker list for testing. 4. After a moment, TAS will present you with a list of all the tickers it found in the Data Directories you defined in the Configure TAS screen. Move the cursor to each ticker symbol you want to run a script against. Hit the SPACE bar on the symbol. It should highlight (indicating it is selected). Hit F3 when all desired symbols are selected. This will save the ticker list you just created. 5. At the Main Menu, select Build or Run Selection by typing "B" 6. Select Use Old from the Build or Run Selection Menu 7. Pick the selection MSURANK.SEL (by typing "M" or moving the cursor to it) and hitting ENTER. 8. Hit the F4 function key to "RUN" the MSURANK selection script. TAS will now display a screen containing all the ticker lists available to use. You will be asked which ticker list you wish to use when you run this script. 9. Pick the ticker list you just created "MYTICKS.TCK" by moving the cursor or mouse to the file name and pressing ENTER or clicking on the filename. This particular selection will create a report like the one Metastock Utility (MSU) creates when you select "Rank" using a 26 day Rate of Change and a 10 day Moving Average. 10. Now TAS runs the script with the ticker symbols you put in the ticker list. As each ticker is processed, you will see a line in the "run" window. Once all tickers are processed, the report will be presented on the screen, sorted by ticker. 11. Hit F1 now to see the choices you have. By hitting F1, you can read the help and see what you can do from here. You can sort your tickers on the value of any column shown, either ascending or descending order. To sort on the values in the second column, press the key sequence Alt-2 (hold the ALT key and hit the number 2). 12. To exit from the report screen, hit the ESC key. The documentation for the system is in the online help file available by hitting the F1 key at any time. Technical Analysis Scanner (TAS) Page 8 Running TAS In general, you can start TAS with the following format command: TAS [switches] [scriptName] [tickerListName] [@parameters] The options in brackets are optional and need not be specified. You can start TAS in "MENU MODE" by simply typing "TAS" by itself. TAS has switches available which you can specify on the command line. They are: -c Eliminate CGA "snow" -b Use BIOS to write to video screen. This may be necessary on some systems which are not 100% compatible. -m Use Monochrome color scheme If you are a registered user of TAS, you can also start TAS in "batch mode" by specifying the name of a SCRIPT, the scriptName, and the Ticker List, the tickerName, on the command line. So, if you had a TAS script named "SELECT.TAS" and a Ticker List named "MYSTOCK.TCK", you could run the SELECT script against the stocks in the list MYSTOCK by typing: TAS SELECT MYSTOCK If you wanted TAS to process all of the stock symbols (Tickers) in your data base, you can omit the Ticker List name. You can also specify initial script statements to be executed at the beginning of the script by specifying parameters on the command line, preceded by the "@" sign. Each statement should be terminated by a semi-colon, just as it would be if it were inserted at the beginning of the script. See the section titled "Syntax" beginning on page for a description of script statements. TAS Menus The TAS Main Menu contains a screen which has all the options you can choose when you work with TAS. The Main Menu looks like the figure below. Technical Analysis Scanner (TAS) Page 9 The following sections will describe each of the options accessible from the Main Menu. Technical Analysis Scanner (TAS) Page 10 Technical Analysis Scanner (TAS v.rr) Copyright 1991, Main Menu Configure TAS Define Ticker List Build or Run Selection Build or Run Profit Test Edit A TAS Script Run TAS Script Quit [F1]=Help Select Choice [ESC]=Quit Special Keys within TAS F1 The F1 key is the HELP Key. This key will cause a help screen to be display when you press it. The help topic will be for the current cursor location (i.e., "context sensitive help"). ALT-X The ALT-X key will exit from TAS to DOS. This will allow you to do a few things outside of TAS. Because TAS is a large program, you won't have a a great deal of storage left when you exit to DOS. To return to TAS from DOS, type "EXIT". ALT-M The ALT-M key will tell you how much memory is available to TAS and the maximum size used of the SYMBOL TABLE. This key will also display the amount of EMS memory used by the program as well as the video display parameters detected by the program. ESC The ESC key will always leave the screen or prompt you are in and immediately "pop" you back to the previous menu. Technical Analysis Scanner (TAS) Page 11 CTRL-BRK The CTRL-BRK key can be used to stop a TAS when it is running. Any other key pressed during the execution of a TAS script will cause the display to pause, awaiting another key press. Error Processing When an error is detected in a TAS script, selection, or profit test, TAS will attempt to isolate the cause of the error and display an error message as well as an information screen that describes the cause of the error and a recommendation for fixing the error. The script line number and column where the error was detected is also given to you to further isolate the problem. Below is an example of an error detected in a Selection Script. Note the error message next to the line in error and the explanation at the bottom of the page. Technical Analysis Scanner (TAS) Page 12 #MAX_QUOTES 31 F1 : ARRAY; F1 = MOV(c,10,'S')x; { <----- ERROR#60:Don't know what to do with "X" } F2 : ARRAY; F2 = MOV(c,30,'S'); F3 : ARRAY; F3 = f2-f1; C1 = ISECT(f1,f2)=0; +--------------------------TAS ERROR 60 Has Occurred---------- --------------------+ The following error has been detected around Line 3, Column 20 ERROR#60:Don't know what to do with "X" Press ESC to continue -----------------------Explanation for Error Number 60-------- ------------------------+ Cause: TAS syntax check has encountered a symbol or word that is either misplaced, mis-spelled, or preceded by a word that might be mis-spelled. Recommendation: Check the spelling of the word pointed out and the previous word. Also, check that you are using it in accordance with the description given in the User's Guide. CONFIGURE TAS - Configuration and Setup The Configuration Menu is used to tell TAS the location of your Metastock or ChartPro Data Directory(ies). Up to ten directories can be defined on the Configuration Menu, and up to twenty directories can be processed at one time. Technical Analysis Scanner (TAS) Page 13 The configuration menu looks like this: TAS Configuration and Setup 1st Data DIRECTORY \MSPTEST\DATA_A_E 2nd Data DIRECTORY \MSPTEST\DATA_F_P 3rd Data DIRECTORY \MSPTEST\DATA_Q_Z 4th Data DIRECTORY 5th Data DIRECTORY . 10th Data DIRECTORY Include Ticker Period Symbol Table Size 9000 Quotes per Symbol 50 Use EMS Arrays Y Your Name John Doe Registration Code 02125F3012 DATA DIRECTORY(S) You should fill in the names of your Metastock or ChartPro Directories, one per line above. Be sure to include the full path Technical Analysis Scanner (TAS) Page 14 name, including the first backslash character. If you have more than one directory of data files, you can enter the other directory names on the second thru tenth lines. You cannot intermix directories across products. In other words, all 10 of your directories must be either Metastock format or ChartPro format. TAS determines the type of directory by first looking for a file named "MASTER" in the first directory. If found, it assumes all directories are Metastock format. If not found, it looks for files ending with ".PRO". If these are found, it assumes that all directories are ChartPro data. If neither search is satisfied, TAS issues an error message and requests that you change the directory name. If you have more than 10 Metastock format directories, you can add the 11th through the 20th directory names in the file TAS.CNF manually with an editor by adding lines like the one below:. MSP_DATA_DIRxx = \MSPTEST\DATA_A_E where xx is 10 to 19 for the eleventh through the twentieth directory. INCLUDE TICKER PERIOD This parameter should be set to "Y" if you have multiple tickers with the same ticker symbol but different "periods". For example, if you have a DAILY and a WEEKLY file for the symbol AAPL, you will need to set this value to "Y" in order to distinguish between the daily and weekly ticker files. If you have TICKER LISTS created with this value set to "Y", they will not work if you change this value to "N" (and vice versa). You will have to re-select the tickers again. TAS is distributed with this value unset (which means "No"). Note also, that if you have this value set to "Y", you must include the ticker file period in every reference to a ticker name, including references on the #INDEX command. Technical Analysis Scanner (TAS) Page 15 SYMBOL TABLE SIZE The SYMBOL TABLE SIZE parameter is a "tuning" value which determines the size of the internal tables for TAS. You may need to increase the value if you write a particularly long or complex selection script. If you specify any value less than 9000, TAS will use 9000 as the value. From time to time, as more functions are added to TAS, there is a natural increase in the SYMBOL TABLE SIZE needed for TAS functions. So, it may be the case that your symbol table is adequate for an earlier release of TAS, but needs to be increased for a new release. Try adding a couple of thousand to whatever value you currently have until your script works. If you want to see the amount of SYMBOL TABLE your TAS scripts are using, you can type the ALT-M key to display the memory usage of TAS. One of the values shown is the maximum SYMBOL TABLE SIZE used so far. QUOTES PER SYMBOL The QUOTES PER SYMBOL parameter specifies how many quotes you want TAS to read into memory when performing the selection. The higher this number, the longer the selection will take. See the section below under Use EMS Arrays for the effect of this setting on the usage of EMS memory and processing time. This parameter has a very significant impact on the processing time that TAS uses for each symbol. It should be set to as low a value as possible (based on the time periods you use in your indicators) so that the TAS processing is minimized. Use EMS Arrays If you have EMS (Expanded Memory) or XMS (eXtended Memory) installed with suitable driver software1, you can set this value ____________________ 1 Most systems today do not actually have EMS memory., but instead have Extended Memory (XMS), the kind that is built-in to new 386 and 486 systems. The term EMS actually refers to a software/hardware standard that is emulated by driver programs from various vendors, such as QuarterDeck Office Systems (QEMM and DesqView/386) as well as Microsoft's EMM386 program. Technical Analysis Scanner (TAS) Page 16 to Y to take advantage of the extra memory you have above the 640K DOS limit. TAS will automatically determine if you have EMS memory installed, and if so, it will always use that memory for a "swapping area", reducing the amount of disk reads required to run the program. In addition, if you set this parameter to Y, and you have requested more arrays or set Quotes per Symbol high enough so that product of all the array sizes times the number of arrays needed is greater than the amount of memory available in the DOS 640K region, TAS will swap arrays into and out of EMS memory. This swapping of arrays can slow TAS processing somewhat, but it allows you to set Quotes per Symbol to a maximum value. REGISTRATION CODE When you register TAS , you will receive a REGISTRATION CODE based on your Name. Whatever name you include in the file REGISTER.DOC will be used to form an encrypted code. Use the same name as sent in the REGISTER.DOC file. Place the REGISTRATION CODE sent to you in the appropriate field. DEFINE TICKER LIST You can create "ticker lists" with TAS. A "ticker list" is a list of stock or ticker symbols which you can name as a group. This allows you to create individualized lists of symbols against which you can run your TAS scripts. As an example, you could create a ticker list containing the Dow Jones 30 Industrials, or a list containing only stocks you hold. When you choose the TICKER LIST menu, you are asked if you want to create a New Ticker List or Modify an Old Ticker List. If you request a new Ticker List, you will be prompted for the Ticker List name. Enter only the filename portion, not the .TCK extension. The file will be created in the \TAS directory. If you want to Modify an Old Ticker List, a File Name Selection Screen will appear which contains the names of all the files in the current directory ending with ".TCK". Move the cursor or mouse over to the correct file name and press Enter (or double-click). Directories will also be displayed in this screen, so if your ticker list is in another directory, you can Technical Analysis Scanner (TAS) Page 17 change to that directory by moving the cursor to the directory name and pressing ENTER. The Ticker List screen will then appear with all the ticker symbols contained in the MetaStock directories you have configured. Each symbol that is highlighted in YELLOW has been "selected" for inclusion in the ticker list. To select or unselect a symbol, move the cursor to the symbol and hit the SPACE Bar. If the symbol is selected, it becomes unselected or vice versa. If you want to SELECT ALL TICKERS, hit the F9 (SELECT ALL) Key. To UNSELECT ALL TICKERS, hit the F8 (UnSELECT ALL) Key. Once you have created the ticker list, hit the F3 (Save) Key to save it. If you do not want to save the list, hit the ESC (Abort) Key. If you want to run a TAS script against all of your data, create a new Ticker List called "ALL". Hit the F9 Key to select all symbols. Then hit the F3 Key to save the list. If you have set the CONFIGURATION option INCLUDE TICKER PERIOD to "Y", your ticker names will be followed by a slash and the period of the file, e.g. "AAPL/D" for APPLE COMPUTER Daily data. The period is not available with ChartPro data files. BUILD OR RUN SELECTION Using the BUILD SELECTION screen of TAS, you can create your own report containing up to 7 columns of calculated formulas or data values. In addition, you can use the Condition entry areas (below the Formulas) to specify which conditions must be satisfied for a ticker to be included in the report output. The figure below shows the equivalent of the MetaStock Utility "Rank" option where the first formula is the Current Price ("C" is the Closing Price), the second formula is the 26 day Rate of Change (ROC). The third formula is the 10 day Simple Moving Average of the price. The fourth is the 10 day Simple Moving Average of "F2", where "F2" is the 26 day ROC. Finally, the last Technical Analysis Scanner (TAS) Page 18 formula F5 is the percentage by which the Price is above or below the moving average contained in F3. TAS Selection Creation Enter Formulas Below, e.g. CCI(14) Title Formula F1 C CURR PRC Formula F2 ROC(C,26,'%') %ROC/PRC Formula F3 MOV(C,10,'S') MOV AVG Formula F4 MOV(F2,10,'S') MA %ROC Formula F5 (F1/F3-1)*100 %PRC MA Formula F6 Formula F7 Enter Conditions Below, e.g. F1 > F2 Condition 1 Condition 2 Condition 3 Condition 4 Condition 5 Condition 6 F1]=Help [F3]=Save [F4]=Run [F5]=Options [F7]=Formula Builder ESC]=Quit You can place any formulas or data value in each of the Formula areas. If you hit the F7 key, a list of functions included in TAS will be shown on the screen and you will be prompted for the parameters of the function. The CONDITION entries are used to "select" only those tickers that match all the conditions specified. The conditions are specified in terms of the formulas given above. In the example above, if you only wanted to see tickers whose ROC (Formula 'F2') was greater than 50, then you could set CONDITION 1 F2 > 50 Also, if you had another condition, for example the current price of the ticker is greater than $5, you could place that condition as follows CONDITION 2 C > 5 and that would select only tickers whose ROC is greater than 50 and whose price is greater than 5. Technical Analysis Scanner (TAS) Page 19 Selection Build Options The OPTION Key (F5) allows you to set options for the SELECTION, such as the MAXIMUM QUOTES to read, and any INDEX file you might want to use. Be sure to use the F3 key (SAVE) if you are in the OPTION screen to save your options. Set Selection Options INDEX Ticker SP-500 Maximum Quotes 200 Start Date / / End Date / / Index Ticker If you want to run a profit test that uses some index, such as the SP-500, you can specify the ticker here. Then, in your profit test, you refer to the index ticker's value with the INDEX array name. Maximum Quotes You can specify the maximum number of quotes to load for the profit test. This number should be less than or equal to the Maximum Quotes per Symbol setting in your Configuration Menu. Start Date If you want to start your test on a specific date, specify that date here. Make sure that the date is a date you have in the file. If it is not, the test will begin on the first date prior to that date. End Date If you want to end your test on a specific date, specify that date here. Make sure that the date is one you have in the file. If it is not, the test will end on the first date prior to the end date. Running Your Selection Once your SELECTION is built, you can run it using the F4 Key. You will be asked for a TICKER LIST against which to run the SELECTION. Choose one. Once the SELECTION starts running, there is no output to the main part of the screen until the SELECTION completes. At that point, a "report" will display on your screen with the TICKER in the first column and the formula values you set up for F1 through F7 Technical Analysis Scanner (TAS) Page 20 in each column. Sorting on Selected Columns You can SORT your report by the contents of any column by typing the ALT key at the same time as you hold down the number over the column you want to sort on. For example, to sort on the contents of the column next to TICKER (this would be column numbered "2"), you would type ALT-2 key pair. If you want to change the order of the sorting from ascending order to descending order, type ALT-D (for "Descending"). To go back to ascending order, type ALT-A. Once you have set the sorting direction, you can then resort using a ALT-column_number again. Printing Your Selection Report To PRINT the contents of your report in the current sort order, type ALT-P. If you want to print to a file, enter a file name. To print to your PRINTER, type LPT1 or PRN (or whatever address your printer is hooked up to) in the file name prompt. Errors In Selection Formulas If you have any errors in the SELECTION you have created, you will be told about them when you try to run the SELECTION. An error message will be displayed and then the TAS EDITOR will be run with a dummy file called _RUNSEL.TAS. This file is the file that is created from your SELECTION. It is a special form of a TAS script. You should recognize the formulas though, since they are the ones you entered in your SELECTION. The EDIT screen will redisplay the error message and the explanation of the error at the bottom of the screen. Hit the ESC key and the cursor will be placed near the place where the error was found. In addition, the error message will be placed in the file to the right of the line in error. Look at the formula or condition and try to figure out what the problem is. You are only half done though. Now you have to go back to your BUILD SELECTION screen (by typing ESC) and fix the formula(s) in that screen. Do not try to fix the problem in the TAS Editor screen, since this is just a temporary view of the actual Technical Analysis Scanner (TAS) Page 21 Selection file. Once you have corrected the error in the Selection screen, be sure to save (by hitting F3) your file. Technical Analysis Scanner (TAS) Page 22 BUILD OR RUN PROFIT TEST The BUILD OR RUN PROFIT TEST screen is similar to the BUILD SELECTION screen in appearance. Shown below is a sample of the Build Profit Test screen. TAS Build/Run Profit Test Enter Plot Formulas Below, e.g. CCI(14) Formula F1 RSI(14) Formula F2 Formula F3 Formula F4 Formula F5 Formula F6 Formula F7 Enter Buy/Sell Conditions below e.g. F1 > F2 Cond C1 F1[-1] < 30 AND F1 > 30 Cond C2 F1[-1] > 70 AND F1 < 70 Cond C3 Cond C4 Cond C5 Cond C6 BUY WHEN SELL WHEN LONG STOP SHORT STOP C1 C2 Technical Analysis Scanner (TAS) Page 23 [F1]=Help [F3]=Save [F4]=Run [F5]=Options [F7]=Formula Builder ESC=Quit You can fill in the FORMULAs (F1 to F6) with indicators (or combinations of indicators) you want to 'plot' for the profit test. Then, in the CONDITION entry areas (COND C1 to C6), you fill in conditions you would use in a BUY, SELL or STOP loss signal. Once you have entered your FORMULAS and the CONDitions, you can choose which conditions you want to use for the BUY, SELL and STOP signals. In the example above, only RSI(14) is being plotted. The condition C1 tests to see if the RSI has crossed from below 30 to above 30 (Buy Signal). Condition C2 tests if the RSI has crossed from above 70 to below 70 (Sell Signal). Notice how C1 is entered below BUY WHEN, indicating the Profit Tester should buy if condition C1 is true (and the stock is not already held). And, then C2 is below SELL WHEN, indicating a similar SELL strategy. Special Note for Metastock Users If you are a Metastock user, you are probably used to being able to enter custom formulas like, (H+L)/2 however, with TAS, this calculation would not work. You must reform the equation as follows DIVBY(ADD(H,L),2) which first adds the High and the Low arrays, and then divides the resulting array by 2, thus creating a new array which is the sum of the High and the Low divided by 2. Whenever you want to add two arrays together, use the ADD function, to subtract, use the SUB function, to multiply, use the MUL function, and to divide, use the DIV function. Each of these functions takes two arrays as arguments and returns a new array as the result. To add, subtract, multiply or divide an array by a number, you would use the ADDTO, SUBFROM, MULBY, and DIVBY functions. Profit Test Options Profit Test has a number of options which are set by hitting the F5 Function Key in this screen. You will see the following screen. Each of the items in bold represent one of several choices available for the option. Technical Analysis Scanner (TAS) Page 24 Set TAS Profit Test Options Initial Cash 5000 Test Type LONG Commissions NOCOMM Share Purchases ONESHARE Price Slippage 0 - TODAYS CLOSE Output File Name Report Detail DETAIL Maximum Quotes INDEX Ticker Reinvest Profits N Start Date / / End Date / / When you bring up this screen, you can choose options by using the TAB key to move to each field and selecting the appropriate option. Type the HELP Key (F1) at each field to see the meaning of the choices. When you are done with changes to this screen, hit the F3 key to save the options. If you are in a "pop-up" window, hit ENTER, then hit F3. Profit Test Option Settings Initial Cash This is the amount of "money" the trading should start with. It must be sufficient to buy the amount of shares specified by the Share Purchase option below. For example, if you start with Technical Analysis Scanner (TAS) Page 25 $1,000 and you are buying Round Lots (100 shares), your stock had better not sell for more than $10 per share or you won't have enough money to buy a round lot. Test Type There are 3 choices for this option. You can perform a LONG , SHORT or BOTH test. A LONG test only takes long positions, that is, it only buys to open a position and sells to close it. A SHORT test only takes short positions, selling to open and buying to close ("cover") the position. A BOTH test opens a long or short position and reverses each time a signal is generated to "go the other way". This is essentially a "stop and reverse" system. Commissions You can use several commission structures for your simulated trading. The commissions for Charles Schwab, OLDE Discount, and PCFN brokerages are built into the profit tester. These commissions are accurate as of 1/1/91. You can also specify a percentage commission amount or a fixed dollar amount for each trade. Finally, you can ignore commissions altogether. Share Purchases You can elect to purchase shares of the security in either Round Lots or using all available cash. If you choose round lots, your profit test will purchase or sell stocks in groups of 100. This is important if you are using a real commission schedule, since the commission per share is reduced when you trade in round lots. Price Slippage Price Slippage refers to the price at which you want to exercise the trade. Generally, you cannot execute a trade at the exact price you want, nor can you always trade at the previous day's closing price. So, you have several options for choosing the trade price. Price Slippage Type Meaning 0 - TODAYS CLOSE Today's closing price 1 - NEXT AVERAGE Tomorrow's (High+Low+Close)/3 2 - NEXT OPEN Tomorrow's Open Price 3 - NEXT CLOSE Tomorrow's Close Price 4 - NEXT HIGH Tomorrow's High Price 5 - NEXT LOW Tomorrow's Low Price Technical Analysis Scanner (TAS) Page 26 The prices at which the BUY, SELL and STOP transactions occur are obtained from the choices given on the Profit Test Build Options screen. There are several choices, one of which is to buy at the close for the prior day. This is the default. If you have OPEN data, you should choose the option to buy at the OPEN price. If not, then you can choose an average of the price range, or several other choices. Just to elaborate on the profit testing, suppose on day 2/15/90, your buy signal is reached..in other words, the BUY WHEN is true. The price at which your buy is made is most accurately at the OPEN of the next day (since you are using CLOSING data for your test up to 2/15/90, you wouldn't have been able to really buy at the CLOSE for 2/15/90). If you don't have OPEN data, you can use some other choice from the prices on 2/16, the following day. But, in every case, the actual BUY takes place on 2/16/90, the day following the date the signal was given (can't buy after the close). Output File Name If you want the output report from the profit test to go to a file, specify the name here. Report Detail There are three choices for this option: DETAIL, TICKERSUMMARY, and TOTALSUMMARY. DETAIL Show every trade TICKERSUMMARY Show totals for each ticker TOTALSUMMARY Show totals only for all tickers Maximum Quotes You can specify the maximum number of quotes to load for the profit test. This number should be less than or equal to the Maximum Quotes per Symbol setting in your Configuration Menu. Index Ticker If you want to run a profit test that uses some index, such as the SP-500, you can specify the ticker here. Then, in your profit test, you refer to the index ticker's value with the INDEX array name. Reinvest Profits This option determines how much money you want the profit tester Technical Analysis Scanner (TAS) Page 27 to use for each trade. If you specify "Y", the profit test will use your current cash position, including profits, minus losses and commissions to determine how much money you have available to trade. If you specify "N", the profit tester will initiate each trade with the same amount of cash, regardless of your prior profits, losses or commissions. Start Date If you want to start your test on a specific date, specify that date here. Make sure that the date is a date you have in the file. If it is not, the test will begin on the first date prior to that date. End Date If you want to end your test on a specific date, specify that date here. Make sure that the date is a date you have in the file. If it is not, the test will begin on the first date prior to that date. Running the Profit Test To run the Profit Test hit the F4 key (once you leave the Options screen). If you want to save the Profit Test formulas, save it with the F3 key and then reselect it to run it. Errors In Profit Test Formulas If you have any errors in the Profit Test you have created, you will be told about them when you try to run the PROFIT TEST. An error message will be displayed and then the TAS EDITOR will be run with a file called _RUNPT.TAS. This file is the file that is created from your PROFIT TEST. It is a special form of a TAS script. You should recognize the formulas though, since they are the ones you entered in your PROFIT TEST. The EDIT screen will redisplay the error message and the explanation of the error at the bottom of the screen. Hit the ESC key and the cursor will be placed near the place where the error was found. In addition, the error message will be placed in the file to the right of the line in error. Look at the formula or condition and try to figure out what the problem is. You are only half done though. Now you have to go back to your BUILD PROFIT TEST screen (by typing ESC) and fix the formula(s) in that screen. Do not try to fix the problem in the TAS Editor screen, since this is just a temporary view of the actual Selection file. Once you have corrected the error in the Profit Test screen, be sure to save (by hitting F3) your file. Technical Analysis Scanner (TAS) Page 28 The file that is built when you create (or modify) a Profit Test has a special file extension ".PTS" (Profit Test Script). This file has a special format that can be read by the Build/Run Profit Test menu. If you go in with an editor and change any part of the .PTS file, it is very likely that the .PTS file WILL NO LONGER WORK when you pull it up into the Profit Test screen. If you want to change a .PTS file, copy it to a file .TAS file name and edit that file. Once you do that, you have to run the file as a TAS SCRIPT, not a Profit Test. EDIT TAS SCRIPT - Editing TAS Scripts TAS has a built-in text editor which can be used to create and modify TAS script files. All TAS script files end with the suffix ".TAS". When you select this menu item, you will be asked if you want to create a New Script or Modify an Old Script. If you request a new script, you will be prompted for the script name. Enter only the filename portion, not the .TAS extension. The file will be created in the \TAS directory. If you want to modify an old script, a File Name Selection Screen will appear which contains the names of all the files in the current directory ending with ".TAS". Move the cursor or mouse over to the correct file name and press Enter (or double-click). The editor screen will then appear with the contents of the file displayed. Technical Analysis Scanner (TAS) Page 29 The TAS editor cannot handle lines larger than 78 characters . If the line is longer than that, it will be broken at column 78 and continued onto the next line. If the total length of the line is more than 256 characters, the last part of the line will be lost if the file is saved. You should be aware of this when creating a script in another editor and then using the TAS editor to modify it. An arbitrary "break" at column 76 might cause a word to be split in the middle, thus introducing an error into the script. Technical Analysis Scanner (TAS) Page 30 Editor Function Keys F1 HELP Key If you need help with the editor, hit the F1 (Help) Key. You will see a list of editor commands. F3 Save Script File Key When you are done with your editing, you can save the file by hitting the F3 (Save) Key. If you do not want to save the file, hit the ESC (Abort) Key. F4 Run Script Key The Run Script key will run the script you are currently editing without saving it back to its original script file. F5 Check Script Key If you wish to check your script file for errors in syntax, press the F5 key. If there are errors in the script which can be detected by the Check Script function, an error message showing the type of error encountered and the line and column number on which the error occurred will appear in a window at the bottom of the screen. This window will disappear after a few seconds or when you hit a key. Then the script file will be positioned so that the cursor is on the line where the error was detected. It is usually the case that the error is somewhere either on that line or on the previous line. F7 Formula Builder Key-One key available in the editor is the Formula Builder Key. This key will bring up a list of Technical Indicator functions and Pre-defined Data Arrays. If you select one of the functions or arrays, the subsequent parameters of the function (e.g. MOV "Moving Average" requires 3 additional parameters) will be prompted. Enter each parameter. When you are done, the formula and parameters will be placed into your script file at the location of the cursor when you hit F7. Editor Control Keys Alt-R Rename script file. You will be asked to provide a new name for the script file. When you save the script, it will be saved with the new name. Alt-S Save script file. The script file will be saved to disk under the name shown at the top of the edit screen. You can continue editing the script after it is saved. Technical Analysis Scanner (TAS) Page 31 RUN TAS SCRIPT - Running TAS Scripts If you have created a script (or are using one of the example scripts) and you want to run it against a specific Ticker List, you should choose the "RUN TAS Scripts" option from the Main Menu. (You must have created at least one Ticker List before you can run TAS) When this option is chosen, you will be asked for the TAS script name and the Ticker List name. Each choice will be from a list of filenames ending with the appropriate extension (".TAS" or ".TCK"). Move the cursor to the correct file name for each choice and hit ENTER. QUIT This option will exit from TAS. If you want to go to DOS and return to what you were doing within TAS, use the ALT-X key. Technical Analysis Scanner (TAS) Page 32 TAS Selection Scripts - Description TAS reads each security name in the TICKER LIST from the historical (MetaStock or Chartpro format) data file. It reads the quotes for the file into the pre-defined data arrays up to the lower of either (1) the number specified in the QUOTES PER SYMBOL (in the Configure TAS Menu) (2) the number specified in #MAX_QUOTES in the script file itself, (3) all the quotes in the file, or (4), the number of quotes between the SCAN_DATE or Start Date and End Date. Once all the price history has been read into the data arrays, TAS "executes" the statements in the TAS script file. Once all statements in the file have been executed, TAS moves on to the next security's symbol in the TICKER LIST. This process continues until all the symbols in the TICKER LIST have been read or until an error is encountered in the script file. The order in which TAS processes the securities in the ticker list is in the order in which the security files are found in the Metastock directories or in the Chartpro directories, not the order of the ticker list. Technical Analysis Scanner (TAS) Page 33 TAS Script Language TAS Script Language is loosely based on the programming language PASCAL. There has to be some way to tell TAS what you want to look for, compute, print, etc., so the choices made in the way you tell it to do something are what can be called the "syntax". In a way, the language is similar to English, where you would say "If a is greater than b then tell me about it". Except, as you will see, TAS also has abbreviations for relationships like "is greater than". Other than that, however, the language can be read like English and algebraic notation combined. The following topics will give an explanation of the TAS script language. The TAS package contains numerous examples of TAS Scripts. You should print them and look at them while reading the next section. The sample scripts contain "comments" which explain what the script is doing at each point of the script. Syntax In the subsequent discussion, the word "statement" is used. A "statement" is like a sentence in English. Like a sentence, it is composed of "words". A semi-colon (;) is used to tell TAS that the statement you just entered is done. Every statement should be terminated by a semi- colon. In the syntax descriptions below, words you must use are in UPPER CASE, and parts of the statement that are up to you are in lower case. Building Blocks The "Building Blocks" of TAS scripts are the following types of items: Technical Analysis Scanner (TAS) Page 34 "VARIABLES". Variables are where you put values or, in the case of "pre-defined" variables, where you get them. The names are anything you choose, but they have to start with a letter of the alphabet and must consist of characters from the following set {A to Z, 0 to 9, and underscore}. Other characters are not allowed in the variable name. "ASSIGNMENT ". The ASSIGNMENT statement (":=" or "=") is how you can move a value from one place to another. "ARITHMETIC Operators". These are the usual ADD(+), SUBTRACT (-), MULTIPLY(*) and DIVIDE(/) and EXPONENTIATION (^). "FUNCTIONS". A "function" is a built-in Technical Indicator , math function, or "output" function which usually returns a value. IF statements An "IF" statement is used to test a condition or value. Once the condition is tested, you can perform certain actions "if" it is TRUE or "if" it is false. WHILE statement The WHILE statement is used to control the execution of a sequence of instructions that need to be repeated until some condition is false. FOR statement The FOR statement is used to describe the values to be used for a "loop" or sequence of statements that need to be executed a certain number of times. "BEGIN-END Blocks" A "BEGIN-END" block is a way to "group" several statements into one. For example, the IF statement only allows you to execute the following "statement". However, if you use a BEGIN followed by multiple statements, followed by an END, the whole series of statements from the BEGIN through the END is considered to be ONE statement. It is similar to putting parentheses around an arithmetic expression. "Logical AND" Technical Analysis Scanner (TAS) Page 35 The AND word takes a left-hand side and a right-hand side. If both are TRUE, the whole is TRUE. "Logical OR" The OR word also has a left and right side. If either is TRUE, the whole is TRUE. "RELATIONAL Operators" These are how you test the "relation" between two values. The English language form of the operators and the symbolic form for the operators are shown in the table below. You may use either form for expressing an equality or inequality relationship. English Language Keyword form Symbolic form EQUAL = GREATER THAN > GREATER THAN OR EQUAL >= LESS THAN < LESS THAN OR EQUAL <= NOT EQUAL <> Comments These are used to "document" the TAS script. They perform no function, but only help to understand what is going on in the general area of the script. They are good to use and should be included in the script to make it easier to understand. Variables The concept of a "variable" can be difficult to communicate to anyone who hasn't programmed before. Loosely speaking, it is a name given to a "place" to put a "value". Think of it as a "name Technical Analysis Scanner (TAS) Page 36 for a value"2. Except for "pre-defined" variables (see below) you can make up the names for the variables in your script. A variable name must start with an alphabetic letter, contain only letters, numbers and underscores ("_"). Some valid names are: my_stuff, my_122999, my999, m9, M32_togo, Beethoven, etc Generally, you first use variables in "assignment statements", that is, you first "put" something into them. Subsequently, you can use them as values passed to functions or another statement such as an IF statement or a WHILE statement. Creation of Variables TAS variables are created in one of two ways. You can "declare" them before using them, as you must do with ARRAY's, or you can just assign some value to them. When a variable is created, it has a "scope" or area of the script where it is guaranteed to be "known". The area of the script where it is "known" (or "scope" of the variable) is determined by the BEGIN..END block structure of the script. A variable that is created within a BEGIN..END block is "known" to all inner statements to that BEGIN..END block, but it will lose its value once the BEGIN..END block is departed. This may seem confusing at first, so here is an example: if C > 25 THEN BEGIN price = price+c; END; WRITELN(price); If the Closing price is greater than 25, then the BEGIN .. END block is entered. Now, since this is the first assignment to price, the variable price is created with a value of zero. The Closing price for the last day is added to the variable price, suppose it is 32. Now, price contains 32. Then, the END statement is reached. At this point, price is freed, since its scope was only within the BEGIN..END block in which it was first used. The ____________________ 2 The variable names are anything you choose, but they have to start with a letter of the alphabet and must consist of characters from the following set {A to Z, 0 to 9, and underscore}. Other characters are not allowed in the variable name. Technical Analysis Scanner (TAS) Page 37 subsequent WRITELN statement will write out price, but this time, the variable price is used outside of the BEGIN..END block in which it was previously created, it is a new variable. The value of price at this point will be zero3! TAS Variable Types "String" Variables These are variables to hold text information, like 'IBM', or 'THIS IS A STICK-UP'. String variables must be surrounded by single-quote (') characters. String variables can be different lengths, depending on what you put into them. They can contain blanks at the end of the variable, which you may need to remove with the TRIM function. "Numeric" Variables These are variables that hold numbers, like 32, or -75.69, or 10000034. There are two types of numeric variables, INTEGERS and REAL numbers. An INTEGER is a number which has no decimal point and must be smaller than 32,767 in value. An INTEGER can be NO LARGER THAN 32,767 in value. If you need to use a number larger than 32,767 then you must include a decimal point followed by at least one zero in the number. For example, if you want to use the number 1 million in your script, you cannot say 10000000 because the number is larger than 32,767 and it does not contain a decimal point. In this case, you must say 1000000.0 to tell TAS that the number is a REAL number. "Numeric Array" Variables These are variables that hold many numbers in an "array" (or collection of numbers). All of the numbers in the array have the same variable name; however, you cannot "look" at them all at once. You must pick out one of the numbers of the array by specifying its "location" in the array. ____________________ 3 Current versions of TAS allow you to create a variable within a BEGIN..END block and use it outside of that block. However, future versions of the program will not guarantee that such a technique will work. Technical Analysis Scanner (TAS) Page 38 Each array has exactly QUOTE_COUNT entries. The variable QUOTE_COUNT is "filled in" by TAS when the script runs for the ticker file. Given a ticker that has 100 quotes (or the maximum number of quotes to load, MAX_QUOTES, set to 100) the following indices are usable for any array in the ticker file: English Language Index Index Relative to Today Index Relative to First Day Today 0 100 Yesterday -1 99 2 Days Ago -2 98 3 Days Ago -3 97 .................... ..... ..... 99 Days Ago -99 1 An example of an array that is always available when a ticker is processed is the Closing Price array,"C". Obviously, there are many Closing Prices (one for each quote, in fact), and in order to refer to the Closing Price on a particular day, there must be some way to reference it. In the absence of any explicit reference to a particular day in an array, TAS will assume the reference is for the last day for the ticker. However, if you need to know what the value of the Closing Price was two days before the last quote's day, you have to tell TAS that you want the quote two days before. You can do this in one of three ways. Suppose you have 100 days of data loaded. To get the Closing Price quote from two days prior to the last day, you could say: 1) C[-2] 2) C[98] 3) C 2 DAYS AGO Methods (1) and (2) above use "subscript" notation to tell TAS which number in the array is needed. In the first case, you are saying "give me the Closing Price array entry 2 days backward from the last entry". The negative number says to start "counting" back days from the last day. The second version, shown in (2), says "give me the Closing Price array entry 98 days from the first day loaded". Since we had stipulated 100 days were loaded, this is the same as the price two days ago (100-98 = 2). Finally, the last expression, shown in (3), says in English that you want to retrieve the Closing Price 2 days ago. In the interest of readability, this version is the best, but it is more wordy and does incur a very slight performance penalty when you Technical Analysis Scanner (TAS) Page 39 run the script, since TAS has extra work to do in order to interpret the English phrase. In addition, you can also describe the current day's Closing value by saying CLOSE OF TODAY and you can refer to yesterday's Closing price by saying CLOSE OF YESTERDAY Other pre-defined data arrays, like H, L, C, V (for High Price, Low Price, Closing Price and Volume) are examples of arrays. If you want to refer to a closing price 10 days ago (using our earlier example of 100 days loaded), you can say C[-10] or C[90] or CLOSE 10 DAYS AGO Each time you refer to an "element" of an array, you need to either provide the "subscript" in square brackets, e.g. [-10], which means "subscript minus ten" or say "xx DAYS AGO". You can define your own variable array by "declaring" it (prior to first using it) as follows: variable_name : ARRAY; OR variable_name IS AN ARRAY; where 'variable_name' is the name by which you want to refer to the array. You might wonder "Why would I define my own array?". The answer to that depends on what you are trying to do. Generally, you define your own array because you want to put some indicator value into it. Most indicators create arrays of numbers. When using a charting program, you can see these numbers as a line on a graph. Each of the points on the line are values of the indicator for a particular day. Now, suppose you wanted to know what the value of the indicator was two days ago. Normally, when an indicator is computed, it returns (or creates) an array. However, if you don't put the result of the indicator function into an array (declared via the ARRAY declaration as shown above), then the result stored is the indicator value for the current day only. In order to "look" at the indicator value for other than the last day loaded, you must place it into an array that you have already declared. For more information on placing the results of a function into an array or variable, see the section that follows. Technical Analysis Scanner (TAS) Page 40 Assignment Statement The Assignment Statement is used to set the contents of a variable or array to the result of an "expression". An "expression" is a term, that means sequence of mathematical operations, a logical relation and/or the result of a "function". It might help to give some examples of assignment operations: a := b + 3 / 4; The ":=" (colon-equal) is the operator that says "assign to"4. So, reading the above assignment, in English, it says "add the contents of variable 'b' to the result of dividing 3 by 4. Place this result in variable 'a'". If variable 'b' contained 6 when this statement was encountered, then variable 'a' would contain 6.75 (6 + 3/4). Another example is: a := (c[-1] + c[0]) / 2; In this example, the array 'c' is pre-defined as the "closing price array". So, the statement is adding the closing price yesterday (c[-1]) to the closing price today (c[0]). It is then dividing the total of this addition by 2 and placing the result in variable 'a'. Note the use of the parentheses to "group" the addition so that it would be done before the division by 2. If there were no parentheses, the result would have been considerably different. Instead, it would have divided today's closing price by 2, added it to yesterday's closing price, and placed the result in 'a'. Another example of an assignment is the result of a "function" call. All Technical Indicators available in TAS are created by making a "function" call. In other words, the Technical Indicator is referred to by its name (the "function"). So, for example, a := mov(c,21,'E'); calculates the 21 day exponential moving average ("mov" function) of the closing price array. If variable 'a' has been declared to be an ARRAY prior to this point, then 'a' contains all the moving average "points". If 'a' has not been declared as an ARRAY, then 'a' will contain the value of the moving average at the last ____________________ 4 TAS will also accept a simple "equal" sign in lieu of the "colon-equal" sequence of characters for an assignment statement. Technical Analysis Scanner (TAS) Page 41 point of the range, i.e., today's value. See the section titled "Numeric ArrayVariables for a description of arrays and "subscripts". Arithmetic Operators Arithmetic Operators are addition (plus sign '+'), subtraction (minus sign '-'), multiplication (asterisk '*') , division (slash '/') and "exponentiation" (caret "^"). When you write an arithmetic expression, you should use parentheses to guarantee the order in which the operations are performed. In general, exponentiation is performed first, then division and multiplication are performed, then lastly, addition and subtraction. The Arithmetic Operators do not apply to math operations on arrays. If you want to add two arrays together, you cannot use the "+" operator to add them. In this case, you must use the ADD function. The same applies to the use of the other arithmetic operators on arrays. As an example of what won't work, suppose you told TAS to perform the following operation A IS AN ARRAY; A := CLOSE + HIGH TAS would assume that by CLOSE, you meant the last day's Closing Price and that by HIGH, you meant the last day's High Price. It would then add the two last day's together and place the result in the last day of array A. All prior days in the array A would be left unchanged. This is obviously not what you would want to happen, so the way to perform the addition of the Close and the High price and place it in an array A would be to do the following: A := ADD(CLOSE,HIGH); Now array A contains the sum of the Close and the High prices for each day in the security file. Functions A "function" is a reference to a "built-in" Technical Indicator function (like "MOV(...)"), an output function (like WRITE or WRITELN), or an array manipulation function (like DIVBY). See the individual descriptions of each function in the Metastock Professional User's Guide for a more complete definition of the meaning of the various Technical Indicators that are found in that program. IF Statement The IF statement is perhaps the most powerful feature of TAS. It enables you to create complex relationships between indicators based on their relationship with other indicators and values. Technical Analysis Scanner (TAS) Page 42 An IF statement is written as follows: IF condition THEN statement to execute if the condition is true ELSE statement to execute if the condition is false; The ELSE part of the IF statement is optional, but sometimes it is convenient to make a two way decision about something. You could alternatively say: IF condition THEN statement to execute if the condition is true; The TAS language does not require you to include the word THEN after the IF part of the statement. You must terminate each IF statement with a semi-colon. Note, however, that IF statements containing an ELSE part are terminated after the ELSE part. For example, IF a GREATER THAN b THEN WRITELN('a is greater than b, hurray!') ELSE WRITELN('a is not greater than b, sorry.'); Note how there is a semi-colon on the last line, but not after the first WRITELN. However, if you wanted to print a message only if "a" is greater than "b", then you would say IF a GREATER THAN b THEN WRITELN('a is greater than b, hurray!'); Note the semi-colon after the last line. WHILE Statement The WHILE statement executes a statement (or group of statements surrounded by a BEGIN..END) as long as the condition given in the WHILE statement is true. A WHILE statement is written as follows: WHILE condition statement to execute "while" the condition is true FOR Statement The FOR statement executes a statement (or group of statements surrounded by a BEGIN..END) a certain number of times, and while a condition is true. The FOR statement has three parts to it. each part separated from Technical Analysis Scanner (TAS) Page 43 the previous part by a semi-colon. The first part is done once, before the statement following the FOR is executed. This part of the FOR statement is called the initializer. The second part is the test of the condition that controls the loop. This part is called the condition. The third part is executed each time after the statement following the FOR has been executed. This third part is called the re-initialization step. The format of the FOR statement is FOR initializer; condition; re-initialization; statement; As an example, suppose you wanted to add the HIGH and the LOW for each day of the security's loaded data and also get the difference of the HIGH and the LOW. Also suppose you wanted to place both of these values in their own array. You could put a FOR loop "outside" of the actions you wanted to perform for each day. Using the index variable i to refer to each day's array entry, you would set it up as follows: HIGHLOWSUM : ARRAY; HIGHLOWDIFF : ARRAY; FOR i = 1; i <= QUOTE_COUNT; i = i+1; BEGIN HIGHLOWSUM[i] = CLOSE[i] + HIGH[i]; HIGHLOWDIFF[i] = CLOSE[i] - HIGH[i]; END; This statement is a very powerful and convenient way to "iterate" or loop through some portion of the price or indicator data. BREAK Statement The BREAK statement can be used within either a FOR or WHILE loop to "break" out of a loop before the terminating condition has been reached. BEGIN..END Statement Suppose you want to do more than one thing if the condition "a is greater than b" is true. In that case, you would need to use a BEGIN .. END block. A "BEGIN..END" block "groups" all statements between the BEGIN and the END so that the entire "group" is treated as if it were one statement. This is useful in the case of the IF (or FOR and WHILE) statement, because the action to be taken following the statement THEN or ELSE part of the IF can only be one statement. But if you use the BEGIN..END block to group several statements, the entire Technical Analysis Scanner (TAS) Page 44 block is treated as a "single" statement. Think of BEGIN..END blocks in the same way you would think of parenthesized arithmetic expressions. You use parentheses to "group" some operations so that they are treated as a group. An example of the use of the BEGIN..END block in an IF statement is shown below: IF a GREATER THAN b THEN BEGIN a := a - 1; b := mov(c,21,'E'); WRITELN('New values for a and b are:' ,a,' ',b); END; All three statements following the BEGIN will be executed (acted upon) if the value of "a" is greater than the value of "b". If you had left out the BEGIN..END section, only the first statement ("a := a - 1") would have been done if "a GREATER THAN b" was true. The following two statements would have ALWAYS been done, since they were not part of the IF. GOTO Statement and LABELS You can use the GOTO statement in a script to transfer control to a LABEL you define in the script. A LABEL is defined by a COLON (":") immediately followed by a LABEL NAME. For example, in the script below, the third line has the sequence ":AGAIN". This makes "AGAIN" the name of a LABEL. On the tenth line of the script, there is a "GOTO AGAIN" which transfers the "flow of control" of the script back to the statement just following the label 'AGAIN'. The purpose of the script below is to show an example of GOTO and LABEL's, but incidentally, it also computes all the moving averages for periods from 20 days to 40 days and prints them. ma_array10 IS AN array; n = 20; :AGAIN ma_array10 = mov(c,n,'e'); writeln(ticker,date,int(n),' day moving average is ',ma_array10); n = n+1; if n LESS THAN 40 then GOTO AGAIN; The following script is an example of using GOTO and LABEL's to transfer control FORWARD in the script. Note the GOTO B in the Technical Analysis Scanner (TAS) Page 45 first IF statement. n = 1; :a if n GREATER THAN 30 then goto b; { DO SOME WORK HERE USING THE VALUE OF N} n = n+1; goto a; :b writeln('done...n is ',n); When you use the GOTO within a BEGIN..END block, you must be careful not to GOTO someplace outside of the block. Your script must encounter the END statement which matches the previous BEGIN statement. GOSUB statement The GOSUB statement is used to "go to a subroutine". This statement can be used when you have the same section of script code that you want to execute several times. Rather than including the same lines in the script in each place you want to use them, you can place them in one location in the script and use GOSUB each place you want to execute them. When you use GOSUB, you specify a label where the 'subroutine' starts. When the subroutine is completed, it should have a RETURN statement. The RETURN statement will return the script control back to the statement FOLLOWING the GOSUB. Here is a sample script using the GOSUB statement: Technical Analysis Scanner (TAS) Page 46 a = 5; gosub s1; gosub s2; return; :s1 begin writeln(ticker); writeln('s1 entered, a = ',int(a)); return; end; :s2 a = a+1; begin writeln('s2 entered, a = ',int(a)); gosub s3; return; end; :s3 a = a+1; begin writeln('s3 entered, a = ',int(a)); return; end; The output from this script is: AMH s1 entered, a = 5 s2 entered, a = 6 s3 entered, a = 7 RETURN statement The RETURN statement in a script will stop processing the current ticker or return from a GOSUB call. For example, if you want to avoid computing several complex indicators if there are less than 100 quotes in the file or the price is less than $5, you could put the following section of code BEFORE your calculations in the script: IF quote_count LESS THAN 100 OR close LESS THAN 5 THEN RETURN; Or, if you have a subroutine that you call with the GOSUB statement, you need to return back to the place where the GOSUB was made by using a RETURN statement at the end of the subroutine. Technical Analysis Scanner (TAS) Page 47 GOSUB SUB1; {Call subroutine 1} RETURN; {Return to TAS and end script} :SUB1 { BEGINNING OF SUB1} { DO WHATEVER SUB1 DOES HERE ......................} RETURN; { RETURN FROM SUB1} Logical Operators You can combine relations by using the words "AND" and "OR". They have the same sense as in English. Whenever you use AND and OR, you can use parentheses to group your relations to be sure they are computed the way you want them to be understood. For example: IF a GREATER THAN b AND b EQUAL TO 1 THEN WRITELN('a is greater than b and b is equal to 1'); This example compares "a" to "b". If "a" is greater than "b", then it compares "b" to the number 1. If "b" is equal to 1, then the message a is greater than b and b is equal to 1 will be printed. If either of the "relations" (a in "relation" to b AND b in "relation" to 1) is not true, then the WRITELN will not be done. On the other hand, suppose we want to print the message if either of the conditions is true. Then we would say: IF a > b OR b = 1 THEN WRITELN('a is greater than b OR b is equal to 1'); In this case, it would print the message if "a" were greater than "b" or if "b" were equal to 1. Relational Operators Relational Operators describe a "relationship" between the expression on the left of the operator and the expression on the right of the operator. For example, "a > b". 'a' is on the left side, 'b' is on the right side, and the operator is '>' which means "greater than". Relational operators can be expressed using mathematical notation (">", "<", "<>", ">=") or by using English forms of the same relation, such as "GREATER THAN", "LESS THAN", etc). Comments Comments are surrounded on both sides by "curly braces". These are the characters at the right of your keyboard. They look like this: Technical Analysis Scanner (TAS) Page 48 { - Left "curly brace" } - Right "curly brace" You can place these "curly braces" around any thing in your script file that you do not want TAS see. It is only for your eyes and the eyes of other humans. Pre-Defined Variables Predefined Variables are variables that are "filled in" when each MetaStock TICKER is processed or at specific times during the processing of ticker files. TICKER The 'ticker' symbol, e.g., AXP FULLNAME The 'full name', e.g., AMERICAN EXPRESS DATAPATH contains the DOS file name of the data subdirectory currently being processed. TICKER_PERIOD contains the periodicity of the ticker file. This is taken from the Metastock PERIOD field. QUOTE_COUNT The number of quotes in the file QUOTE_RANGE Initially set to QUOTE_COUNT by TAS. This variable can be modified by the script to set the index of the last quote in the file for computation. Somewhat similar to the Metastock REF function.. FIRST_TICKER Variable, which, if equal to 1 (one), indicates this ticker is the first to be processed. LAST_TICKER Variable, which, if equal to 1 (one), indicates this ticker is the last to be processed. DATE The date of the latest quote in the file in the format MM/DD/YY. P The "last computed" array. For example, X := MOV(C,30,'E') places the last day's 30day EMA in 'X' and the entire EMA array is in 'P' until another function is called. Technical Analysis Scanner (TAS) Page 49 PLOT_PHASE Variable which is set to 1 when the Profit Test Script is entered for the first time for a ticker. TEST_PHASE Variable which is set to 1 when the Profit Test Script is entered for the EACH quote for a ticker. END_PHASE Variable which is set to 1 when the Profit Test Script is entered for the last quote for a ticker. Pre-Defined DATA Arrays A pre-defined DATA Array contains one entry of one type of value for each day in the ticker file. There are as many entries in each array as there are days loaded for the ticker. Unlike user-defined arrays, the pre-defined arrays should not be defined within the script with the array declaration. Since they are pre-defined, they are always available for use within the script. There are two ways to refer to each of the pre-defined arrays. There is an English language name, such as CLOSE and a "short variable name", such as "C", for the Closing Price array. The names for the pre-defined arrays are shown in the table that follows: English language name for array Short Variable Name Description Pre-defined DATA Arrays OPEN O The OPEN PRICE "data array" HIGH H The HIGH "data array" LOW L The LOW "data array" CLOSE C The CLOSE "data array" VOLUME V The VOLUME "data array" OPEN_INTEREST OI The OPEN INTEREST "data array" INDEX INDEX Array containing the CLOSE quotes for a TICKER defined by an INDEX command. DATES DATES Array of DATES associated with each of the price entries. These dates are in number format, not string format. Technical Analysis Scanner (TAS) Page 50 Pre-defined Functions TAS functions which are also available in MetaStock have the same names and (nearly the same) parameters as those documented in the MetaStock Custom Formulas Section of the MetaStock "User's Manual". Functions which are unique to TAS (not shared by MetaStock) are described in detail in this document. The MetaStock functions are only summarized. Please refer to the Metastock documentation or the Encyclopedia of Technical Market Indicators for a complete description of the functions and their parameters. In some instances, the parameter to a MetaStock named function has to have single quotes around it. This is the case with any function that passes a single character as a parameter, such as the last parameter in the "mov" (Moving Average) function. Technical Indicators available in Metastock ad() Accumulation/Distribution The Accumulation/Distribution indicator, developed by Marc Chaikin, calculates the percent range a stock moves in a given day and multiplies this times the volume. The relationship of the close is (Close - Low) - (High - Close). This is then divided by the range (High - Low) and multiplied by the volume. The result is added to the running total. The buying pressure is compared to selling pressure for each day and like the OBV the indicator is cumulative. The A/D line is analyzed much like the OBV. If a stock is going to rise then there should be volume behind it. This volume is measured by the degree the close is closer to the high of the day. If there is buying pressure then the percent of the close times the volume will be greater. This adds more to the A/D line and divergences may be detected before the price has actually risen to a great extent. Sample script: {A/D Volume Line for one year of data} Technical Analysis Scanner (TAS) Page 51 #max_quotes 265 opengraph(3,-264,0); sizegraph(3,1,3); graph(1,'PRICE'); graph(v,'VOLUME'); graph(ad(),'ACCUMULATION DISTRIBUTION LINE',mov(ad(),30,'s'),'30 DMA'); closegraph(); References: Chaikin, Marc. 177 E. 77th Street, New York, NY 10021 adx(p) Average Directional Movement adxr(p) Average Directional Movement Rating add(a,b) Add two arrays Add each element of array "a" to the corresponding element of array "b". cci(p) Commodity Channel Index Array p = number of periods co() Chaikin's Oscillator cos(a) Trigonometric cosine of each entry in array 'a'. Use the _cos(n) function to compute the cosine of a single number "n". cum(a) Cumulative Sum of Array "a" div(a,b) Divide two arrays Divide each element of array "a" by an element of array "b". dmi(p) Directional Movement Index exp(a) Exponential Function Computes the exponential value of each entry in array "a" Use the _exp(n) function to compute the exponential of a single number "n". hhv(a,p) Highest High Value Returns Highest High Value in the array 'a' over the period Technical Analysis Scanner (TAS) Page 52 'p' llv(a,p) Lowest Low Value Returns Lowest Low Value in the array 'a' over the period 'p' log(a) Exponential Logarithm of each entry in array 'a'. Use the _log(n) function to compute the exponential logarithm of a single number "n". macd() Moving Average Convergence/Divergence Computes Gerald Appel's MACD indicator. mdi(p) Minus Directional Movement (-DI) mo(p) Momentum Array p = number of periods mov(d,p,t) Compute Moving Average Moving Average Array d = Data Array p = number of periods t = Moving Average Type 'E' - Exponential 'S' - Simple 'W' - Weighted mul(a,b) Multiply two arrays Multiply each element of array "a" by the corresponding element of array "b". neg(a) Negative of Array "a" Computes the negative of an array "a". nvi() Negative Volume Indicator obv() On Balance Volume On balance volume uses the change of the close plus volume to determine how much buying or selling pressure there is in a stock. If the close is higher than yesterday then the volume is added to yesterdays OBV. If the stock closes lower than yesterday the volume is subtracted from the OBV indicator. Because this indicator keeps a running total it can reveal the accumulation or distribution of a stock. This can show early interest in a stock or an eventual sell off. OBV can be analyzed several ways. A simple moving average of the OBV can be used to watch for breakouts. For more intense study, Technical Analysis Scanner (TAS) Page 53 the patterns the indicator makes can be compared to the stock for divergences, higher highs, or lower lows. These patterns may suggest activity not seen in just in the price chart. Sample script: {On Balance Volume for one year of data} #max_quotes 265 opengraph(3,-264,0); sizegraph(3,1,3); graph(1,'PRICE'); graph(v,'VOLUME'); graph(obv(),'ON BALANCE VOLUME',mov(obv(),30,'s'),'30 DMA'); closegraph(); References: Granville, Joseph E. New Strategy of Daily Stock Market Timing for Maximum Profit. Englewood Cliffs NJ: Prentice_Hall, 1976. oscp(p1,p2,t,r) Price Oscillator Price Oscillator formed by subtracting a "t" type "p2" day moving average of the Closing Price from a "t" type "p1" day moving average of the Closing Price. p1 = shorter moving average period p2 = longer moving average period t = Moving Average Type 'E' - Exponential 'S' - Simple 'W' - Weighted r = ROC Type '%' - percentage ROC '$' - Unit ROC oscv(p1,p2,t,r) Volume Oscillator Volume Oscillator formed by subtracting a "t" type "p2" day moving average of the Volume from a "t" type "p1" day moving average of the Volume. p1 = shorter moving average period p2 = longer moving average period t = Moving Average Type 'E' - Exponential 'S' - Simple 'W' - Weighted r = ROC Type '%' - percentage ROC '$' - Unit ROC Technical Analysis Scanner (TAS) Page 54 pdi(p) Positive Directional Movement (+DI) per() Performance Indicator Performance Indicator computed as follows: pvi() Positive Volume Indicator rsi(p) Wilder's Relative Strength Indicator p = number of periods roc(d,p,r) Rate Of Change Array Computes the rate of change of the data array "D" over "p" periods, using either a percentage basis or a dollar unit basis. d = Data Array p = number of periods r = ROC Type '%' - percentage ROC '$' - Unit ROC sar(i,m) Wilder's Parabolic (SAR) or Stop and Reverse indicator. Create a parabolic stop line either over or under the price graph. where 'i' = increment value and initial 'm' = maximum acceleration factor Wilder's explanation uses the values of i = .02 and m= 0.20 In ChartPro, this indicator is referred to as Technical Study 'PTP' sin(a) Trigonometric sine of each entry in array 'a' Use _sin(n) for the sine of a single number. sqrt(a) Square root of each entry in array 'a'. Use the _sqrt(n) function to compute the square root of a single number "n". std(d,p) Statistical Standard Deviation. Computes the standard deviation of the array 'd' using 'p' data points. Defined as the square root of the variance (see var below). Technical Analysis Scanner (TAS) Page 55 stoch(p,s) Stochastic Oscillator p = number of periods s = k slowing periods sub(a,b) Subtract one array from another Subtract each element of array "b from the corresponding element of array "a". sum(a,p) Summation of array over period Create a 'p' day summation of array 'a'. tan(a) Trigonometric tangent of each entry in array 'a'. Use _tan(n) for the tangent of a single number. trix(p) TRIX Function Calculate a 1 day percent Rate of Change of a p day triple exponential moving average of the closing price. tsf(a,p) Time Series Forecast function. This function computes a p day linear regression of the array a for each day. var(d,p) Statistical VARIANCE of the array 'p' over the time period 'p'. vol(pm,pr) Volatility Indicator. This is the 'pr' day Rate Of Change Oscillator of a 'pm' day exponential Moving Average of the difference between each day's high and low price. wc() Weighted Close defined as (2 * CLOSE + HIGH + LOW)/4 willa() William's Accumulation/Distribution. willr(p) William's %R for 'p' periods. This is equivalent to a 'p' period stochastic with 1 day smoothing. The result is then reduced by 100. zig(a,r,t) Zig Zag Function Compute a ZIG ZAG function for array 'a'. 'r' is the minimum percentage or unit (dollar) change which must be made in order to reflect a change in the Zig Zag line. The third parameter 't' is either '%' or '$'. If it is '%', then the 'r' value is expressed as a percentage change, otherwise it is a unit (or dollar) change. Technical Analysis Scanner (TAS) Page 56 If you want to see what kind of profits you could make, run the ZIG.PTS Profit Test file. According the Equis Metastock User's Manual, "The Zig Zag indicator has 20/20 hindsight...Unfortunately, the Zig Zag's foresight is not as profitable. This is because the last "leg" of the Zig Zag indicator isn't fixed until future prices are known. If you use the Zig Zag indicator to predict future prices, you are probably fooling yourself." Sorry, but that's the way it works. It is provided in TAS as a sort of "benchmark" to judge how much the IDEAL strategy could SQUEEZE out of a portfolio. It is nearly ideal, because it knows the future. TAS Functions addto(a,n) Add number to array Adds the number "n" to each entry of array "a" and returns the result in an array. angle(a) Angle of a line returns the angle in degrees of the line described by the array 'a'. This function is only usable on an array that has been created by either linreg or linreg2. alpha() Alpha function The alpha function is a "sister" function of the beta function. This function describes how much the stock's price would have moved on average on a yearly basis assuming the INDEX did not change. An alpha of .20 means that the stock would have increased 20% more than the INDEX during the year. In terms of a two way linear regression (performed by the beta function), the alpha is related to the y-intercept of the linear regression line. It is important to note that the alpha function must be called immediately after the beta function. At any other time, the results of the alpha function are undefined. avgprc() Average Price Creates an array where each entry is that day's (HIGH+LOW+CLOSE)/3 bbandt(p,s) Top Bollinger Band Bollinger Band upper (top) indicator for "p" periods with "s" standard deviations added to the p-day simple moving average. Technical Analysis Scanner (TAS) Page 57 bbandb(p,s) Bottom Bollinger Band Bollinger Band lower (bottom) indicator for "p" periods with "s" standard deviations subtracted from the p-day simple moving average. beta(r) "Beta" function The beta function calculates the linear regression of the percentage rate of change of the closing price (of the current ticker being processed) to the percentage rate of change of the INDEX. Values of r, the rate of change period, are 'D' Daily rate of change 'W' Weekly rate of change 'M' Monthly rate of change The weekly rate of change calculates the rate of change from Friday to Friday and the monthly rate of change calculates the rate of change from the first of each month. The actual value returned by the beta function is the slope of the line created by this two way linear regression. The purpose of the beta function is to measure the stock's sensitivity to movement in the general market over the period of time chosen. A beta value of 2.00 means that the stock tends to move with the market, but 2 times as far (percentage change is twice as much). A beta of -.5 means that the stock moves in the opposite direction of the market, but only one half as far. corrcoef() Correlation Coefficient returns the "correlation coefficient" of the last linear regression performed. This value ranges from -100 to +100. If the data points match the points in the linear regression approximation, the correlation coefficient will be 100. If the points show no correlation with the approximation, the correlation coefficient will be zero. datestr(d) Create a formatted date Create a "date string" in the form MM/DD/YY from the DATES array entry 'd'. daymon(d) Day of Month function Returns the "DAY OF THE MONTH" of the DATE contained in variable "d". The value returned is the day of the month. For example, daymon(910204) will return 4. Technical Analysis Scanner (TAS) Page 58 daywk(d) Day of Week function Returns the "DAY OF THE WEEK" of the DATE contained in variable "d". The value returned is a number from 0 to 6, where 0 is Sunday, 1 is Monday, 2 is Tuesday, 3 is Wednesday, 4 is Thursday, 5 is Friday and 6 is Saturday. divby(a,x) Divide array by number Divide each element of array "a" by the value of "x". In this case, "x" is a single number. dump_array Dump Array Contents dump_array(a1,a2...aN) Dump the contents of arrays"a1" to "aN" to the screen or a file. Each entry in the array is shown as a decimal number with the entry number in square brackets to the left, followed by the date. DUMP_ARRAY can be called with up to 12 array names. They will be printed side-by-side on the display. This function is useful for checking out the contents of an array...in other words, it is a debugging tool, not a report generating tool. int(x) Create Integer Turns the number "x" into an "integer" by dropping any part of the number to the right of the decimal point. An integer is a number without a fractional part (the part after the decimal). The maximum number that you can turn into an integer is 32,767. isect(a,b) Find array intersection Find the latest intersecting point of the two arrays "a" and "b". Returns the number of days since the two arrays intersected (as a negative number) or 1 (positive one) if they have never intersected. NOTE: Since the graph of the two arrays actually crosses BETWEEN two days, the value returned will be the later day AFTER the crossing. For example, if the arrays crossed between yesterday and today, the value returned will be zero. If they crossed between two days ago and yesterday, the value returned will be -1, and so forth. Technical Analysis Scanner (TAS) Page 59 linreg Linear Regression over time linreg(a,s,e) Create a linear regression line using "least-squares" method to find the mathematical average of the values in the array "a" starting at entry "s" and ending at entry "e". If "s" is zero, it refers to the first value in the array. If "e" is zero, it refers to the last value in the array. Positive values for "s" or "e" refer to the appropriate array entries (counting from 0). A negative number in the "s" or "e" index is subtracted from the total number of entries in the array to get the appropriate positive array index. For example, x : array; x := linreg(c,-50,-10); will find the line passing most closely through the closing prices from 50 days before the last day in the file to 10 days before the last day in the file. linreg2 Linear Regression of two variables linreg2(y,x,s,e) Create a linear regression line using "least-squares" method to find the mathematical average of the values in the array y over the array x starting at entry "s" and ending at entry "e". If "s" is zero, it refers to the first value in the array. If "e" is zero, it refers to the last value in the array. Positive values for "s" or "e" refer to the appropriate array entries (counting from 0). A negative number in the "s" or "e" index is subtracted from the total number of entries in the array to get the appropriate positive array index. For example, x : array; x := linreg2(c,v,-50,-10); will find the line passing most closely through the closing prices and volume from 50 days before the last day in the file to 10 days before the last day in the file. load(t,f) Load a data array The load function will retrieve the first occurrence of a ticker from the Metastock directory. The ticker is specified as the first parameter to the load function. The second parameter of the load function is the field to be loaded from the ticker file. The name of the field must be surrounded by single quotes or it must be a string variable containing the name of the field. The field names are the same as the pre-defined data array names, that is, C for closing price, H for high price, etc. Technical Analysis Scanner (TAS) Page 60 The value returned from the load function is an array containing the portion of the ticker file requested by the field name. macdx(s,l,t) "MACD Extended" Compute an MACD indicator using a short term EMA of "s" periods, a long term EMA of "l" periods, and a trigger line of "t" periods. mfi(p) "Money Flow Index" as described in Equis "The Pointer" Volume 5, Number 4 and corrected in Vol 6, Number 1. month(d) Month function Returns the Month (1-12) of the date value contained in the parameter. mulby(a,x) Multiply by number Multiply each element of array "a" by the value of "x". In this case, "x" is a single number. over(a,b) Over function If array "a" is "over" array "b", this function returns the number of days since array "a" crossed above(or over) array "b". See the description of the isect function page for the values returned when the arrays cross. peak(a,n) Find Peak in Array returns the index of the 'n'-th peak value in array 'a'. A 'peak' is defined as a high value surrounded by lower values. The value returned from this function is the array index to the peak value. In the figure above, the peak(C,2) call would return the index of the point marked P2. If you consider the volume vertical bars a day, then the value returned in this example would be '-13', or 13 days prior to the last day. per1(a) Performance using Array Computes the "performance indicator" for an array a. The performance indicator is computed as Technical Analysis Scanner (TAS) Page 61 set(a,v) Set Array to Value Sets all entries in array 'a' to the value 'v'. For example, you could use this function to create an array where each entry is 22.5. slope(a) Slope of Line will return the mathematical "slope" of the line whose points are contained in array "a". This array must have been created with the linreg function. strlen(s) String Length The strlen function will return the length of the string variable "s" as an integer. For example, X = strlen('IBM'); will set X to 3. subfrom(a,n) Subtract number from array Subtract the number "n" from each entry in array "a" returning the result in an array. substr(s,b,l) Substring function The substr function takes a string "s" as the first argument and extracts the substring starting at character position 'b" for the length "l". For example, X = substr('ABCDEF', 2,4) will create set the variable X to the string 'BCDE'. trough(a,n) Find Trough in Array returns the index of the 'n'-th "trough" value in array 'a'. A 'trough' is defined as a low value surrounded by higher values. The value returned from this function is the array index to the trough value. In the figure shown with the peak function above, the trough(C,2) call would return the index of the point marked 'T2'. Based on the volume bars shown, the value returned in this example would be '-11', or 11 days prior to the last day. tr() Wilder's True Range This function creates an array containing for each day, the higher of the following differences : Between today's high and today's low. Between today's high and yesterday's close. Between today's low and yesterday's close. The value of tr() for any day is always positive or zero. Technical Analysis Scanner (TAS) Page 62 trim() Trim blanks from a string This function takes a string variable as input and returns a string variable as the return value. The returned string variable has all spaces removed from the right hand portion. year(d) Year function Returns the Year (0-99) of the date value contained in the parameter. zero(a) Zero Array Sets each entry of array 'a' to zero. Technical Analysis Scanner (TAS) Page 63 Output Functions WRITE and WRITELN Functions There are two direct output functions, WRITE and WRITELN. The WRITELN function is identical to the WRITE function, except that WRITELN causes a NEW LINE to be added at the end of the last field. The parameters to WRITE (and WRITELN) are either text strings, like 'this is a text string', surrounded by single quotes ('), or "variable values". A variable value is a value that you have assigned to a name by use of a formula or constant setting. There are "pre-defined" variables, such as H, L, C, V, O, TICKER, FULLNAME. These pre-defined variables are "filled in" when TAS reads the data values for each symbol. You can control the formatting of your output to some extent by using the characters sequence "\t" (backslash tee) in your text string. This will place a "tab" character in the output. TAS places "tab stops" every 4 columns of the output line. You can cause a new page to be printed by placing a "\f" (formfeed) in your WRITELN string. In addition, the sizes of the two types of "numbers", are constant. If you are printing an INTEGER value, it is five characters wide, left-justified. If you are printing a number with a decimal point, it is eight characters wide (99999.999). This will allow you to line up the output with column headings. FORMAT Function The FORMAT function can be used to precisely control the way numbers print. This function takes two arguments. The first argument is the number to be formatted. The second argument is a "format specifier" string. A format specifier string is is formed as follows: % [width] [.prec] [type] The [width] is the minimum number of characters to print. Technical Analysis Scanner (TAS) Page 64 The [.prec] is the maximum number of characters to print or the minimum number of digits to print. [type] for the FORMAT function can only be 'f' for REAL numbers For example, to print the closing price without the decimal point normally printed with the WRITELN fucntion, you could say writeln('Closing price is ',format(c of today,'%4.0f')); This would print the closing price in a field that is 4 characters wide with zero decimal places. Note also that the closing price printed would be rounded to the nearest integer. SORT Functions TAS contains functions which can be used to sort your report output. Rather than doing WRITE and WRITELN, you can call the SORTOUT function to place the report data in a "sort buffer". Once all the tickers have been processed (when LAST_TICKER is 1), you can then sort the data using the SORTON function. Finally, you can retrieve the sorted "lines" with the SORTGET function or print them with the SORTPRINT function. If you want to experiment with the SORT commands, you should start out simply and then work toward more complex combinations. These are advanced functions and are not necessarily appropriate for the person who doesn't want to plan their requirements. In order to understand how the sort commands work, you need to understand some terms. The first term is a "line". Each time you use the SORTOUT function, you give it a "line" of data which is placed in the "sort buffer". Each "line" is composed of 'columns". A "column" is a group of data values that are repeated for each SORTOUT function. So, for example, if you wanted to create a list of TICKERs and their Closing Prices, you would have two "columns", the TICKER and the Closing Price for the ticker. The "line" would consist of the combination of the TICKER and Closing Price. SORTOUT The SORTOUT function takes up to 40 parameters which are fields to be placed in the 'sort buffer'. As each ticker is processed, you can place the computed results in the 'sort buffer'. Technical Analysis Scanner (TAS) Page 65 For example, suppose you wanted to create a report of tickers in order by their volume. You wanted the report to contain the TICKER, the High, Low and Closing prices as well. For each ticker you would say SORTOUT(TICKER,H,L,C,V); SORTON Once all tickers have been processed, and their lines of data have been placed in the sort buffer using the SORTOUT function, you can sort the lines of data with the SORTON function. The SORTON function requires pairs of two parameters as follows: SORTON(column_number_1, direction_1,column_number_2, direction_2,....,column_number_N,direction_N) where: column_number_* is the parameter position of the data field (column) in the SORTOUT command that placed the data in the sort buffer. direction_* is either 'a' for ASCENDING or 'd' for DESCENDING sort. The SORTON function will sort first on column_number_1 in direction_1, then on the next column/direction pair, etc. Using the example given in the SORTOUT description above, since the report was to be sorted by VOLUME, that is the 5th parameter position ("column") in the SORTOUT function shown. The SORTON function returns as its value the number of records in the sort buffer. SORTGET After a SORTON function is called, the data in the sort array is in some particular sorting order. If you want to retrieve each "line" from the sort array, one at a time, you can use the SORTGET function. When you use the SORTGET function, you are asking TAS to "retrieve" the columns of data in the next line from the sort buffer and to place those data values in the variables you specify as parameters to the SORTGET function. After the SORTGET function returns, the variables you named in the SORTGET function call will be "filled in" with the values from the next line (in sequence) of the sort buffer. Technical Analysis Scanner (TAS) Page 66 SORTGET(v1,v2,v3,....,vN) where v1 is the first variable to be filled in by SORTGET v2 is the second variable to be filled in by SORTGET, and vN is the last variable to be filled in by SORTGET. The number "N" must be exactly equal to the number of parameters used in the SORTOUT command that filled in the sort buffer. The SORTGET function returns as its value a 1 (one) if the variables were "filled in" by a record from the sort buffer and 0 (zero) if not. This returned value can be used in a WHILE loop to determine when the last sort record has been obtained. SORTPRINT The trickiest part of using the SORT feature is the specification of the 'format string' used by the SORTPRINT function. If you have access to a C Programming book, you will find the format specifications under the PRINTF() function description. Short of that, a summary of the types of format specifiers follows: A format specifier is formed as follows: % [width] [.prec] [type] The [width] is the minimum number of characters to print. The [.prec] is the maximum number of characters to print or the minimum number of digits to print. [type] is one of three values: 'ld' for INTEGER values (result of INT() function) 'f' for REAL numbers (most results) 's' for a STRING CONSTANT (like TICKER or DATE) So, to print the results of the SORTOUT request given above, there must be five format specifiers (since there are five parameters to SORTOUT). The first parameter is the TICKER (which is a 'string') so its format specifier would simply be '%s'. The next three fields are all 'real' numbers (that is, they have decimal points), so their format could be '%7.3f' which would say, make the field 7 characters wide, and include three decimal places, like this '999.999', so this will work fine unless the price is greater than 1000. If it were, you could make the field '%8.3f' to add more room at the left. Technical Analysis Scanner (TAS) Page 67 Finally, the last field, V (VOLUME) does not contain any portion beyond the decimal point. That is, shares are reported in whole numbers. But, because Volume is typically larger than the maximum value of an "integer" field (32,767) , it is also a 'REAL' number. To make the volume field report in whole units, without a decimal point, you would say '%8.0f' which would place volume in an eight character field with no decimal. So, the format string for the SORTPRINT would be: SORTPRINT('%s %7.2f %7.2f %7.2f %8.0f\n'); The '\n' at the end of the SORTPRINT format string is to start a NEW LINE after printing this line. Column Headings For an example of controlling the printing of 'headings' in your TAS output, go to the section describing the pre-defined variable FIRST_TICKER. Using this variable, you can determine when to print a heading initially in your report. In addition, since all variables are initially set to zero before the first TICKER file is processed, you can use a variable to accumulate a "line count". You can test this variable and generate a new heading each time it is greater than the number of lines on your page (e.g. 66). An example of how to place a heading on each page of the report follows: IF FIRST_TICKER OR (LINE_COUNT > 65) THEN BEGIN LINE_COUNT := 0; WRITELN('YOUR REPORT HEADING WOULD GO HERE'); END; Then, each time you wrote a line in your script you would execute the statement: LINE_COUNT := LINE_COUNT + 1; Technical Analysis Scanner (TAS) Page 68 Profit Test Statements Profit Test Statements are used to: Define which Technical Indicators are to be computed. Define BUY conditions Define SELL conditions Define STOP conditions See Page for an explanation of how the price at which a transaction is executed is determined. The statements used to describe the situations above are described in the next 4 sections. PLOT statement: Define Technical Indicators The PLOT statement is used to create the formulas or indicators which will be used in the subsequent profit test. The PLOT statement is executed once per ticker symbol, and must be placed prior to any of the BUY/SELL/STOP WHEN conditions. The format of the PLOT statement is: PLOT stmt; where 'stmt' can be a single statement or a BEGIN..END block. For example, if your profit test is to test the Commodity Channel Index (CCI) for 14 days, you could say: CCI_ARRAY : ARRAY; { Define the cci array} PLOT CCI_ARRAY := CCI(14); In the example, only one indicator is computed, so there was no need to use the BEGIN..END block. Suppose, however, that we want to incorporate Wilder's RSI in the profit test as well. Then we would say: Technical Analysis Scanner (TAS) Page 69 CCI_ARRAY : ARRAY; { Define the cci array} RSI_ARRAY : ARRAY; { Define the rsi array} PLOT BEGIN CCI_ARRAY := CCI(14); RSI_ARRAY := RSI(14); END; { of PLOT statement} BUY WHEN - Define BUY Conditions The BUY WHEN condition causes the profit tester to 'buy' the stock if the condition is true. BUY WHEN expression; where 'expression' can be any combination of logical or relational operators. For example, using the last PLOT statement in the previous example, we will issue a BUY signal when the CCI rises above -100 and the RSI is less than 40: BUY WHEN cci_array OF YESTERDAY IS LESS THAN < -100 AND cci_array OF TODAY IS GREATER THAN -100 AND rsi_array IS LESS THAN 40; SELL WHEN - Define SELL Conditions The SELL WHEN condition causes the profit tester to 'sell' the stock if the condition is true. SELL WHEN expression; where 'expression' can be any combination of logical or relational operators. For example, using the last PLOT statement in the previous example, we will issue a SELL signal when the CCI drops below 100 and the RSI is greater than 60: Technical Analysis Scanner (TAS) Page 70 SELL WHEN cci_array OF YESTERDAY > 100 AND cci_array OF TODAY < 100 AND rsi_array OF TODAY IS GREATER THAN 60; STOP (LONG or SHORT) Condition The STOP LONG and STOP SHORT statements close a "long" position or a "short" position, respectively, by either selling or buying to cover an open position. To close out a long position (by selling), the statement is: STOP LONG WHEN expression; where 'expression' can be any combination of logical or relational operators. To close out a short position (by buying), the statement is: STOP SHORT WHEN expression; where 'expression' can be any combination of logical or relational operators. Adding a long stop to the example built in the prior sections, we could say that we want to issue a stop if, after having gone long, the CCI drops below -100 again. In that case, we could say: STOP LONG WHEN cci_array < -100; TAS Profit Tester Functions The Profit Tester feature of TAS uses the following functions to indicate the buy/sell transactions controlled by a Profit Testing script. Technical Analysis Scanner (TAS) Page 71 pt_buy() Buy the stock at the current closing price if not already held. If testing Short positions, buy to 'cover' the short sale. pt_sell() Sell the stock at the current closing price if it has been bought. If testing Short positions, sell the stock short. pt_stop(t) Issue either a Long Stop or a Short Stop. The parameter 't' is either 'L' for a Long Stop, or 'S' for a Short Stop. pt_price(t) Returns the share price at which the last OPEN transaction was executed. If there is currently no position held, then the value returned depends on the value of the parameter t. If t' is 'L', the value returned is 0. If t is 'S', the value returned is 9999999.0. The function is useful if you want to set a STOP based on the change in price. The parameter t is either 'L' for a Long Position, or 'S' for a Short Position. pt_setprice(p) Sets the price at which the next transaction will take place, where p is the price. Profit Test Phases - Advanced Use Only TAS runs the profit test in two phases. The first phase, called PLOT PHASE is when the script should compute the arrays to be tested during the next phase. This next phase is the TEST PHASE. This phase is entered for the data points of the ticker file. After all data points have been processed, the END PHASE indicator is set. Each 'phase' of the Profit Test process is indicated by a variable being equal to 1. The two phases are analogous to the steps you might run in Metastock to do the Profitability Test. First, you would plot an indicator, moving average, or custom formula. This is similar to the 'PLOT PHASE' in TAS. Next, you would run the Profit Tester specifying your Buy/Sell conditions. Metastock then applies your Buy/Sell signals to each plotted point on the graph, proceeding left to right until it reaches the last day loaded. This is the 'TEST PHASE' in TAS. When the TEST PHASE is entered with the last day of the ticker file, a variable, called 'END_PHASE' is set to 1. Testing this variable will allow you to print out the results for the Profit Test. Technical Analysis Scanner (TAS) Page 72 For each ticker, the script is entered once for the PLOT Phase, and then as many times as there are data points for the TEST Phase. If you use the PT_BUY, PT_SELL, PT_STOP, PT_PRICE functions, you will need to understand the different phases for the Profit Tester. However, if you use the BUY WHEN, SELL WHEN, STOP ... WHEN and PLOT forms of the Profit Test, you do not need to be concerned about the different Profit Tester phases, since the script generates the appropriate phase testing automatically. You should use the BUY, SELL and STOP WHEN statements to do your PROFIT TESTING. See RSIPT.TAS for an example. Technical Analysis Scanner (TAS) Page 73 GRAPH Functions The TAS GRAPH functions increase the power of TAS by making it possible to display the contents of any indicator, either builtin, or created by the user, in a graphical display. You can write a script that selects only those tickers with the conditions you are looking for, and when one of them is found, display a graph of the indicators and the stock price action. Up to 10 individual graphs with up to 10 indicators on each graph can be displayed at once with the GRAPH feature. Individual graphs can be assigned their own sizes relative to the other graphs on the screen, or each graph can be the same size as the other graphs. OPENGRAPH OPENGRAPH(numgraphs[,start,end]) This function prepares for numgraph graph windows to be displayed. The dates displayed are from quote start to quote number end. For example, to prepare to display 3 graphs of the last 50 days, you would say: OPENGRAPH(3,-50,0); The start and end values are optional, so you don't have to specify them. If they are not specified, the default is to display from the first to the last quote. SIZEGRAPH SIZEGRAPH(S1, S2,...Sn) where S1..Sn are the number of 'shares' of the display area each graph prepared by the OPENGRAPH function will get when shown. For example, as above, with 3 graphs to be displayed, if you want the first graph to have 2 times as much space as the second or third, you would say SIZEGRAPH(2,1,1); Note that there must be as many parameters to the SIZEGRAPH function as the number in the first parameter of the OPENGRAPH function (numgraphs above). Technical Analysis Scanner (TAS) Page 74 GRAPH GRAPH(a1,l1,a2,l2...,aN,lN) where a1 is the first array to be graphed, l1 is the legend (name to be displayed with) the graph of a1, a2 is the second array and l2 is the second legend. Each of the arrays and legends specified in the GRAPH command are graphed in the same window, one on top of the other. For example, to graph +DI, -DI and ADX on the same graph, you would say GRAPH(PDI(14),'+DI',MDI(14),'-DI',ADX(14),'ADX 14'); Simple as that. There is a special 'array' named '1' which represents the Price Bar Chart normally seen in charts. So, to plot the price bar chart, you could say GRAPH(1); DRAWLINE DRAWLINE(color,x1,y1,x2,y2,start,end) This function will draw a line from the point (x1,y1) to (x2,y2) starting at point start and ending at point end. The color parameter can be in the range from 0 (black) to 15 (white). Technical Analysis Scanner (TAS) Page 75 The following table lists the color codes that can be used with the DRAWLINE function. Color # Color Generated 0 BLACK 1 BLUE 2 GREEN 3 CYAN 4 RED 5 MAGENTA 6 BROWN 7 LIGHTGRAY 8 DARKGRAY 9 LIGHTBLUE 10 LIGHTGREEN 11 LIGHTCYAN 12 LIGHTRED 13 LIGHTMAGENTA 14 YELLOW 15 WHITE CLOSEGRAPH CLOSEGRAPH() The CLOSEGRAPH() function waits for you to hit any key. If you hit an ESC or CTRL-C the graphing (and the script) stop completely. Any other key will close the graph and go back to the regular TAS output display. GRAPH EXAMPLES Here is an example of a graph that shows how to draw a price graph with Bollinger Bands around it in the first (top) graph and the MACD indicator and its trigger in the bottom graph. Technical Analysis Scanner (TAS) Page 76 opengraph(2); graph(bband_top,bband_bot,1); graph(macd(),'Macd',macdtrigger(),'Trigger'); closegraph(); The next figure shows a graph created by TAS using the following GRAPH commands: opengraph(2); sizegraph(2,1); graph(1,'PRICE', bbandt(20,2),'BBAND TOP', bbandb(20,2),'BBAND BOT', mov(c,21,'e'),'21DAY EMA', mov(c,200,'e'),'200DAY EMA'); graph(rsi(14),'RSI 14'); { show RSI } drawline(3,0,20,0,20); drawline(3,0,80,0,80); closegraph(); The first statement above, opengraph(2), tells TAS to create space on the screen for 2 graph areas. The second statement, sizegraph(2,1), says to give the top graph 2 "shares" of space and the bottom graph 1 share of space. This effectively gives the top graph 2/3 of the screen and the bottom graph the remaining 1/3 of the screen. The third statement graph(1,'PRICE', bbandt(20,2),'BBAND TOP', bbandb(20,2),'BBAND BOT', mov(c,21,'e'),'21DAY EMA', mov(c,200,'e'),'200DAY EMA') defines the values to be graphed in the first (top) graph. The first value to graph is the "price bar chart" which has a special indicator name of "1". Then, two Bollinger Bands, top and bottom, are graphed . Finally, a 21 day Exponential Moving Average and a 200 day Exponential Moving Average are graphed. Each of these items to be graphed can be followed by a "legend" or title to be displayed on the graph in the color chosen for the line. The statement graph(rsi(14),'RSI 14') tells TAS to place a graph of Wilder's Relative Strength Index in the second (bottom) graph. The next two statements, Technical Analysis Scanner (TAS) Page 77 drawline(3,0,20,0,20); drawline(3,0,80,0,80); tell TAS to draw a line in blue from the left of the graph (just drawn) to the right of the graph at height 20 and 80. This is just adding the 20/80 lines to the RSI graph for ease of recognition of crossings to overbought/oversold conditions. Technical Analysis Scanner (TAS) Page 78 TAS "POUND" (#) Commands TAS "POUND" commands are used to control special script processing. They must begin with a "pound sign" ('#') in the first column of the line, and they must be completed on the same line. DO NOT USE A SEMI-COLON to terminate a POUND command, since they are not TAS script language statements, but are TAS run settings. You should not put comments at the end of a POUND command either. "POUND" commands are executed by TAS only one time during the life of the script, as contrasted with other TAS script statements which are executed once for every ticker. OUTPUT_FILE Command You can direct the output of a script to a file by placing an #OUTPUT_FILE command in the script file. The #OUTPUT_FILE command must start in the first column of the line. It should be followed by the output file name surrounded by single quotes. If you want to direct your output to a PRINTER, for example, LPT1, you can use the #OUTPUT_FILE command, #OUTPUT_FILE 'LPT1' For example, #OUTPUT_FILE 'select.lst' would place the output text of the script into the file 'select.lst'. Appending to Output File If you want to APPEND, or add to, the end of the output file, you can do so by placing a plus (+) character at the end of the output file name. From the example above, #OUTPUT_FILE 'select.lst+' would place the output of the script at the end of file "select.lst". This feature will be most useful if you are running several scripts in succession and want to place the output from different scripts into one output file. Technical Analysis Scanner (TAS) Page 79 Suppressing TAS Report Heading In addition, if you want to suppress the headings that TAS normally puts out on its reports, you can do this with the OUTPUT_FILE command by placing the letter "N" after the file name (preceded by a space). MAX_QUOTES Command You can use the #MAX_QUOTES command to limit the number of quotes read into a script. This value must be less than the MAXIMUM QUOTES you specified in the TAS Configuration Menu. If it is less than the TAS Configuration Menu MAXIMUM QUOTES, it will override the quote count to read for the script in which it is contained only. The format of the #MAX_QUOTES command is: #MAX_QUOTES nnn where "nnn" is the number of quotes to read into TAS when this script is processed. SCAN_DATE Command You can use the #SCAN_DATE command to define the time frame you want to process. You can specify a beginning date, an ending date or both. The SCAN_DATE command enables you to start loading quotes from a specific date (the start date) and to stop loading quotes after a specific date (the end date). The format of the #SCAN_DATE command is: #SCAN_DATE start_date end_date or #SCAN_DATE end_date Both start_date and end_date can be in the following format where yy is the year, mm is the month, and dd is the day : Technical Analysis Scanner (TAS) Page 80 yymmdd ,e.g. 910302 for March 2, 1991 'mm/dd/yy' mm/dd/yy Some examples of the use of #SCAN_DATE are: #SCAN_DATE 910102 0 will start loading data on Jan 2, 1991 and load up to the last day in the file. #SCAN_DATE 910102 910915 will start on Jan 2, 1991 and load up to Sept 15, 1991. If there is no quote in the file for the start_date, the first date prior to the start_date will be loaded. If there is no quote in the file for the end_date,the first date prior to the end_date will be used. Either the start_date or the end_date may be zero, in which case, it means to load from the beginning or the end of the file without regard to date, but taking into account the MAX_QUOTES range. PROFIT_TEST Command The #PROFIT_TEST command informs TAS of the type of profit test you want to run, whether you want to test "LONG", "SHORT" or "BOTH" long and short positions, and the amount of "money" you want your position to start with. This command must be placed in the front of the TAS script, prior to any statements which do not begin with a # sign. The format of the #PROFIT_TEST command is: #PROFIT_TEST type money where 'type' is either LONG, SHORT or BOTH (for a "long" position test or a "short" position test, or a test of both Long and Short positions) and "money" is the amount of money with which to start the test for each symbol. Technical Analysis Scanner (TAS) Page 81 INDEX Command The #INDEX command can be used to load an "index" data array, such as the SP500, DJIA or another stock. It tells TAS to access the ticker symbol contained in the command and place its CLOSING PRICES into a Pre-defined Data Array named "INDEX". The format of the INDEX Command is: #INDEX 'ticker' where 'ticker' is the TICKER SYMBOL of the Index quote file. For example, if you had the SP 500 quotes in a file with a ticker name of "SP500", and you wanted to load it as the INDEX array, you would say #INDEX 'SP500' Later in the script, you could reference the array by the name of INDEX. This command must be placed in the front of the TAS script, prior to any statements which do not begin with a # sign. It also should follow any #MAX_QUOTES statement that is in the script. INCLUDE Command The #INCLUDE command will "include" another file into the current script as if that file were part of the script . Once the included file is read into TAS, the original script is continued. You can include up to 8 levels of includes, that is, the included file can contain a #include and that file can contain one, etc., up to 8 levels. The format of the #include command is #INCLUDE filename where filename is the name of a file in the current directory. Technical Analysis Scanner (TAS) Page 82 TAS Script Examples Included with the TAS package are several sample .TAS script files. Check your directory after you install TAS to see the samples included. Putting Them Together If the script has the statements: todays_ma := mov(c,21,'E'); diff := CLOSE OF TODAY- todays_ma; if diff IS GREATER THAN 0 then writeln(TICKER, ' IS ABOVE 21 DAY EMA BY ',diff); else writeln(TICKER, ' IS BELOW 21 DAY EMA BY ',diff); The script will print out the ticker name followed by the message indicating whether the latest close is above or below the 21 day EMA, and by how much. In this particular example, let's take a closer look at what is going on. In the first line, todays_ma := mov(c,21,'E'); we are computing the 21 day Exponential Moving Average of the Closing Price Array. Once computed, we are assigning the latest value of this moving average to the "variable" named 'todays_ma'. You could call it anything you want, but giving it a name that reminds you of what it contains is useful. If you wanted to keep the 21-day EMA in its own array. You could declare the variable as follows (before using it the first time): big_ma_array : ARRAY; This tells TAS that "big_ma_array" is an array of values, not just one value. So, if you now said: big_ma_array := mov(c,21,'E'); the contents of big_ma_array would be ALL of the Moving Average values up to the latest day. To refer to the value of the 21 day EMA yesterday, we would write "big_ma_array[-1]" where the "[-1]" refers to the contents of the array "-1" days from now (in other words, one day ago). If you wanted to refer to the 21 day EMA 10 days ago, it would be "big_ma_array[-10]". If you wanted to refer to the latest day's 21 day EMA, it would be "big_ma_array[0]" Technical Analysis Scanner (TAS) Page 83 (zero days ago). The next statement in the example is: diff := c[0] - todays_ma; which assigns to the variable "diff" the value of the latest closing price, "c[0]", minus the latest 21 day EMA as computed and assigned to the variable "todays_ma" in the previous statement. New High/New Low Example The following script is contained in file "NHNL.TAS". Technical Analysis Scanner (TAS) Page 84 Script Contents { NHNL.TAS- This script example will show the 52 week high and low for each ticker. If the current day's high is equal to the highest high or the current low is equal to the lowest low, then we have a probable new high or new low. It might also be the case that today's high or low is just equal to the previous high or low. Just to make the script slightly more interesting, we will also compute the "percentage off from high", a frequently used metric seen in financial tables. } if first_ticker then begin writeln(' - CURRENT - - 52 WEEK - OFF'); writeln('TICKER HIGH LOW HIGH LOW HIGH'); end; high_value := HHV(h,52*5); { compute high over 52 weeks } low_value := LLV(L,52*5); { compute low over 52 weeks } off_high_value := ((high_value - c) / high_value) * 100; write(TICKER,' ',h,' ',l,' ',high_value,' ',low_value, '\t',INT(off_high_value),'%'); if (high_value <= h) then { today's high is new high } write(' New High '); if (low_value >= l) then { today's low is new low } write(' New Low '); write('\n'); { end the line with a 'newline'} Script Output - CURRENT - - 52 WEEK - OFF TICKER HIGH LOW HIGH LOW HIGH ABX 21.875 21.375 24.750 15.875 13% AAPL 28.000 26.000 50.375 26.000 47% New Low ARIX 1.062 0.938 5.625 0.875 81% BP% 12.500 11.125 14.500 6.000 17% CMNT 2.312 2.188 3.500 2.063 33% GR 32.125 31.875 57.500 29.500 44% SWZ 12.125 11.750 17.500 10.875 32% LA 11.625 10.375 50.375 9.750 77% MXTR 5.625 5.250 16.500 5.250 66% New Low PCG 22.375 22.000 23.500 18.750 4% TX 61.625 60.125 68.500 49.875 12% UAL 110.000 99.000 286.750 87.250 64% Technical Analysis Scanner (TAS) Page 85 TICKER Symbol Processing The following example shows how you could create a special script to notify you when certain stocks had reached prices you had set. This script is in "LIMIT.TAS". Script Contents { limit.tas This is an example of using a TAS script to watch your stocks. It checks the ticker symbol against one of several which you might (and I do) own. If the current close (shown as 'c[0]' is greater than the limit for profit or less than the stop loss, a message is generated. } stop_loss := 0; sell_profit := 0; if ticker = 'aapl' then if c > 47 then sell_profit := 1; else if c < 41 then stop_loss := 1; if ticker = 'gr' then if c > 43 then sell_profit := 1; else if c < 38 then stop_loss := 1; if ticker = 'la' then if c > 27 then sell_profit := 1; else if c < 10 then stop_loss := 1; if stop_loss = 1 then writeln(ticker, ' has reached your STOP LOSS limit. SELL'); if sell_profit = 1 then writeln(ticker, ' has reached your Profit target. SELL'); Technical Analysis Scanner (TAS) Page 86 Directional Movement Example The following script is contained in file "DM.TAS". NOTE : This script will only work with the REGISTERED VERSION of TAS. Script Contents #output_file 'dm.lst' { DM.TAS Wilder's Directional Movement Trading Example This script will indicate a BUY signal if the +DI(14) crosses above -DI(14) and ADXR > 25 a SELL signal if the -DI(14) crosses above +DI(14) and ADXR > 25 } { declare the +DI (Positive Directional Movement array} pdi_array : array; { declare the -DI (Negative Directional Movement array} mdi_array : array; pdi_array := pdi(14); { calculate +DI} mdi_array := mdi(14); { calculate -DI} adxr_14 := adxr(14); adx_14 = adx(14); dx_14 = dx(14); if first_ticker then writeln('TICKER ADXR DX ADX +DI -DI ACTION'); write(ticker,' ',int(adxr_14), int(dx_14), int(adx_14), int(pdi_array[0]), int(mdi_array[0])); action = ''; if (adxr_14 > 25) then { AVG DX Rate of Change > 25 } begin if (over(pdi_array,mdi_array) = 0) then action = '** BUY SIGNAL'; else Technical Analysis Scanner (TAS) Page 87 if (over(mdi_array,pdi_array) = 0) then action = '** SELL SIGNAL'; end; writeln(action); Script Output TICKER ADXR DX ADX +DI -DI ACTION AA 33 28 33 25 14 ALD 22 15 22 30 22 AXP 34 59 34 39 10 T 30 41 30 29 12 BS 26 42 26 32 13 BA 22 8 22 27 23 CHV 17 4 17 27 29 KO 27 49 27 32 11 DD 21 23 21 29 18 Modified "Binary Wave" The file "SELCT.TAS" contains a rather lengthy script which contains the logic for computing a 6 point "binary wave". The first 4 "points" of the wave are those described in the "MetaStock User's Manual" in Chapter 7, section 7.7.2 "Example Binary Waves". The final 2 points of the "binary wave" are included to show how you can extend the original example to compute additional indicators (Chaikin's Oscillator and Commodity Channel Index) which are used to further refine the selection. Since the file is large, it is not included in this documentation, but the file is included in the TAS package. Profit Test Example Using RSI(14) The TAS Script file 'RSIPT.TAS' shows a Profit Test using the 14-day RSI. It serves as a simple example of the kind of profit testing available with TAS. Script Contents (RSIPT.TAS) { Technical Analysis Scanner (TAS) Page 88 RSIPT.TAS RSI PROFIT TEST SCRIPT EXAMPLE This script will signal a SELL when the RSI(14) crosses under 'rsi_upper' and a BUY when RSI(14) crosses above 'rsi_lower'. } #PROFIT_TEST LONG 1000 { long positions with $1000} #MAX_QUOTES 300 { only read in 300 quotes } #OUTPUT_FILE 'RSIPT.LST' { assign output listing to rsipt.lst} RSI_VALUES : ARRAY; { array containing plotted points } RSI_UPPER := 75; { Upper range of RSI - point to SELL Change this if you want to test different value} RSI_LOWER := 50; { Lower range of RSI - point to BUY Change this if you want to test different value} PLOT BEGIN { This begins the "plot" of the RSI } RSI_VALUES := RSI(14); { COMPUTE THE RSI(14) PLOT } END; BUY WHEN RSI_VALUES[-1] < RSI_LOWER AND RSI_VALUES > RSI_LOWER; SELL WHEN RSI_VALUES[-1] > RSI_UPPER AND RSI_VALUES < RSI_UPPER; Script Output The following report shows the output of the Profit Tester for a single stock. Technical Analysis Scanner (TAS) Page 89 Technical Analysis Scanner (TAS 3.64) File Date : 05/08/90 Run Date : Wed May 29 22:28:00 1991 Script Name: RSIPT Ticker Name: T Amdahl (AMH) From 03/20/90 To 05/29/91 Initial Cash $ 1000.00. (Long Positions Only) Share Purchases use All Available Cash with NO Commissions |-----Current Trade-------| |-- Cumulative--| Date Action Shrs Price Points Cash Comm Profit Points Profit -------- ----- ----- -------- ------ ------ ----- ------- ------ - ------- 05/09/90 Buy 70 14.250 0.000 2 0 0 0.000 0 05/22/90 Sell 70 15.625 1.375 1096 0 96 1.375 96 06/12/90 Buy 69 15.750 0.000 10 0 0 1.375 96 07/18/90 Sell 69 18.250 2.500 1269 0 172 3.875 269 09/07/90 Buy 97 13.000 0.000 8 0 0 3.875 269 Summary for AMH |--Trades-----| |-Runs-| Percent |---Maximum--| Total % Tot Win Los Stp Win Los Win Los Profit Loss Commn Profit Gain Long 2 2 0 0 2 0 100% 0% 269 0 0 269 27% Short 0 0 0 0 0 0 0% 0% 0 0 0 0 0% Closed 2 2 0 0 2 0 100% 0% 269 0 0 269 27% Open 1 1 0 0 1 0 100% 0% 315 0 0 315 32% Total 3 3 0 0 2 0 100% 0% 315 0 0 584 58% Summary for ALL SYMBOLS |--Trades-----| |-Runs-| Percent |---Maximum--| Technical Analysis Scanner (TAS) Page 90 Total % Tot Win Los Stp Win Los Win Los Profit Loss Commn Profit Gain Long 2 2 0 0 2 0 100% 0% 269 0 0 269 27% Short 0 0 0 0 0 0 0% 0% 0 0 0 0 0% Closed 2 2 0 0 2 0 100% 0% 269 0 0 269 27% Open 1 1 0 0 1 0 100% 0% 315 0 0 315 32% Total 3 3 0 0 2 0 100% 0% 315 0 0 584 58% Technical Analysis Scanner (TAS) Page 91 TAS Error Message TAS has extensive error checking features that attempt to detect and isolate errors as close to the source as possible. The following section is a list of the error messages that can be exhibited by TAS. The Error Message list is in alphabetic sequence, so you can look up the message by the first letter of the first word of the message. Most messages have an error number associated with them as well. This number should be used when communicating the problem to FlexSoft. For each error message, there are three sections, The first section is the actual text of the message including an error number (Ennn) , the second section is the cause of the message, and the third section is the recommendation, or action to resolve the error. At the end of the list of error messages is a list of Diagnostic Actions. These are described in the error message recommendation as Action Dx, where the x is a diagnostic action number. A Diagnostic Action is a sequence of steps necessary to resolve the problem or to gather and provide enough information for resolution by FlexSoft Technical Support. Error Messages E72,'(', number value or variable expected. Cause: In trying to decipher an arithmetic expression, TAS found a sequence where it expected to find either an expression in parentheses, a number or a variable. It found nothing it could make sense of. Recommendation: Examine the line where the error was flagged and correct the mistake. E68,')' expected. Cause: In trying to decipher an arithmetic expression, TAS found a sequence that is missing a right parenthesis. Recommendation: Examine the line where the error was flagged and correct the Technical Analysis Scanner (TAS) Page 92 mistake. A Math Error (code ) has occurred while processing symbol in TAS Script File