Database Management FAQ’s

An unsorted, unqualified list of FAQ’s relating to anything and everything to do with database management.

The list is dynamic and subject to change without notice.

 

Q6 (a). What happens when my original (MS) data source adds, or deletes, a stock code or merges two codes together?
Do I have to take care of this myself?

A6.  Use the METASTOCK PLUGIN  http://www.amibroker.com/guide/h_extsources.html  to read the MS database directly (so you don’t need to re-import all the time).

Re: understanding categories.

Categories are NOT folders (like in Windows Explorer). The difference is fundamental. In the Explorer a file appears (usually) only once in the given
tree leaf. In the Workspace symbol tree a given symbol appears multiple times because it appears in every category leaf that it belongs to, even if this is the same symbol and it exists only as a single entity. One symbol belongs to MANY categories at the same time. For example AAPL (Apple Inc.) will belong to"Stocks" group category, "Nasdaq" market category, "Information" sector category, "Comp-Computer Mfg" industry category, and may also belong to several watch lists and favorites category ALL at the same time.That’s why ONE symbol will appear in many leaves of the symbol tree. Now if you delete the SYMBOL it will of course disappear from ALL categories because you have deleted the SYMBOL.

There are two types of categories:

1. with mutually exclusive membership: groups,markets, sectors/industries - it means that symbol MUST belong to ONE group, ONE market, and ONEsector/industry at a time - you can move the symbol from one group/market/sector/industry to another but you can not remove this assignment - create "Unassigned" group/market/sector/industry instead.
2. with free membership: watch lists/favorites/indexes - it means that a symbol may belong to ANY number (including zero) of watchlists (and to favorite/indexcategory too)In this case you can remove this assignment by Watch List -> RemoveWatch lists are covered in detail in the User’s Guide:
http://www.amibroker.com/guide/h_watchlist.html     (the same is available when you press F1 from AmiBroker)

Another thing: if you use "DELETE" button in Symbol->Categoriesit displays the warning:"This will delete selected symbols FROM THE DATABASE".Again: it will delete FROM THE DATABASE, not from the category.

Tomasz Janeczko - amibroker.com

Authors comments: As a rule of thumb, where data is accessed directly from an external source, WITHOUT a local (AmiBroker) database enabled, changes made to the database by the provider will be reflected at the AB user interface.

Where data is accessed from an external source, WITH a local (AmiBroker) database enabled, database changes will be at the discretion of the user. Depending on the access method, new symbols will be automatically added to the database e.g. when using the MS plug-in, and redundant symbols, or symbols that change, will remain in the database (with their data). The user has the option to merge changed symbols or delete old symbols (the symbol lists are stored in the local AmiBroker database, independently of the plug-in).

Where a local AmiBroker database is used as a standalone (data is updated via AmiQuote) the user has complete control over which symbols to add and delete etc (once again redundant symbols, and their data, will remain in the database unless manually deleted).

Q6 (b). How can I merge two symbols together after a name change?

A6 (b). Pick the symbol, that you want to retain in the database (master symbol), from the All symbols list and select Symbols >> Merge from the AB file menu. Click on the symbol, that you want to assimilate into the master, from the drop-down list in the Merge quotes window that opens, select from the options available (overwrite duplicate quotes, delete the slave symbol after assimilation or assign an alias name) and then click on OK.

 

Q5. Does anybody know how to check the number of stock symbols in a database?

A5. Hover the mouse pointer over the Data information section of the AmiBroker Status Bar (in the bottom right of the AB screen). A tool-tip will report on the database file name and path, the number of symbols in the database and the number of quotes in the current symbol.

 

Q4. Currently, my EOD data is supplied in Metastock format from an external supplier (JustData)…how can I setup to use it in AmiBroker?

It is stored in the following folders/directories on my pc:
C: - MyDatabases - Metastock -
ASX - 0
ASX - 1
ASX - A
ASX - B
ASX - C, etc, etc
LSE - 0
LSE - 1
LSE - A
LSE - B, etc, etc
World Indices

At the moment I trade multiple exchanges (ASX, LSE) as shown above.
To use this data within Amibroker, I am aware that I can use the Metastock Plug-in to recreate my databases in Amibroker, as per this link http://www.amibroker.com/guide/h_extsources.html

However, when it comes to creating the equivalent databases in Amibroker, how would others recommend I create them?

For example, would I need a different Amibroker Database for:
1. each current folder (as listed above),
2. 1 for all the ASX data, 1 for all the LSE data, etc
3. 1 database which captures ALL my data (LSE, ASX & Indices)?

If option 3 is suitable, then how would I distinguish in Amibroker which exchange a security belongs to (LSE or ASX)?

A4. Authors comments - AmiBroker doesn’t provide for easy ways to reference symbols that are in one database from within another, so with that restriction in mind it depends on how you want to use the data. If you are going to cross reference World indices to local or international markets, then you would be better off merging them into one database. This takes some work, so if you are not going to do inter-market analysis it is a matter of personal choice whether the benefits are worth the effort.

From an organizational point of view, international exchanges can be ‘managed’ at the Market, Group or Watch list level (refer to Users’ Knowledge Base >> Setup A Custom Database for assistance with organizing Categories within AmiBroker).

Adapting some of the basic procedures outlined in that tutorial you can either:

1) Create a new local AmiBroker database and use the Metastock Wizard to import the symbols into Watch lists, folder by folder, and then assign them to Categories from there (with the help of categoryAddSymbol).

2) Create a new database and access the symbols using the Metastock plug-in (this requires nominating the folders that will be referenced by selecting them in the File >> Database settings >> Configure window). From there you will need to import Watch lists, that correspond to the Metastock folders, and then assign them to Categories (using categoryAddSymbol once again).

Method 1 will create a static database, for historical back-testing only, and method 2 will create a database that dynamically updates to the Metastock database.

Both database types rely on organizing the symbols into Categories, after the initial setup, if you want to replicate Metastock folders.

 

