Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Code - Monte Carlo

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Stocks & Commodities V.

19:2 (81-85, 92): Traders’ Tips

TRADERS’ TIPS
SUM( CL*(VO/(VMA * n)) , n )

where:
CL is the last price
VO is the day volume
VMA is the volume moving average over n periods.

The entire expression is summed over n periods. Note the


volume moving average (VMA) is multiplied by its period to
obtain the total volume.
—Eric Hynniman
Linn Software, 800 546-6842
FIGURE 6: BYTE INTO THE MARKET. Select the parameters for your trading system test, sales@linnsoft.com, http://www.linnsoft.com
including cash management, test dates, and how you want the results ranked. You can run the
test against all the securities in your main portfolio or you can create a subgroup of stocks to
test on.

of the 12 subgroups easier and allows you to more easily


scroll through the securities (change securities) in the group,
applying a chart layout you are using to examine the system
to each ticker sequentially (for example, only the tickers in
the group get placed into the layout as you cycle through
securities with either your mousewheel or repetitive icon bar
clicks).
We created a layout with the charted system and the two
volume-weighted moving averages in one pane and the
simple moving average (SMA) crossover system and the two
SMAs in a second pane. This chart template (layout) is
available for download from our website at http://
www.tarnsoft.com/buff.zip.
FIGURE 7: TRADING SOLUTIONS. Here’s a sample chart of the Buff volume-weighted
A chart created from this template is shown in Figure 4. To
run a test on the main security group, right-click the colored moving averages as implemented in TradingSolutions software.
status button for the charted trade system to display its
context menu and select “Multiple security test” as shown in
Figure 5. The multiple security test setup dialog then appears, ! TRADINGSOLUTIONS
where you can set your cash management (for example, no TradingSolutions allows you to enter custom formulas as
stops, no commission, constant-share trade amount) and the function definitions that you apply to any stock or data series
dates for the tests, as well as how you would like the results in your portfolio. These functions can also be exported to be
ranked. Click the “tag all” button to test all the securities in shared with other users.
the 12 subgroups at once (since the security group data The volume-weighted moving average presented in Buff
restriction means that these are the only securities BITM is Dormeier’s article in this issue, “Buff Up Your Moving
currently using). Or you can specify any of the subgroups by Averages,” can be entered in TradingSolutions using the
clicking “Clear tags” and then checking the securities in the following formula:
subgroup. Such a setup is shown in Figure 6 for the “S&P
large cap,” “Highest beta” subgroup. This subgroup can be Div ( Sum ( Mult ( Close, Volume ), Period ), Sum ( Volume, Period ) )
saved to disk, so in the future you can easily recreate that
particular subgroup’s selections (load it from a disk file). This function is available in a function file that can be
This tip is also available at http://www.tarnsoft.com. downloaded from our website in the Solution Library section.
—Tom Kohl, Tarn Software, 303 794-4184 It can then be imported into TradingSolutions using “Import
bitm@tarnsoft.com, http://www.tarnsoft.com functions...” from the File menu. A sample chart can be seen
in Figure 7.
! INVESTOR/RT To apply one of these imported functions to a stock or
Here are the Investor/RT scan formulas for this month’s group of stocks, select “Add New Field...” from the context
Traders’ Tips subject, Buff moving averages. menu for the stock or group, select “Calculate a value...,” then
Buff averages are calculated in Real Time Language as select the desired function from the “Traders’ Tips functions”
follows: group.

Copyright (c) Technical Analysis Inc.


Stocks & Commodities V. 19:2 (81-85, 92): Traders’ Tips

