These two sites provides free forex tick/time data. So before getting into backtesting, we must get data.

I provide two scripts for you to download and update these data daily.

OK, it’s boring…

However, there’s still some work to update our data every day/week.

Like this:


For the next, we’ll try to apply basic strategy to backtest our data.

Like this:


tradelink Write automated trading systems, connect with 17+ broker APIs
AIOTrade AIOTrade (formerly Humai Trader Platform) is a free, open source stock technical analysis platform built on pure java.
manticore-trader manticore-trader is a free and open java software for day trading warants on stocks, currencies and comodities. It includes modules for charting, position and risk management, automatic ordering and system trading. Instruments and quotes of the main financial markets are provided daily
G-BOT G-BOT is a public academic project, headed by Prof. Tom Gastaldi (first University of Rome “La Sapienza”). The project is about the study of trading algorithms and fully automated strategies for systematic profitability.
Marketcetera Marketcetera focuses on building the key trading functions that are common to all organizations, thus freeing our clients to concentrate on proprietary trading algorithms and other specialized software that provide a competitive advantage.
Merchant of Venice MOV is a stock market trading programme that supports portfolio management, charting, technical analysis, paper trading and genetic programming. Venice runs in a graphical user interface with online help and has full documentation.
EclipseTrader Eclipse Rich Client Platform (RCP) application featuring shares pricing watch, intraday and history charts with technical analysis indicators, level II/market depth view, news watching, and integrated trading.
JBookTrader All aspects of trading, such as obtaining market prices, analyzing price patterns, making trading decisions, placing orders, monitoring order executions, and controlling the risk are automated according to the user preferences. JBookTrader is a “sister” project to JSystemTrader. Matrex The perfect desktop tool for mathematical, statistical models and complex calculations. Adapters to matlab, scilab, octave, R.
OpenGamma OpenGamma provides technology for financial institutions to improve analytics calculation and delivery to front-office and risk users.
Open Java Trading System (Last Update 2010-08-14) The Open Java Trading System (OJTS) is meant to be a common infrastructure to develop (stock) trading systems. There are four parts: gathering of raw data over the internet, recognition of trading signals, a visualization module and trading with banks.
Joone Joone is a neural net framework written in Java(tm). It’s composed by a core engine, a GUI editor and a distributed training environment and can be extended by writing new modules to implement new algorithms or architectures starting from base component
Data Visualizer (Last Update 2009-07-17) Modular environment for graphical visualization of stock market type data SFL Java Trading System Enviroment (Last Update 2009-07-17) Java application built on KISS principle ( Keep It Simple,Stupid ) and its aim is to provide a fast and platform indipendent infrastructure to develop and execute trading systems.
ActiveQuant (Last Update 2009) Somewhat heavy stuff, for proficient programmers only
JSystemTrader (Last Update 2009) Developed to work with Interactive Broker’s API, fully automated trading system (ATS) that can trade various types of market securities during the trading day without user monitoring.
Market Analysis System (Last Update 2009-07-17) System for analysis of financial markets using technical analysis. Includes facilities for stock charting and futures charting, as well as automated generation of trading signals based on user-selected criteria. Operates on both daily and intraday data.
Oropuro trading system (Last Update 2009) Complete technical analysis & trading system, full set of features: retrieve, analyze EOD stocks data; manage multiple portfolios; technical analysis & graphical rendering; neural networks for generation of trading signals; support trader community,
AlgoTrader AlgoTrader is an automated trading system (ATS) that can trade any type of security on any market available through InteractiveBrokers or FIX. All aspects of trading like getting market data, analyzing prices, taking trade decisions, placing orders & tracking executions can be automated.
Encog Encog Java and DotNet Neural Network Framework | Heaton Research Encog Ninjatrader Getting Started – Encog Machine Learning Framework
Encog is an advanced neural network and machine learning framework. Encog contains classes to create a wide variety of networks, as well as support classes to normalize and process data for these neural networks. Encog trains using multithreaded resilient propagation. Encog can also make use of a GPU to further speed processing time. A GUI based workbench is also provided to help model and train neural networks.


Bill Williams Indicators

Accelerator/Decelerator oscillator(AC)