Q3. I have a big database with intraday 1-sec quotes. How can I change the quotes interval in the database to shrink the database size ?

A3. You can use Exploration to generate any desired interval (set Periodicity in AA) and export to ASCII then import back to a new database.
http://www.amibroker.com/kb/2006/03/04/how-to-export-quotations-from-amibroker-to-csv-file/

Tomasz Janeczko - amibroker.com

AmiBrokerYahooGroup message #116071 "How can I convert AmiBroker tick database to AmiBroker 1-minute dat" http://finance.groups.yahoo.com/group/amibroker/message/116071

 

Q2. Is it possible to enter negative values via the Quote Editor?

A2. There is special flag $ALLOWNEG 1 that you can use to allow negative data during ASCII import.

Tomasz Janeczko - amibroker.com

AmiBrokerYahooGroup  #116322 "How to enter negative values in quote editor?"  http://finance.groups.yahoo.com/group/amibroker/message/116322

 

Q1. Is it possible to import tick data with the Wizard in AB?

A1. Tick mode _is_ supported by the wizard.
You just need to add $TICKMODE 1 in the "Additional Commands" field in the wizard and use "Close" for Last tick price and "Volume" for last tick size.

Tomasz Janeczko - amibroker.com

AmiBrokerYahooGroup message #116178  "Import TickData"  http://finance.groups.yahoo.com/group/amibroker/message/116178

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Statistics Resources For Traders

An unqualified, unordered, list of statistical resources that have relevance to trading.

The list is dynamic and subject to change without notice.

NOTE - SOME OF THE LINKS CONTAIN COMMERCIAL REFERENCES, OR LINK TO COMMERCIAL SITES.

THE AUTHOR HAS NO COMMERCIAL AFFILIATIONS OF ANY KIND AND RECEIVES NO GRATUITIES, OR BENEFITS, FROM ANY COMMERCIAL ORGANIZATION OR INDIVIDUAL INVOLVED IN COMMERCIAL ACTIVITIES, NOR IS HE PERSONALLY ENGAGED IN ANY COMMERCIAL UNDERTAKINGS, RELATED TO TRADING, IN ANY WAY.

THE LINKS ARE PROVIDED AS A RESOURCE AND FOR EDUCATIONAL PURPOSES ONLY. THEY ARE NOT A RECOMMENDATION, ON THE PART OF THE AUTHOR, NOR DO THEY CONSTITUTE INVESTMENT ADVICE AND SHOULD NOT BE CONSTRUED AS SUCH.

MISCELLANEOUS ARTICLES

1. Link to a short introductory article on the pitfalls of Neural Networking "A Little Knowledge Can Be A Dangerous Thing" by Dr. Halbert White: http://www.secondmoment.org/articles/ann.php

2. Link to a short introductory article on over-fitting data "Reality Check for Data Mining" by Dr. Halbert White: http://www.secondmoment.org/articles/datamining.php

3. Link to a short introductory article on managing missing data "The Curse of the Missing Data" by Yong Kim: http://www.secondmoment.org/articles/missingdata.php

4. Link to a dictionary level definition of the statistical P-value: http://en.wikipedia.org/wiki/P-value

5. Link to the Home Page of the The American Finance Association (AFA): the premier academic organization devoted to the study and promotion of knowledge about financial economics:  http://www.afajof.org/default.asp

Publishers of the Journal of Finance:

  •           search or browse back issues,
  •           free to students,
  •           reasonably priced for others,
  •           registration by international visitors accepted.

6. Link to an overview of Technical Analysis: http://en.wikipedia.org/wiki/Technical_analysis

7. Link to a short, mathematically orientated, article on trend analysis (includes links to regression and least squares methodology):  http://en.wikipedia.org/wiki/Trend_estimation

 

 BOOKS

DRAFT - SUBJECT TO CHANGE - IT IS POSSIBLE THAT REVIEWS WILL BE ADDED AT SOME TIME IN THE FUTURE.

 

1) Aronson - Professor David R, "Evidence-Based Technical Analysis", John Wiley & Sons Inc, 2007.

http://www.amazon.com/Evidence-Based-Technical-Analysis-Scientific-Statistical/dp/0470008741/ref=pd_sim_b_img_4

Link to Professor Aronson’s Home Page: http://www.evidencebasedta.com/   

Professor Aronson has a long term interest in applying "data mining and non-linear predictive modelling to the development of systematic trading methods".

His web-site includes links to two downloadable PDF’s:

  •           Monte Carlo Permutation Evaluation of Trading Systems
  •           Reader Questions & Answers

(Thanks to Whitney Broach who first introduced the author to Aronson’s work via the AmiBrokerYahooGroup).

 

2) Bandy - Doctor Howard B,"Quantitative Trading Systems", Blue Owl Press, 2007.

Link to Doctor Bandy’s home page: http://www.quantitativetradingsystems.com/index.html

 

3) Bernstein - Peter L, "Against The Gods", John Wiley & Sons Inc, 1998.

http://www.amazon.com/Against-Gods-Remarkable-Story-Risk/dp/0471295639/ref=pd_sim_b_img_1

 

4) Katz - Jeffy Owen and McCormack - Donna L, " The Encyclopedia of Trading Strategies", McGraw-Hill, 2000.

http://www.amazon.com/Encyclopedia-Trading-Strategies-Jeffrey-Owen/dp/0070580995/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202289418&sr=1-1

 

5) Kaufman - Perry J, "New Trading Systems and Methods", John Wiley & Sons, Inc, 2005.

An intermediate level reference book that is up to the mark with the latest trading techniques. It isn’t a book specifically on ’statistics for traders’ but it does  include analysis, underpinned by sound logic and quantitative methodologies, on a wide range of trading related subjects.

http://www.amazon.com/New-Trading-Systems-Methods-Wiley/dp/047126847X/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202293686&sr=1-1

 

6) Kennedy - Peter, "A Guide To Econometrics",  T. J. Press Ltd, 1992.