TRADERS’ TIPS
—Gary Geniesse, TradingSolutions Project Lead TrRisk = 1000;
NeuroDimension, Inc. EntPr = H + EntFrac * (H - L);
800 634-3327, 352 377-5144 If C > C[1] then
Buy next bar at EntPr Stop;
info@tradingsolutions.com
www.tradingsolutions.com Exitlong(“MMStop”) next bar at EntryPrice - TrRisk/BigPointValue
stop;
If BarsSinceEntry >= 1 and open of next bar > EntryPrice then
! TECHNIFILTER PLUS ExitLong(“ProfOpen”) next bar at market;
Here is the TechniFilter Plus formula that computes the Value1 = MonteCarlo (ASize, DDGoal, RiskPer, TrRisk, NRand);
volume-weighted moving average described in Buff
Dormeier’s article in this issue, “Buff Up Your Moving {This last line calls the MonteCarlo function, which randomizes the
Averages.” The formula uses the TechniFilter Plus F-modifier trades and summarizes the results. Delete it if you don’t want the
to compute this average. MonteCarlo results.}
—Michael R. Bryant
Formula for a volume-weighted average
NAME: Buff_Avg ! MONTE CARLO SYSTEM
PARAMETERS: 10 The EasyLanguage 2000i function named MonteCarlo, which
FORMULA: (C*V)F&1 / VF&1 was referred to in my article in this issue, “Position Sizing
With Monte Carlo Simulation,” uses a Monte Carlo simulation
Visit RTR’s website at http://www.rtrsoftware.com to to estimate the probability that a series of trades will produce
download this formula as well as program updates. Release a specified, maximum closed-trade drawdown. It consists of
8.3 is available for download. the following steps:
—Clay Burch, RTR Software
Collect the profit/loss for each trade and the amount risked
919 510-0608, E-mail: rtrsoft@aol.com
http://www.rtrsoftware.com on each trade. After all trades are collected, loop over the
number of random sequences:

! AIQ TRADINGEXPERT A. Generate a random sequence of the given trades.


B. Accumulate the account equity and calculate the
Here is some EDS code for AIQ TradingExpert that implements
maximum drawdown and rate of return for the current
the Buff moving averages, submitted by an AIQ TradingExpert sequence.
user. C. Increment sums for the average return and the probability
of meeting the drawdown goal.
! Buff Moving Averages (BMAs)
! AIQ EDS codes by Onnfoh Yu Divide the sums from C by the number of sequences to
Define Fast 5. obtain the average return and the drawdown probability.
Define Slow 20. The function uses the built-in parameter TotalTrades to
determine when each trade exits. When TotalTrades changes
VolumeSumFast is Sum([Volume], Fast). value, it indicates that the prior trade has exited, and the
VolumeSumSlow is Sum([Volume], Slow).
VolumePrice is [Close]*[Volume]. profit/loss for that trade is collected in an array. In certain
cases, it is possible for TotalTrades to increment by 2 on the
FastBMA is Sum(VolumePrice,5)/VolumeSumFast. current bar; in this case, the profit/loss from the last two
SlowBMA is Sum(VolumePrice,20)/VolumeSumSlow. trades are recorded on the same bar.
—Onnfoh Yu, AIQ TradingExpert user Once all the trade data have been collected in arrays, the
function waits until the end of the chart before starting the
calculations. Because the trading system looks forward one
! HIGH PERCENTAGE TRADING SYSTEM CODE day (at the next day’s opening), it never reaches the last bar
The trading system used in my article in this issue, “Position on the chart. As a result, it is necessary to execute the
Sizing With Monte Carlo Simulation,” can be coded in calculations on the next-to-last, rather than the last, bar on the
TradeStation and other software as follows: chart. This is the purpose of the line that contains the function
LastCalcDate.
Input: ASize (30000), { starting account size, $ } A random sequence of trades is generated by first collecting
DDGoal (50), { max closed out trade drawdown, % } a series of M random numbers in an array, where M is the
RiskPer (10), { percentage risk per trade } number of trades. Then the array of random number is sorted,
NRand (1000), { number of random sequences }
EntFrac (0.75); { multiple of range for entry } and the order of the sorted array is taken as the sequence of
the trades.
Var: EntPr (0), { Entry target price } When calculating the rate of return and drawdown for each
XitPr (0), { mm stop exit price } sequence, the number of contracts is calculated according to:
TrRisk (0); { trade risk, $ }

Copyright (c) Technical Analysis Inc.


Stocks & Commodities V. 19:2 (81-85, 92): Traders’ Tips