Acceleration/Deceleration (AC) technical indicator signals the acceleration or deceleration of the current market driving force.

How to Use Acceleration/Deceleration

The indicator is fluctuating around a median 0.00 (zero) level which corresponds to a relative balance of the market driving force with the acceleration. Positive values signal a growing bullish trend, while negative values may be qualified as a bearish trend development. The indicator changes its direction before any actual trend reversals take place in the market therefore it serves as an early warning sign of probable trend direction changes.
The indicator color changes alone are very important as the current green line (irrespectively of the value) warns against long positions the same way as the red one would against selling.
To enter the market along with its driving force one needs to watch for both value and color. Two consecutive green columns above the zero level would suggest you to enter the market with a long position while at least two red columns below the zero level might be taken for a command to go short.
Fake signals prevail in timeframes smaller than 4 hours.

Acceleration/Deceleration Oscillator Formula (Calculation)

AC bar chart is the difference between the value of 5/34 of the driving force bar chart and 5-period simple moving average, taken from that bar chart.

AO = SMA(median price, 5)-SMA(median price, 34)
AC = AO-SMA(AO, 5)


Alligator is an indicator designed to signal a trend absence, formation and direction. Bill Williams saw the alligator’s behavior as an allegory of the market’s one: the resting phase is turning into the price-hunting as the alligator awakes so that to come back to sleep after the feeding is over. The longer the alligator is sleeping the hungrier it gets and the stronger the market move will be.

How to Use Alligator Indicator

The Alligator indicator consists of 13-, 8- and 5-period smoothed moving averages shifted into the future by 8, 5 and 3 bars respectively which are colored blue, red and green representing the alligator’s jaw, teeth and lips.
The Alligator is resting when the three averages are twisted together progressing in a narrow range. The more distant the averages become, the sooner the price move will happen.
The averages continuing in an upward direction (green followed by red and blue) suggest an emerging uptrend which we interpret as a signal to buy.
The averages following each other in the reversed order down the slope are a strong signal of an unfolding downtrend so selling at this point would be more than appropriate.

Alligator Indicator Formula (Calculation)


Awesome oscillator(AO)

Awesome Oscillator (AO) is a momentum indicator reflecting the precise changes in the market driving force which helps to identify the trend’s strength up to the points of formation and reversal.

How to Use Awesome Oscillator

There are three main signals which may be seen:
Saucer – three consecutive columns above the nought line the first two of which must be colored red (the second one is lower than the first one) while the third one is colored green and higher than the previous (second) one. Such a formation would be a clear Buy signal whilst inverted and vertically flipped formation would serve as a Sell signal.
Nought line crossing – the histogram crosses the naught line in an upward direction changing its values from negative to that of positive ones. In this situation we have a Buy signal. The Sell signal would be a reversed pattern.
Two pikes – the indicator displays a Buy signal when the figure is formed by two consecutive pikes both of which are below the naught line and the later-formed pike is closer to the zero level than the earlier-formed one. The Sell signal would be given by the reverse formation.

Awesome Oscillator Trading Strategy

Awesome Oscillator Strategy includes 3 ways of trading. The first way is to open a sell position when the oscillator is below the zero line forming a peak, and open a buy position when the oscillator is above the zero line forming a gap.
Another way is to open a sell position when the oscillator forms two peaks above the zero line, where the second high is lower than the previous one. And, conversely, traders watch to open a buy position when the oscillator forms to lows below the zero line with the last one not as low as the previous one.
The third way is to account crossing the zero line. When the oscillator crosses it from up to down, it is time to open a sell position and when it crosses from down to up, it is time to open a buy position.

Awesome Oscillator Formula (Calculation)

Awesome Oscillator is a 34-period simple moving average, plotted through the central points of the bars (H+L)/2, and subtracted from the 5-period simple moving average, graphed across the central points of the bars (H+L)/2.
SMA — Simple Moving Average.

Fractal Indicator Definition

Fractals is an indicator highlighting the chart’s local heights and lows where the price movement had stopped and reversed. These reversal points are called respectively Highs and Lows.
How to Use Fractal Indicator