http://www.amazon.com/Guide-Econometrics-5th-Peter-Kennedy/dp/026261183X/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202292822&sr=1-1

 

7) Kestner - Lars N, "Quantitative Trading Strategies", McGraw-Hill, 2003.

http://www.amazon.com/Quantitative-Trading-Strategies-Irwin-Traders/dp/0071412395/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202292735&sr=1-1

 

8a) Pardo - Robert, "Design, Testing, and Optimization of Trading Systems", John Wiley & Sons, Inc, 1992.

http://www.amazon.com/Design-Testing-Optimization-Trading-Systems/dp/0471554464/ref=pd_bxgy_b_text_b

 

8b) Pardo - Robert, "The Evaluation and Optimization of Trading Strategies", John Wiley & Sons, Inc, 2008?

http://www.amazon.com/Evaluation-Optimization-Trading-Strategies-Wiley/dp/0470128011/ref=pd_sim_b_img_16

Link to Bob Pardo’s Home Page: http://www.pardocapital.com/

 

9) Stridsman - Thomas, "Trading Systems That Work", McGraw-Hill, 2001.

http://www.amazon.com/Trading-Systems-That-Work-Evaluating/dp/007135980X/ref=pd_sim_b_img_1

 

10) Taleb - Nassim Nicholas, "Fooled By Randomness", Random House, 2005.

 http://www.amazon.com/Fooled-Randomness-Hidden-Chance-Markets/dp/0812975219/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202292553&sr=1-1

 

 

11b)  Vince - Ralph, "The Mathematics Of Money Management: Risk Analysis Techniques For Traders", John Wiley & Sons, Inc, 1992.

 

http://www.amazon.com/Mathematics-Money-Management-Analysis-Techniques/dp/0471547387/ref=sr_1_5?ie=UTF8&s=books&qid=1207524559&sr=1-5

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.33 out of 5)
Loading ... Loading ...

Setup A Custom Database (v3)

OBJECTIVE

The objective for this tutorial is to setup an example database, including grouping and sector classification. Some basic database management skills are demonstrated and then built on in a later Users’ Knowledge Base (UKB) article: Setup A Custom Database - Nasdaq

SPECIFICATION

  • - AmiBroker: Standard v4.9
  • - Amiquote: v1.94 registered
  • - Time Frame: Daily
  • - Data Source: Yahoo
  • - Data Type: US Stocks
  • - OS: Windows XP (Home)
  • - Software: Microsoft Office XP Professional 2002
  • - Browser: Internet Explorer v7.0

PRE-REQUISITES

It is assumed that readers are familiar with the preceding articles in the UKB >> Database Management sub-category and also the AmiBroker Help >> Tutorial >> Database Management section. 

Note: To see articles in their order of precedence it is necessary to go the the UKB Homepage and browse the Table Of Contents. In all other places, including RSS feeds, UKB searches and category filings, the posts are sorted by the publication date, which is often the reverse of the order of precedence.

INTRODUCTION

AmiBroker is a flexible program, that, in many areas, allows owners to use it according to their personal preferences. This is nowhere more evident than when sourcing data. Data can be obtained from providers, who manage the classification and categorization of stocks for their subscribers, or, for those who want to ‘do their own thing’, custom databases can be setup using alternative or unique categories.

There is no set nomenclature, or structure, for categorizing database constituents, other than the limits set by the program and by the way in which the markets work:

  • - Markets, Groups, Sectors and Industries  are major, market orientated, categories.
  • - Watchlists and Favorites are minor, personally orientated, categories.
  • - Indexes is a market orientated category grouped with the personals. 
  • - All categories can contain sub-categories except for Favorites and Indexes.
  • - Sub-categories under the major categories are mutually exclusive i.e symbols can only belong to one sub-category at a time.
  • - When symbols are re-classified within a major category they are effectively moved from one sub-category to another.
  • - Watch list sub-categories are not mutually exclusive i.e. symbols can belong to more than one sub-category.
  • - Sub-categories only go down one level, except for Sectors, that goes down two i.e. Sectors > Industries.
  • - Unclassified (Unassigned, Undefined) should be used for symbols that don’t fit neatly into a defined sub-category.  
  • - When symbols are assigned to two or more sub-categories the most recent operation will take precedence.
  • - Only sub-categories that contain symbols will be visible, as a folder, in the Workspace Symbols List. 

This example imports a list of the Dow Jones Industrial Average (^DJI) members and ‘divides’ it into some arbitrary groupings, to demonstrate the principles of categorization.

Note: The database comprises 32 symbols, some of which are redundant i.e. there is no data available for that symbol (redundant symbols have been included to demonstrate a point). It has been broken into two groups (Group A and Group B) and 6 sectors (DJI 0-5) containing five symbols each.  A redundant symbol has been added to the last two sectors (4&5).

CREATE A NEW DATABASE.

The first step in the process is to create a new database.

Sector and industry classifications are put in place when a database is created, so it is necessary to think about the required classifications before hand.

To create a database without classifications:

  • 1) Make a backup copy of the original broker.industries and broker.sectors files in the C:/Program Files/AmiBroker folder (or the equivalent) then delete the original versions.
  • 2) Download the resetindustries.txt and resetsectors.txt files attached to this post and save them in the C:/Program Files/AmiBroker folder to replace the original versions (rename them as broker.sectors and broker.industries).

Note: The files can be opened and read in a text editing program like Notepad.

3) Create a new database called Data_CustomExample using the default EOD settings.

CD101

When the database is created the Sectors and Industries sub-categories will automatically be set to the broker file specifications i.e. in this example the first sub-category in Sectors and Industries will become Unclassified and the remainder will be set to the defaults i.e. Sector 1 - 63 and Industry 1 - 255 (this removes any redundant settings, for those categories, from the Symbol >> Categories or Symbol >> Organize assignments windows).