TRADERS’ TIPS
N = Risk%/100 * Equity/TradeRisk
{ Generate random sequence of trades }
For ii = 0 to NTrades - 1 Begin { generate random
where Risk% is the fixed fraction in percent (that is, percent numbers }
of account risked on each trade), Equity is the current equity RandNums[ii] = IntPortion(NTrades * Random(10));
in the account up to that point, and TradeRisk is the dollar
amount being risked on the next trade. Because the number of end;
For ii = 0 to NTrades - 1 Begin { sort index of
contracts must be a whole number, N is rounded down to the RandNums array }
nearest integer. The number of contracts is then multiplied by MaxNum = -1;
the trade profit/loss and added to the current equity to get the For jj = 0 to NTrades - 1 Begin { find biggest # left
new equity value. }
If RandNums[jj] > MaxNum then Begin
The EasyLanguage 2000i code for function MonteCarlo MaxNum = RandNums[jj];
follows: iMax = jj;
end;
Input: ASize (NumericSimple), { account size, $ } end;
DDGoal (NumericSimple), { max closed out trade RandIndx[ii] = iMax; { record location of max
drawdown, % } number }
RiskPer (NumericSimple), { percentage risk per trade } RandNums[iMax] = -1; { “remove” max # from array }
TrRisk (NumericSeries), { risk for current trade, $ } end;
NRand (NumericSimple); { number of random
sequences } { Calculate account balance and drawdown for current
sequence }
Array: Trades[200](0), { Trades, $ (win +; loss -) } Equity = ASize;
TrRisks[200](0), { trade risks, $ (+) } EqtyHigh = Equity;
RandNums[200](0), { array of random numbers } DDmax = 0;
RandIndx[200](-1); { randomly chosen indices for trade For ii = 0 to NTrades - 1 Begin
array } NCon = IntPortion(RiskPer/100 * Equity/
TrRisks[RandIndx[ii]]);
Var: NTrades (0), { Number of trades } NewEquity = Equity + NCon * Trades[RandIndx[ii]];
iSeq (0), { sequence number }
MaxNum (0), { max number left in array RandNums } { Calculate closed trade percent drawdown }
iMax (0), { index (location) of MaxNum in array If (NewEquity > EqtyHigh) then
RandNums } EqtyHigh = NewEquity
NCon (0), { number of contracts } else Begin
Equity (0), { account equity } DD = 100 * (EqtyHigh - NewEquity)/EqtyHigh;
NewEquity (0), { account equity } if (DD > DDmax) then
EqtyHigh (0), { highest equity } DDmax = DD;
DD (0), { closed trade drawdown } end;
DDmax (0), { worst case closed trade drawdown } Equity = NewEquity;
PReturn (0), { percent return } end; { for ii }
AveRet (0), { average percent return } PReturn = 100 * (Equity - ASize)/ASize;
ProbDD (0), { probability of drawdown goal }
ii (0), { loop counter } { Accumulate results for probability calculations }
jj (0); { loop counter } AveRet = AveRet + PReturn;
if (DDmax <= DDGoal) then
{ Collect profit/loss and risk } ProbDD = ProbDD + 1;
If TotalTrades > NTrades then Begin End; { for iSeq }
If TotalTrades - NTrades < 2 then Begin
NTrades = NTrades + 1; { Calculate probabilities by dividing sums by number of
Trades[NTrades - 1] = PositionProfit(1); sequences }
TrRisks[NTrades - 1] = TrRisk; AveRet = AveRet/NRand;
end ProbDD = 100 * ProbDD/NRand;
else Begin{ case where TotalTrades increments by 2 } MessageLog(“RiskPer=”, RiskPer:5:1, “ DDGoal=”,
NTrades = NTrades + 1; DDGoal:5:1,
Trades[NTrades - 1] = PositionProfit(2); “ ProbDD=”,ProbDD:5:1);
TrRisks[NTrades - 1] = TrRisk[1]; MessageLog(“Average Return = “, AveRet:6:2);
NTrades = NTrades + 1; end;
Trades[NTrades - 1] = PositionProfit(1);
TrRisks[NTrades - 1] = TrRisk; MonteCarlo = 1;
end;
end; —Michael R. Bryant
310 370-4069
{ Calculate results 1 day from last bar on chart }
If Date = JulianToDate(DateToJulian(LastCalcDate) - 1) then
Begin

for iSeq = 1 to NRand Begin { loop over # of random


sequences }

Copyright (c) Technical Analysis Inc.

You might also like