Bill Williams’ Fractals are formed around a group of five consecutive bars the first two of which are successively reaching higher (or diving deeper) and the last two descending lower (or growing higher) with the middle one being the highest (or the lowest) result in the group accordingly.
Buy fractal is an arrow pointing to the top
Sell fractal is an arrow pointing to the bottom
Gator Oscillator Definition

The Gator Oscillator (GO) is a supplement to the Alligator indicator and is used alongside with it showing the absolute degree of convergence/divergence of the Alligator’s three SMAs pointing at the Alligator’s periods of slumber and awakeness (i.e. trending and non-trending market phases).
How to Use Gator Oscillator

Being an oscillator in the form of two histograms built on either side of the naught line, the Gator Oscillator plots the absolute difference between the Alligator’s Jaw and Teeth (blue and red lines) in the positive area and the absolute difference between the Alligator’s Teeth and Lips (red and green lines) in the negative area. The histogram’s bars are colored green if exceeding the previous bar’s volume or red if falling short.
The bars of the extreme values are in tune with the strong trend forces.
The Alligator’s activity periods are divided into the following four:
Gator awakes – the bars on different sides of the naught line are colored differently.
Gator eats – green bars on both sides of the naught line.
Gator fills out – single red bar during the “eating” phase.
Gator sleeps – the bars on both sides are red
Market Facilitation Index Definition

The Market Facilitation Index is designed for evaluation the willingness of the market to move the price. The indicator’s absolute values alone cannot provide any trading signals unlike it’s dynamics in relation to the dynamics of the volume.
How to Use Market Facilitation Index

The absolute values of the index are represented by the histogram’s bars while the comparison of the index and volume dynamics are given in colors which are vital in terms of reading the indicator signs.
Green bar – both MFI and volume are up. Increasing trading activity means market movement acceleration. We may join the trend.
Blue bar – MFI indicator is up, volume is down. The movement is continuing although the volume has dropped. The trend will soon be reversing.
Pink bar – MFI indicator is down, volume is up. The slowing down movement while volume is raising may indicate a possible break through, often a U-turn.
Brown bar – both MFI and volume are down. The market is no longer interested in the current direction and is looking for signs of a future development.
Market Facilitation Index
Market Facilitation Index (BW MFI)
Market Facilitation Index Formula (Calculation)



Trend Indicators

Volume Indicators


Accumulation/Distribution is a volume-based technical analysis indicator designed to reflect cumulative inflows and outflows of money for an asset by comparing close prices with highs and lows and weighting the relation by trading volumes.

How to Use Accumulation/Distribution

The Accumulation/Distribution line is used for trend confirmation or possible turning points identification purposes.
Trend confirmation:
An uptrend in prices is confirmed if A/D line is rising;
A downtrend in prices is confirmed if A/D line is falling.
Divergence pattern analysis:
Rising A/D line along with decreasing prices indicates the downtrend may be weakening to a bullish reversal;
Falling A/D along with rising prices indicates the uptrend may be weakening to a bearish reversal.

Accumulation/Distribution Indicator Formula (Calculation)

A/D(t) = [((C – L) – (H – C)) / (H – L)] x Vol + A/D(t-1),
A/D(t) – current Accumulation/Distribution value;
A/D(t-1) – previous Accumulation/Distribution value;
H – current high;
L – current low;
C – close price;
Vol – volume.


Average Directional Movement Index(ADX)

Average Directional Index (ADX) is a technical indicator developed by Welles Wilder to estimate trend strength and determine probable further price movements by comparing the difference between two consecutive lows with the difference between the highs.

How to Use ADX Indicator

ADX is a complex indicator, which results from calculation of the Plus Directional Indicator (+DI – green line) and the Minus Directional Indicator (-DI – red line), but all of them may be used for trend analysis.

In general the indicator (bold line) move is believed to reflect current trend strength:
Rising ADX (usually climbing above 25) suggests strengthening market trend – trend following indicators are becoming more useful;
Falling ADX suggests the trend development is doubtful. ADX values below 20 may indicate neutral trend is present – oscillators are becoming more useful.
Use of complex ADX trading system may require additional confirmation signals:
Normally if +DI (green line) climbs above -DI (red line), a buy signal is generated;
Normally if -DI climbs above +DI, a sell signal is generated.
Average Directional Index Indicator – ADX Indicator
Average Directional Index (ADX) Indicator