Note: Redundant titles can be retained in the Categories or Organize assignments lists from database to database. In practice they do not have any adverse effect on the current database. In this example, the Sectors and Industries sub-categories have been reset to the defaults so that readers, who are following the example, will achieve exactly the same outcome as shown.  Normally the broker files don’t need to include the default names; the end result, in the Workspace Symbols Tree, would have been exactly the same if the broker files had listed Unclassified as the sole sub-category.

CD012

The Markets and Groups categories are not established when the database is created and they need to be set manually (if they are not reset the defaults will automatically be used, including any redundant sub-categories that remain from the previous database).

Note: When symbols are first imported into a new database they are entered under the first sub-category in each category by default (the exception is Groups that defaults to Group 255).

4) Go to Symbols >> Categories >> Markets/Groups and Edit the first name in the list as required then click on OK to save the changes.

CD102

For this example the Markets default needs to be NYSE and the Groups first sub-category needs to be Unclassified. 

CD103

Once the Markets and Groups have be named symbols can be imported into the database.

In this case a list of symbols, in Comma Separated Values (CSV) format, will be entered into the database using the Import Wizard.

Note: The lists used in this example can be downloaded, in Excel format, from the Attached Files section at the end of this post.  To create text files, suitable for importing into watchlists, copy the symbols from the relevant Excel column and paste them into a text editor, like NotePad.

To import from a CSV file using the Wizard:

1) Before importing symbol lists check the source file:

  • - If the file is in Excel format Save it As a CSV file before proceeding.
  • - It should contain only one Worksheet so Delete any additional Sheets.
  • - Copy any columns that are constructed from underlying formulas and Paste special as Values to stabilize the  data.
  • - Remove any extraneous material (Delete any notes or comments, other than the title row, and also any redundant columns).
  • - Save the modified CSV file locally, using a meaningful name that associates the contents with an Industry sub-category.

Note: The ASCII Import Wizard and watch list importation use different formats. ASCII import allows for importing data to several fields, including the fullname, while watch lists are limited to ticker lists only. As a rule of thumb ASCII import should be used for global importing, and attribution of information values, while watch lists importation should be used to manage categorization i.e. move symbols from one category to another.

WARNING: THE IMPORT PROCESS WILL STRIP ANY ADDITIONAL  WORKSHEETS FROM THE FILE IF THEY ARE NOT MANUALLY REMOVED FIRST.

  • 2) Open the Import Wizard using the File > Import Wizard command from the AmiBroker menu bar.
  • 3) Click on Pick files.

CD014

4) Select the file to be imported from the file browser window that pops up and click on Open.

CD104

The selected file will be listed in the Wizard’s information pane.

 CD030

5) Click on Next >.

The Define Fields window will open with a ‘preview’ of the file format in the Data file sample pane.

Note: In this example the file has a single header row (title), the first data column contains the Symbol (Ticker) and the second column contains the Name (Fullname). The data columns are separated by a comma and there is no quotation data included.

CD105

6) Define the fields according to the file format:

  • - use the drop-down menus to set Column 1 to Ticker, Column 2 to Fullname and the remaining columns to Skip (ignore) anything else,
  • - set the Separator to Comma(,),
  • - pick Unclassified from the Group drop-down menu,
  • - skip the first line (title row) by entering 1 into the Skip first: input box,
  • - check Log errors (optional),
  • - check Automatically add new symbols (all of the symbols are new to the database and need to be added),
  • - check No quotation data (the list does not contain any quotation data as only Tickers and Fullnames are to be imported).

When the settings are correct click on Next > and the Additional Settings window will open.

CD032

  • 7) For this example there is no need to save the import format. Click on Finish to complete the symbol/information importation.
  • 8) Save the database using the File >> Save Database command from the menu bar.

Note: It isn’t essential to save at this stage but it is a good precaution to take before continuing on.

All of the symbols are arranged in one market (NYSE), and they are Unclassified at the Group/Sector/Industry level, as expected.

CD107

This establishes Data_CustomExample as a global DJI database.

From there it can be categorized according to personal preference.

CATEGORIZE THE DATABASE CONSTITUENTS

Setup Group Assignments

Some planning is also required when assigning symbols to groups as the sub-groups need to be unique and the order in which the assignments are made can affect the outcome.

For this example the ^DJI database will be separated into Group A and Group B listings (once again this is for demonstration purposes only and it has no practical application in the ‘real’ trading world).

To assign symbols to Groups:

1) Enter a name for the groups, in the order required, and click on O.K.

Note: The order is permanent i.e. sub-categories will not be alphabetically sorted in the Workspace window.

CD106

2) Import the A and B list symbols using the Wizard.

CD109

Pick Group A from the Group drop-down menu to assign the symbols to the relevant group.

CD136

Note: There is no need to check Automatically add new symbols since the groups are sub-sets of the global database (there are no new symbols since all the symbols in the group lists were already imported at the market level) .

Repeat the import procedure using the Group B file.

The Group assignments have now been installed (all of the symbols have been moved from Unclassified to the relevant group folder and the Unclassified group folder is empty).

CD110

Setup Industry and Sector Assignments.

Setting up the sectors and industries is a little more complicated and requires the use of an AFL formula.

The formula does the work of assigning the symbols to sectors but before it can be used some preparation is required:

  • - the Sector and Industry sub-categories need to be named,
  • - the watch lists need to be named to correspond to the Industry names (this is optional but it is a good practice to adopt to make sure that symbols end up in the right place).
  • - downloaded lists, in CSV or Excel format, need to be converted into a watch list compliant format and imported into the database (once again it is recommended that the files are named to match the industry names),
  • - price data needs to be imported  (AFL formulas will not work with symbols that do not contain quotes). 

Note: A handy tip, that the author picked up from Richard Dale of Norgate Investor Serices, is to append the sub-category number to the title e.g. when renaming List 0 to indicate that the folder contains DJIA components use the title DJIA 0 or DJIA (0) etc (once again this helps to ensure that symbols end up in the right place after a hard day at the office).

To name sector, industry and watchlist sub-categories:

1) Name the Watch lists so that they correspond to the Industry sub-category names.

Note: Start at the head of the list and do not leave any unnamed sub-categories in between the first and last ‘named’ item.

CD113

2) Repeat the exercise for the Sectors sub-categories.

CD118

3) As there is no information available on industry classifications, for this database,  name the Industries in exactly the same way (this will establish a one to one relationship between the Sectors and the Industries).

CD117

After the Sectors and Industries have been named the Sector that corresponds to the Industry will be listed in the Settings pane (click on any industry sub-category to see the associated sector).

The default Sector/Industry, in the Workspace Symbols Tree, has changed from Unclassified to Djia0.

CD137

Note: The smart way to setup the Sectors and Industries would have been to list them in the broker files, prior to initializing the database. The names were entered manually, in this example, for demonstration purposes only (refer to AmiBroker Help >> Contents >> Tutorials >> Database Management >> Understanding Categories >> How to define your own sectors and industries for assistance with setting up 1-1 ’sector to industry’ broker files).

To prepare a watch list compliant file from a spreadsheet symbol list:

  • 1) Select the column, to be copied, by clicking on the Column Title e.g. "A".
  • 2) Right click inside the selected area and Copy the symbol list using the context menu that opens.
  • 3) Open a text editor, like NotePad, position the cursor in the white space of a new "blank" page, right click and select Paste from the context menu that opens  (this will produce a plain text file with a single symbol per line - formats from the spreadsheet will be stripped from the text version).
  • 4) Edit out the title rows, or extraneous text, if any, and save the file locally.

CD131

To import symbol lists to the corresponding watch lists:

1) In the AmiBroker Workspace right click on any symbol, in any symbol list, and select Watch list >> import from the context menu that opens (a Select Watch list(s) window will open).

Note: The folders in AmiBroker’s Symbols Tree do not have a right click >> context menu, with the exception of watch list folders that contain symbols. The alternative path to the Watch list menu is  Symbol >> Watch list from the menu bar.

2) Select the Watch list that is going to receive the imports, select the Import/Export from /to: File radio button and click on OK (a file browser window will open).

CD120

3) Pick the text file that contains the ticker list to be imported and click on Open.

CD122

The watch list folder, containing the imported symbols, will automatically be established in the Workspace(repeat the import process for the remaining industry orientated watch lists).

CD123

Note: At this stage all symbols are still classified under the default Sector/Industry i.e. Djia0

It is commonplace for constituent lists to contain redundant symbols. In some cases the symbol has been changed and in others the company has ceased to trade or has undergone restructuring of some kind. Symbols that contain no quotes will not be assigned to categories by AFL formulas so it is necessary to download some data to the database to give the assignment code something to work with.

Current data will download from Yahoo ‘orders of magnitude’ faster than historical data. Since only one quote is required, for AFL formulas to function, it makes good sense to use the Yahoo Current option for the download, especially when the procedure is applied to ‘working’ databases containing thousands of symbols.

To download temporary data:

  • 1) Open AmiQuote while AmiBroker is open with Data_CustomExample as the current database.
  • 2) Get the tickers from AmiBroker using the AmiQuote Tools menu and Automatically import data with Yahoo Current as the selected source. The status will be recorded as the download proceeds.

Note: AmiQuote does not show error messages, in current mode, for symbols that are redundant, or have no data to download.

CD125

The current data for the day will only be available on the Yahoo server for a limited time (it is reset to zero in time for the new trading day). In one trial, conducted by the author, current data, for the American market, ceased to be available from 4 AM Eastern Time (USA).

A quick check can be made to see if the current quotes are extant at the time that a download is required.

To check the availability of current quotes:

1) Enter a valid stock symbol in the Quotes input box, at any Yahoo! Finance page, and then click on Get  Quotes.

CD138

The Quotes Summary page will open.

2) Look at the Change report (if the current data is still on the server the change % will be shown).

CD061

Note: When the current data is ‘deleted’ from the server the Change % report, and other outputs in the quotes panel at Y!Finance, reset to zero or N/A (the time might vary from day to day or with different exchanges for the American market). For international markets allow approximately four hours before ‘the opening bell’ (the author only checked a limited number of international exchanges - readers should check their own exchange for themselves).

Once the global database contains all of the required symbols, complete with data, the following AFL formula can be used to add symbols to a nominated industry, watch list by watch list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*X_CategoryAddSymbols*/  
   
/*Assigns tickers to Industries, according to Watchlist membership,   
on a one to one basis i.e. tickers in Watchlist 0 are assigned to Industry 0 etc.*/  
   
Filter = 1;  
   
for(W = 0; W < 63; W++)//"W", the Watchlist number, is limited to 63 for v4.9 and below.  
{  
&#160;&#160; if(InWatchList(W))  
&#160;&#160;&#160;&#160;&#160; {   
&#160;&#160;&#160;&#160;&#160;&#160; CategoryAddSymbol("",categoryIndustry,W);    
&#160;&#160;&#160;&#160;&#160; }  
}  
AddColumn(Close,"Close",1.2);

To use watch list membership to assign symbols to industry groups:

1) Run an exploration using the X_CategoryAddSymbols formula, with all symbols selected and the Range set to n last days = 1.

CD139

Note: AddColumn(Close), in the formula, serves no practical purpose, in terms of assigning the symbols to the industry sub-categories; it is only there to allow ‘Explorer’ to run.

Sectors and Industry classifications are automatically assigned as the formula is processed.

CD128

Note: SBC and HWP are not assigned because they do not contain data (’no quotes’ symbols remain ‘behind’ in the default industry folder i.e. Djia0, while all valid symbols are ‘moved’ to their nominated industry folder).

CD140

2) Manually check and repair or delete ‘no quotes’ symbols from the database.

Note: The quotes status, for databases containing only the current days data, can be seen in chart window for the selected symbol.

CD141

When the database quality has been confirmed, historical data can be downloaded to create a ‘working’ database.