ADX Trading Strategy

ADX trading strategy aims to identify the strongest trends and distinguish between trending and non-trending conditions.
ADX reading above 25 indicates trend strength, while when ADX is below 25, this shows trend weakness. Breakouts, which are not difficult to spot, also help to identify whether ADX is strong enough for the price to trend or not. Thus, when ADX rises from below 25 to above 25, trend is considered strong enough to continue in the direction of the breakout.
It’s a common misperception that when ADX line starts falling this is a sign of trend reversal. Whereas, it only means that the trend strength is weakening. As long as ADX is above 25, it should be considered that a falling ADX line is simply less strong.

ADX Formula (Calculation)

ADX = MA [((+DI) – (-DI)) / ((+DI) + (-DI))] x 100;
+DI – Plus Directional Indicator;
-DI – Minus Directional Indicator.


Average True Range(ATR)
Bears Power
Bollinger Bands
Bulls Power
Commodity Channel Index(CCI)
Gator oscillator
Ichimoku Kinko Hyo
Market Facilitation Index(BWMFI)
Money Flow Index
移动平均线(Moving Average,MA)


Moving Average is a technical analysis tool that shows average price over a given period of time, which is used to smoothen price fluctuations and therefore to determine trend direction and strength.
Depending of the method of averaging, distinguish between simple moving average (SMA), smoothed moving average (SMMA) and exponential moving average (EMA).

Moving Average Trading Strategy

Moving average strategy is essentially a trend following means. Its objective is to signal the beginning of a new trend or a trend reversal. Herein, its main purpose is to track the progress of the trend and not to predict market action in the same sense that technical analysis attempts to do. By its nature, Moving Average is a follower; it follows the market telling that a new trend has begun or reversed only after the fact.

Moving Average Formula (Calculation)

SMA = Sum (Close (i), N) / N,
Close (i) – current close price;
N – period of averaging.
EMA(t) = EMA(t-1) + (K x [Close(t) – EMA(t-1)]), 
t – current period;
K = 2 / (N + 1), N – period of averaging.

How to Use Moving Average

Generally moving average curves analysis includes the following principles:
Direction of moving average curve reflects prevailing trend over a period;
Low-period averaging may give more false signals, while large-period averaging tend to be lagging;
To increase (decrease) sensitivity of the curve one should decrease (increase) the period of averaging;
Average curves are more useful in trending environment.

Comparing moving average with price movements:
A strong buy (sell) signal arise if price crosses from below (from above) its rising (falling) moving average curve;
A weak buy (sell) signal arise if price crosses from below (from above) its falling (rising) moving average curve.
Comparing moving average curves of different periods:
A rising (falling) lower-period curve crossing from below (above) another rising (falling) longer-period curve gives a strong buy (sell) signal;
A rising (falling) lower-period curve crossing from below (above) another falling (rising) longer-period curve gives a weak buy (sell) signal.
Moving Average of Oscillator
抛物线转向(Stop And Reverse)


# -*- coding: utf-8 -*-