Note: To download historical data; open Amiquote, get the tickers from AmiBroker  and then download with the date range set to capture the required history (the historical download will overwrite the temporary current values).

POST CREATION FIXES

After a database is created it sometimes becomes necessary to make changes or ‘repair’ any errors that are found.

There are a lot of different situations that can arise and they often require a creative approach to find ways to work around them. As a rule of thumb; use ASCII import to add symbols to the database, so that the information values can be appended, use watch-lists to categorize symbols in bulk or Symbols >> Assignments Organizer to manually move small numbers of symbols around and for data acquisition; import new symbol lists into AmiQuote (open a plain text list in AmiQuote as a .tls file) then download data for the new symbols and push it into the database, using the Automatic import checkbox in AmiQuote, (this approach allows a match-up between the imported date range and the existing range of the database).

One example from this database.

MSFT and  INTC are Nasdaq listings that are in the NYSE Market folder.

To move symbols from one market to another ‘after the event’:

  • 1) Import a ticker list of symbols to be moved into a ‘vacant’ Watch list folder e.g in this example List 6 is used since the first six Watch lists (0-5) still contain the sector component lists.
  • 2) Run an exploration using the following AFL formula (an AFL version is attached in the Attached Files section at the end of this post).

CD142

After categorization of the database is complete any redundant Watch lists can be emptied.

To empty redundant Watch lists:

  • 1) Right click on the Watch list folder.
  • 2) Select Erase (make empty) from the context menu that opens.
  • 3) Nominate the Watch list in the Select watch list(s) window that opens.

CD143

The symbols will be removed from the Watch list, but not the database.

Note: Empty Watch list folders will not be present in the Workspace Symbols Tree next time the database is opened.

CONCLUSION

That concludes this tutorial that demonstrates some basic database management procedures.

The method chosen is only one of several ways of achieving the same, or similar, outcomes e.g. the procedure could be described as a top-down approach but the bottom-up path, where the global database is compiled by importing Watch lists via the Import Wizard, could just as easily have been used.

It isn’t necessarily the best possible way to go about it and users should experiment for themselves by mixing and matching the various data management tools available.

The base method will be used as a template, for a subsequent post, that will construct a ‘working’ Nasdaq Composite database (some slightly more advanced points, that expand on some of the key concepts introduced so far, will be detailed there).

APPENDIX

Logic for X_categoryAddSymbols

Filter = 1;

Passes all symbols for processing.

for(W = 0; W < 63; W++)

Is a form of counter (counters are standard fare in programming languages).

It comprises three statements:

  • W = 0 assigns the number 0 to the variable W as the starting value,
  • W < 63 sets an upper limit to the count,
  • and W++ adds one to the count after the  following statements are executed.

if(InWatchList(W))

Places a condition on the statement to be executed i.e. the expression must be true for the following to be applied.

  • {
  • CategoryAddSymbol("",categoryIndustry,W);
    }

The statement to be executed, (more than one statement could be included within the curly brackets to form a compound statement).

AddColumn(Close,"Close",1.2);

Serves no purpose in assigning symbols to categories. It is required to allow the exploration to process the code.

More often than not, in example code, "i" is used as the variable in a counter. It has been ‘borrowed’ from mathematics where, by convention, "i" represents the index of summation in Summation Notation.

The ‘counter’ looping, used in X_categoryAddSymbols, is analogous to ‘walking through’ an index of the variables, when the execution of the code is considered as a sequence of steps.

Note: for this example the upper limit for the count was set to 63, which is the maximum number of Watch lists available in AB v4.9.

(INDEX OF) THE VALUE OF THE VARIABLE VARIABLE < LIMIT IF THE CONDITION IS ALSO TRUE EXECUTE THE STATEMENT ADD 1 TO THE VARIABLE (LOOP BACK TO THE START OF THE CODE)
W = O TRUE The symbol is in Watch list 1 (repeat for all symbols) Add the symbol to Industry 1 W = 0 +1 (enter the new value to the start of the next line)
W = 1 TRUE The symbol is in Watch list 2 (repeat for all symbols) Add the symbol to Industry 2 W = 1 + 1 (enter the new value to the start of the next line)
W = 2 TRUE The symbol is in Watch list 3 (repeat for all symbols) Add the symbol to Industry 3 W = 2 + 1 (enter the new value to the start of the next line)
etc        
         
         
         
         
W = LIMIT FALSE Exit the loop and move on to the next sequence in the code (if any).    

The processor walks from line to line repeating the code ‘module’ 63 times until the loop is exited ‘on the count’.

Code extension for X_categoryAddSymbols

Building on the basic module X_categoryAddSymbols v1 adds Watch list counting to the start of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*X_CategoryAddSymbols v1*/  
//Assigns tickers to Industries, according to Watchlist membership, on a one   
//to one basis i.e. tickers in Watchlist 0 are assigned to Industry 0 etc.    
//Adds auto Watch list count to X_CategoryAddSymbols v0    
//tested OK on AB v4.9  
&#160;  
Filter = 1;  
Count = 0;  
&#160;  
for(i = 0; i < 63; i++)//"W", the Watchlist number, is limited to 63 for v4.9 and below.  
&#160;&#160;&#160; if(StrLeft(CategoryGetName(categoryWatchlist,i),4) != "List")  
&#160;&#160;&#160; {   
&#160;&#160;&#160; Count = Count + 1;    
&#160;&#160;&#160; }  
&#160;  
for(W = 0; W < Count; W++)  
&#160;&#160;&#160; if(InWatchList(W))  
&#160;&#160;&#160; {   
&#160;&#160;&#160; CategoryAddSymbol("",categoryIndustry,W);    
&#160;&#160;&#160; }  
&#160;  
AddColumn(Close,"Close",1.2);

 

Code Extension 2 for X_categoryAddSymbols