"""   2014

Translated from
Requires pandas to load csv files, and matplotlib to chart the data

The main expects table.csv file. Valid files can be downloaded on Yahoo Finance

import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt

def psar(barsdata, iaf = 0.02, maxaf = 0.2):
    length = len(barsdata)
    dates = list(barsdata['Date'])
    high = list(barsdata['High'])
    low = list(barsdata['Low'])
    close = list(barsdata['Close'])
    psar = close[0:len(close)]
    psarbull = [None] * length
    psarbear = [None] * length
    bull = True
    af = iaf
    ep = low[0]
    hp = high[0]
    lp = low[0]
    for i in range(2,length):
        if bull:
            psar[i] = psar[i - 1] + af * (hp - psar[i - 1])
            psar[i] = psar[i - 1] + af * (lp - psar[i - 1])
        reverse = False
        if bull:
            if low[i] < psar[i]:
                bull = False
                reverse = True
                psar[i] = hp
                lp = low[i]
                af = iaf
            if high[i] > psar[i]:
                bull = True
                reverse = True
                psar[i] = lp
                hp = high[i]
                af = iaf
        if not reverse:
            if bull:
                if high[i] > hp:
                    hp = high[i]
                    af = min(af + iaf, maxaf)
                if low[i - 1] < psar[i]:
                    psar[i] = low[i - 1]
                if low[i - 2] < psar[i]:
                    psar[i] = low[i - 2]
                if low[i] < lp:
                    lp = low[i]
                    af = min(af + iaf, maxaf)
                if high[i - 1] > psar[i]:
                    psar[i] = high[i - 1]
                if high[i - 2] > psar[i]:
                    psar[i] = high[i - 2]
        if bull:
            psarbull[i] = psar[i]
            psarbear[i] = psar[i]

    return {"dates":dates, "high":high, "low":low, "close":close, "psar":psar, "psarbear":psarbear, "psarbull":psarbull}

if __name__ == "__main__":
    import sys
    import os
    if len(sys.argv) < 2:
        sys.exit("Usage: %s datafile.csv" % sys.argv[0])
    if not os.path.exists(sys.argv[1]):
        sys.exit("Error: can't open file '%s': No such file" % sys.argv[1])

    barsdata = pd.read_csv(sys.argv[1])
    #Reindex the data: ascending dates are expected in the function
    barsdata = barsdata.reindex(index=barsdata.index[::-1])
    #Convert strings to actual timestamps
    barsdata['Date'] = [datetime.strptime(x, '%Y-%m-%d') for x in barsdata['Date']]

    startidx = 0
    endidx = len(barsdata)
    result = psar(barsdata)
    dates = result['dates'][startidx:endidx]
    close = result['close'][startidx:endidx]
    psarbear = result['psarbear'][startidx:endidx]
    psarbull = result['psarbull'][startidx:endidx]
    plt.plot(dates, close)
    plt.plot(dates, psarbull)
    plt.plot(dates, psarbear)

Moving Averages Convergence/Divergence(MACD)
On Balance Volume(OBV)
相对强弱指标(Relative Strength Index,RSI)
Relative Vigor Index(RVI)
漫步随机指标(Random Walk Index,RWI)
Standard Deviation(StdDev)
Stochastic Oscillator
Larry Williams’ Percent Range(WPR)

View: Information and connections
Intention: Goals
Speech: Communication among the agents
Action: Interaction
Livelihood: Payoffs
Effort: Strategies and actions
Mindfulness: Cognition
Concentration: Model focus and heterogeneity














#!/usr/bin/env python
import random

match_first = 0.00
match_second = 0.00

for i in range(1,1000):
    print "Game round %i" % i 
    door = ['a', 'b', 'c']
    # We choose a random door with prize.
    prize = door[random.randint(0,2)]
    # Now player's turn
    player_choice = door[random.randint(0,2)]
    # If player choose the right one at first
    if player_choice == prize:
        # If player sticks to his/her choice
        match_first += 1
        # If he change hist mind and we can be sure that player is lost
        print "Stick to the first: %i\nChange to the second: %i\nWin on the second thought: %.2f" %(match_first, match_second, match_second/i)
    # If player choose the wrong one at first
        # We open a blank door and player changes his mind, then player wins
        match_second += 1
        print "Stick to the first: %i\nChange to the second: %i\nWin on the second thought: %.2f" %(match_first, match_second, match_second/i)


Game round 999
Stick to the first: 347
Change to the second: 652
Win on the second thought: 0.65



100个工人操作1个生产豆子的机器,生产出的豆子可以用来消费、购买机器(一个豆子)、储蓄,每个机器的产出为 100*机器数量^0.5 个豆子,机器第二年的报废率为10%,每年总产出的20%用于投资,其他用于消费。


总产出 = 100 * 机器数量^0.5

储蓄 = 储蓄率s * 总产出

总产出 = 消费 + 投资

下一年机器数量 = 当年机器数量 + 投资机器数量 - 报废率d * 当年机器数量



s * 100 * 机器数量^0.5 = d * 机器数量

此时机器数量维持在 10000s/d

消费 = 10000 * s * (1-s)/d


Here’s the sketch.

Source code.













2016-7 模型学习、算法学习、平台构建、渠道收集
2016-8 算法学习、平台构建、趋势输出