Adds a Watch list report to the Exploration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*X_CategoryAddSymbols v2*/  
//Assigns tickers to Industries, according to Watchlist membership, on a one   
//to one basis i.e. tickers in Watchlist 0 are assigned to Industry 0 etc.    
//Adds an Exploration report to X_CategoryAddSymbols v1    
//Tested OK on AB v4.9  
&#160;  
Filter = 1;   
Count = 0;  
&#160;  
for(i = 0; i < 63; i++)//"W", the Watchlist number, is limited to 63 for v4.9 and below.   
&#160;&#160; {    
&#160;&#160;&#160; if(StrLeft(CategoryGetName(categoryWatchlist,i),4) != "List")    
&#160;&#160;&#160;&#160;&#160; {    
&#160;&#160;&#160;&#160;&#160;&#160; Count = Count + 1;    
&#160;&#160;&#160;&#160;&#160; }    
&#160;&#160; }  
&#160;  
for(W = 0; W < Count; W++)   
&#160;&#160; {    
&#160;&#160;&#160; WLName = CategoryGetName(categoryWatchlist,W);    
&#160;&#160;&#160; Ticker = WriteIf(InWatchList(W),Name(),"");    
&#160;&#160;&#160; AddTextColumn(Ticker,WLName);  
&#160;&#160;&#160;&#160;&#160; if(InWatchList(W))   
&#160;&#160;&#160;&#160;&#160; {    
&#160;&#160;&#160;&#160;&#160; CategoryAddSymbol("",categoryIndustry,W);    
&#160;&#160;&#160;&#160;&#160; }    
&#160;&#160; }

Use the Exploration Results window to cross check the symbols that have been assigned to Sectors/Industries, against the Watch lists, or export the results to a Comma Separated Values (CSV) file for saving or printing.

CD144

ATTACHED FILES:

  • broker reset files: resetindustries.txt and resetsectors.txt
  • broker files: brokerindustries.txt and  brokersectors.txt
  • Excel file used to create broker reset templates: resetcategories.xls
  • DJI file with nominal groups and industries included: dji.xls
  • AFL formula for Industry assignment: x_categoryaddsymbols.afl
  • AFL formula for Market assignment (manual version): x_categoryaddsymbols3.afl
  • AFL formula for Industry assignment updated with auto Watch list count: x_categoryaddsymbols-v1.afl
  • AFL formula for Industry assignment updated with Watch list reporting: x_categoryaddsymbols-v2.afl
  • Click on the link to browse spreadsheet files on line, or, Save As to download an editable version (requires Excel to edit or Excel Viewer to read).
  • Click on the link to browse text files on line, or, right click and Save Target As to download an editable version (requires NotePad or similar).
  • To download .afl files; right click on the link  and Save Target As ‘filename’ at Program Files/AmiBroker/Formulas/Custom to access them as formulas in the AmiBroker Charts list.

 

  •  Version 1 - Oct6/2007 - updated from a draft, added formula for ‘manual’ assignment to markets, uploaded afl files
  • Version 2 - Oct10/2007 - added an Appendix containing formula logic and a new version of the code
  • Version 3 - Oct17/2007 - added categoryAddSymbols v2
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Backfill Exploration for Real-Time data

Backfilling data can be done in many ways, and different methods may be needed for different data providers. The method shown below was developed for eSignal data. If you use another data provider, you may need to modify the code and the procedure.

When backfilling data, you should confirm that data are backfilled properly and have some indication regarding the presence of data holes. As pointed out in Data Holes in Real-Time Trading, to be able to detect holes, you need a perfect data array against which to compare the data. Since AmiBroker doesn’t have such a data array, the method presented here uses the QQQQ as a reference ticker. Turn ON and set Backtester Settings -> General -> Pad and align all data to reference symbol -> QQQQ. To have all tickers backfilled, you should also turn ON Wait for Backfill(RT only). To speed up real-time backfills you may want to display only a simple price chart, instead of complex code. Refreshing complex Indicators or Systems will slow down backfill. The following Exploration will Backfill all tickers in your Watchlist and report on it’s success:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
SN = Status("StockNum"); 
DT = DateTime(); 
DN = DateNum(); 
NumBars = Cum(1); 
NewDay = DateNum() != Ref(DateNum(),-1); 
DayCount = Cum(Newday); 
HoleCount = Cum(V==0); 
Plot(C,"A filled Bar is Red",IIf(V==0,colorRed,colorBlack),styleBar); 
Title = "\nBACKFILL EXPLORATION"+"\n"+ 
" Stock: "+Name()+"\n"+ 
"Stock Number: "+NumToStr(SN,1.0,False)+"\n"+ 
" Time frame: "+Interval(2)+"\n"+ 
" First Date: "+NumToStr(DT[0],formatDateTime)+"\n"+ 
" Last Date: "+NumToStr(DT[BarCount-1],formatDateTime)+"\n"+ 
" Day Count: "+NumToStr(DayCount,1.0,False)+"\n"+ 
" Bar Count: "+NumToStr(BarCount,1.0,False)+"\n"+ 
" Hole Count: "+NumToStr(HoleCount,1.0,False); 
Filter=Status("LastBarInTest"); 
SetOption("NoDefaultColumns",False); 
AddColumn(HoleCount,"#Holes",1.0); 
AddColumn(SN,"Stock#",1.0); 
AddColumn(NumBars,"#Bars",1.0); 
AddColumn(DayCount,"#Days",1.0); 
AddColumn(DT[0],"From",formatDateTime); 
AddColumn(DT[BarCount-1],"To",formatDateTime);

When executed on a Watchlist, the above Exploration will backfill all stocks and produce the report shown below:

Edited by Al Venosa.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 3 out of 5)
Loading ... Loading ...

15 Day Performers Trading System

  • AmiBrokerYahooGroup message #116148
  • “Code Question: buy best performing ticker of last 15 days”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//Buy on Friday the ticker symbol with the best performance of the last 15 trading days.
//Sell 5 weeks later
//It calculates the PositionScore on the Close at a thursday then it enters a trade at the Open on a friday AND closes this trade on the Open on a thrursday at least 22 bars after entry,
//You will need the latest Version of Amibroker for this because of the break function.
//Ed Pottasch and Samantha 
 
SetBarsRequired(10000,10000); 
SetOption("MaxOpenPositions", 1 ); 
PositionSize = -100; 
SetTradeDelays(0,0,0,0); 
PositionScore = IIf( Ref(ROC(C,15),-1) > 0, Ref(ROC(C,15),-1), 0); 
 
procedure sell_proc(Buy,Sellday){ 
 
global Sell; 
global SellPrice; 
SellPrice = 0; 
Sell = 0; 
 
// sell delay in bars 
selldelay = 22; 
 
for (i = 1; i < BarCount; i++) 
{ 
   if (Buy[ i ]) 
   { 
      for (j = i + selldelay; j < BarCount; j++)  
      { 
         if (Sellday[ j ]) 
         { 
            Sell[ j ] = 1; 
            i = j; 
            break; 
         } 
      } 
   } 
} 
} 
 
Buy = DayOfWeek() == 5; 
BuyPrice = O; 
 
sell_proc(Buy,DayOfWeek() == 4); 
SellPrice = O; 
 
SetChartOptions(0, chartShowDates); 
GraphXSpace = 5; 
Plot(C,"C",1,64); 
 
PlotShapes(IIf(Buy,shapeUpArrow,0),colorWhite, layer = 0, yposition = BuyPrice, offset = 0 );

The idea works. Backtesting, using the above code on, for instance, a stock list Nasdaq 100, will give positive results. The results get even better if you divide your money in smaller portions like for instance

SetBarsRequired(10000,10000);
SetOption(”MaxOpenPositions”, 10 );
PositionSize = -10;
SetTradeDelays(0,0,0,0);

However, since it is a long only system you will see that in a down market it will give bad results. So you can add additional constraints only to buy when the market is trending upwards, like:

  • Cf = Foreign(”!COMP”,”C”);
  • Buy = DayOfWeek() == 5 and Cf > MA(Cf,100);

Just adding some ideas. In an upmarket the system makes around 25% per year without slippage. But slippage for such a system will be very small to negligable and can easily be avoided. The idea needs to be fine tuned so it will make money in any market. Also 25% per year is too little in my opinion. Need systems > 60% before they get interesting in my opinion.

  • Trading idea by Samantha.
  • Code and comments by Ed Pottasch.

To meet and greet Ed and Samantha visit http://finance.groups.yahoo.com/group/amibroker/

ATTACHED FILES

15 Day Performers: b_15dayperformers.afl   (AFL formula file)

  • To download .afl files; right click on the link  and Save Target As ‘filename’ at Program Files/AmiBroker/Formulas/Custom to access them as formulas in the AmiBroker Charts list.
  • 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
    Loading ... Loading ...

    AFL Testing Databases

    Small databases, with a limited number of symbols and limited data, can be useful for solving complex problems or designing systems within AmiBroker. A small amount of data can be easier to use, for debugging code or proving strategies, than larger amounts. For AmiBroker users, Yahoo data is readily available for this purpose.

    In this tutorial new users are shown a simple method to create small quality controlled databases that are suitable for testing basic AFL functions and procedures.

    FORMULAS FEATURED: BarCount, BarIndex();

    INCLUDING: creating, copying, naming, deleting and backing up databases; managing databases from AmiBrokers? File commands or Windows Explorer; database naming conventions, creating small databases using AmiQuote; manipulating data with Quote Editor; understanding errors reported by the Database Purify Tool, plotting AFL functions as a training aid and more …………….

    Attached Files:

  • Click on the link to browse document files on line, or, Save As to download an editable version, complete with a document map (the document map will only be available to users who own a copy of Word).
  • To download .afl files to the desktop right click on the link  and Save Target As ‘filename’ at Program Files/AmiBroker/Formulas/Custom to access them as formulas in the AmiBroker Charts list.
  • 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
    Loading ... Loading ...

    Keeping Your Chart Right-Justified

    In real-time trading it is vital to keep your chart right justified, i.e., ensuring the right-most price bar is visible at all times. Failing to do so and looking at the wrong bar when trading real-money can invoke a panic response by the trader that results in erroneously closing a position or worse, placing a wrong order. This can easily happen if you are running several computers and are not always monitoring the chart being traded.

    The following code shows you how you can right-justify your chart at system startup or from the Param window. A visible alert that changes the chart back ground color when the last bar is not visible is included.

    The Alarm uses DateTime() to automatically correct for blank bars at the right edge of your chart. The code is kept explicit and you may be able to optimize it for speed.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    procedure RightJustifyChart( ChartWidth )
    {
    DT = DateTime();
    BI = BarIndex();
    FirstDateTime = LastValue( Nz(Ref( DT,-Max(2, ChartWidth) ) ) );
    FirstDateTimestr = DateTimeToStr( FirstDateTime );
    LastDateTimestr = DateTimeToStr( LastValue(DT) );
    AB = CreateObject("Broker.Application");
    AW = AB.ActiveWindow;
    AW.ZoomToRange( FirstDateTimestr, LastDateTimestr );
    }  
     
    RightJustify  = ParamTrigger("Right Justify Chart","RIGHT JUSTIFY");
    ChartWidth = Param("Chart Width",20,1,200,1);
    NotRightJustifiedColor = ParamColor("Chart Right Justified",colorPink);
    if( IsNull(StaticVarGet("CodeInitialized")) OR RightJustify )
        {
        StaticVarSet("CodeInitialized", 1);
        RightJustifyChart( ChartWidth );
        }  
    Plot(C,"",1,128);  
    DT=DateTime();
    IsRightJustified = LastValue(DT) == LastValue(ValueWhen(Status("BarVisible"), DT));
    if( NOT IsRightJustified ) SetChartBkColor(NotRightJustifiedColor);

    Edited by Al Venosa.

    1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.5 out of 5)
    Loading ... Loading ...
    « Previous Page