Generation of Predictive Price and Trading Volume Patterns in a Model of Dynamically Evolving Free Market Supply and Demand

present a model of stock market price fluctuations incorporating effects of share supply as a history-dependent function of previous purchases and share demand as a function of price deviation from moving averages. Price charts generated show intervals of oscillations switching amplitude and frequency suddenly in time, forming price and trading volume patterns well-known in market technical analysis. Ultimate price trends agree with traditional predictions for specific patterns. The consideration ofdynamically evolving supply and demand in this model resolves the apparent contradiction with the Efficient Market Hypothesis: perceptions of imprecise equity values by a world of investors evolve over non-negligible periods of time, with dependence on price history.


I. INTRODUCTION
A fundamental tenet underlying chart technical analysis is the belief that future changes in prices of market securities are predictable, within a range of precision, based on the prior history of traded prices and volume (number of shares traded in one time period).Extensive literature exists detailing different methods of technical analysis; see for example Pring (1991) and Edwards and Magee  (1992).Numbers of chart technicians and their organizations past and present have traded profit- ably using these methods.Chart technical analysis has traditionally not been seriously regarded by academic researchers, however, due to the appar- ent paradox that if all future prices are foreseeable due to well-known techniques, then trades by analysts must always be too late to profit from predictions (an application of the Efficient Market Hypothesis).Market technicians, behavioral econ- omists, and presumably all discretionary investors and analysts, resolve this paradox as due to slow J.K. WANG evolution of perceptions of imprecise value by a diverse spectrum of investors, resulting in and influenced by dynamically evolving strengths of supply and demand for shares.
In technical analysis, concepts such as price levels of support and resistance and sentiment are used in making detailed analyses and projections of supply and demand levels.Price levels define ranges of predicted price movements for traded securities and indices.Sentiment refers to quanti- tative measures of the dominant aggregate ten- dency of investors to buy or to sell.At present, however, no complete explicit mathematical model exists of the interplay of investor actions, psychology, and prices to test and analyze consistency of these concepts.That is, although an extensive body of analytical techniques exists for predicting future behavior of markets, a mathematical model remains to be developed that reproduces realistic market behavior, giving a picture of the basic mechanisms underlying free market dynamics.Day (1997) has recently developed a model of market price action in the absence of information shocks that takes into account investor supply and demand and interactions due to market mediation (by a specialist or marketmaker).Prices generated by his model exhibit chaotic, quasi-periodic beha- vior-irregular oscillations which do not follow a simple regular formula-and patterns similar to well-known formations from technical analysis.Wang (1998) has noted, however, that in Day's   model share supply and demand, price jumps and volume, are all functions independent of time ex- cept through dependence on the last traded price.This is in contradiction with observations in reallife markets and with the principle from technical analysis of ever-changing supply and demand un- derlying price resistance and support levels.
In this paper I extend Day's model to include: share supply (sell orders) as a dynamic function dependent on the history of previous purchases; share demand as a function of the current price relative to moving averages; and trading volume including the specialist's contribution.The mathematical formulation and some preliminary discussion of the dynamically evolving model are presented in Sections II and III below.In Section IV I present results of calculations using the model, including theoretical price charts generated by the model.I find that using a wide range of parameters, quasi-periodic price behavior also occurs in this model with evolving supply and demand.I examine parameters representing var- ious supply and demand scenarios, bullish, bottom- ing, topping, and compare results to frequently observed real stock price patterns.In Section V I conclude with discussion oflimitations and assump- tions in the model and suggestions for further study and improvements.

II. MATHEMATICAL FORMULATION OF THE MODEL
As discussed in the Introduction, I developed my model beginning with several assumptions from Day's market price model.First, I assume trading by two types of investors, value/contrarian (A) and short-term/trader (B), and by a marketmaker or specialist who adjusts prices in a discrete tatonne- ment process dependent on the supply/demand im- balance for shares of stock.Throughout the rest of this paper, this model will be discussed in re- lation to "stock" prices and shares; all equations (with changes of parameters) should apply to any security, index, commodity or derivative traded in an open market.Second, I assume that, at any specific time and current trading price P(t), the price P(t+ 1) in the next period (e.g., hour, day, week) shifts by an amount proportional to excess total market supply of shares (Stot) over total market demand for shares (Otot); so that where Ct is a constant parameter for this tatonne- ment process.
In addition I model the corresponding trading volume V(t) for study as well, volume being nearly as important a variable as price itself in technical analysis.Share volume traded at each P(t) of course includes all investor share supply and demand which can be directly matched.At each time I also assume a constant fraction Csp of re- maining supply or demand imbalance is traded at P(t) by the specialist in the process of adjusting price to P(t+ 1).That is, V(t) (1 Csp)min(Otot, Stot) + Csp max(Dtot, Stot). (2) On the NASDAQ or other exchanges without specialists, the behavior of the equivalent market- maker is presumably similar, with different value of Csp (perhaps 0).
Total supply of/demand for stock shares is simply equal to the sum of supply/demand from the different investor types: Stot-SA n t-SB (3a) and Dtot DA -+-DB For common stocks, values are not precisely known and are generally perceived as different by different investors.Share supply and (indirectly) demand can then both depend to large extent upon trading history.Stock buying is primarily price- driven, by expectation of selling in the future at a higher price.In the absence of precise measures, investors must estimate stock purchase value relative to the range of past traded prices, i.e., by how much the market is "going up".If shorting of unowned shares comprises relatively little of total share supply, then selling is by previous buyers seeking gain (or minimal loss), also relative to the prices at time of original purchase.It is noted that market trading history is important even to investors who value using price/earnings ratios or other "fundamental" indicators, since they ulti- mately evaluate numbers relative to ranges of historically observed values.
Following the above arguments S and D;, A and B, were modeled to have dependence on (a) the evolving history of past trading prices, P(s; s < t), and (b) the distribution of shares currently owned at time and originally purchased at prices p, summarized as "ownership" functions N; (p, t) (ignoring dividends).The evolving dependence (a) on past prices is approximated as dependence on moving averages of past prices P; avg(t).Moving-  averages are widely used in technical analysis to determine optimal purchase and sale prices; see for example Pring (1991); Edwards and Magee (1992); and Ross (1998).Assuming that analysts do not themselves dominate market behavior, the success of such indicators is evidence that investor supply and demand in real markets do have strong dependence on price moving-averages.The model "memory" variable Ni(p,t) (b) includes no in- formation on times of earlier purchases at prices p.This implies that length of ownership has no effect on sale price.This is not strictly true in technical analysis but is a reasonable approximation; see Pring (1991), p. 186.If shorting except by the specialist is ignored, then Ni(p, t) is always positive.
For each investor type i, functions Si and Di can assume different functional dependences on price history and different parameter values.The func- tions assumed in this paper are" DA[P(t)] CA max{1 P(t)/PA avg(t), O} n, Si[P(t)] Z si[P(t)'P]' summed overp, (5a)   where si[P(t),p] RNi(p, t)tanhn[ll P(t)/pl/Li], (5b) and Ni(p, t) Ni(p, 1) si[P(t 1),p] min{V(t-1)/Stot[P(t-1)], 1} Ci, R, Li and n in the above equations are all constant parameters.As discussed in the preceding paragraph, Pi avg(t) in Eqs. (4)are exponential moving averages of P(t), with fixed time constant parameters.Investor B demand [Eq.( 4b)] in this model combines demand functions of short-term value (buying on small dips) and short-term trend (buying on small jumps) investors.As price devia- tions increase from zero, the tanh dependences in Eqs. ( 4b) and (5b) increase asymptotically from power-law dependences to constants.Intuiti- vely, supply and demand for a given stock cannot grow without limit in a finite market system.

III. COMMENTS ON THE MODEL
At each point in time all model variables in the model are calculated based iteratively on values one time interval before.At time 0 I start with assumed initial values for P(0), Pi avg(0), and Ni (p,  0).Equations ( 4) and (5) determine functions Si and Di, from which Eqs. ( 1) and (2) generate V(0), P(1) and Piavg(t).Equation (6) then generates Ni (p, 1).The routine repeats, using values at time to generate values at time t/ 1. Due to limits on computational power, ownership functions Ni(p, t) were approximated in actual calculations as total stock purchased at prices within unit intervals of p rather than at actual prices p (i.e., as discrete rather than continuous functions).For reasonably large values of p, this approximation did not qualitatively affect results.Also due to computational limits, just 3 investor types were modeled in Section II: long-term value investor, short-term buyer-on-dips, and short-term buyerof-trends.While diversity is no doubt much greater in real markets, it was hoped that important features of real markets would still appear in this model approximation.
Some comments are in order regarding the constant parameters in Eqs.(4) and (5): Ci, R, Li and n, as well as the time constants for moving averages Pi avg(t).
In Eqs.(4) C are constant factors determining size of investor demand.They give a measure of interest and/or available liquidity from the different investor classes.
In Eq. (5b), R is similarly a constant factor modifying the actual size of supply, effectively defining the fraction of underlying supply appearing as actual market sell orders in each given time interval.R is therefore a measure of negative sentiment or overall investor readiness to sell.
In Eqs. ( 4b) and (5b), Li is a profit-stop parameter determining the range of price move- ment significant to investor i.LB appears in Eq.
(4b) as a natural limit on demand, since investor B presumably will not buy if prices have jumped from his/her perceived base price Piavg(t) by more than his/her expected profit amount.Li is thus a measure of the strength of investor conviction; i.e., of his/her risk tolerance for fluctuations in investment value.
In Eqs. ( 4a) and (5b), variable n is a constant exponent determining supply/demand price elasticity, or how "abruptly" supply/demand increases as prices approach profit-stop levels, n should be larger for investor classes with well- defined trading strategies and for more homo- geneous investor composition (e.g., for fewer but larger institutional investors rather than numerous smaller investors with a broad spec- trum of trading strategies).For investor B, n equals one, assuming that early response is char- acteristic of buying short-term price moves.To reduce calculational complexity, other investor types are assumed to have the same value of n in a given price chart projection.
In a given price chart projection, precise values of the constant parameters discussed above are not so meaningful as the effects of variations of values in different price chart projections.A trivial ex- ample is that price behavior is unchanged if total number of stock shares were expressed in thou- sands or millions and all parameters were scaled accordingly.

IV. RESULTS OF MODEL CALCULATIONS
IV.1.Head-and-Shoulders Pattern functions for investor types A and B, assuming original purchases of 18.5 shares at 44.5 by A and 5.5 shares at 45.5 and 46.5 each by B. For the sake of clarity supply functions are shown as negative.
As noted above, number of shares in this mo- del could be interpreted as millions of shares of a real exchange-traded stock.Initial moving-average prices are 46 for A and B, with averaging time constants of 108 and 28, respectively.Other para- meters are: CA=240, CB 14, R=9%, LA--16% LB=6%, and n=3.5.Table I summarizes all initial and constant parameters used for price projection studies in this section.Following Eq. (4a) long-term value investor (A) demand [solid dark line] occurs only for prices below the long-term moving-average.Price dependence is highly non-linear; value investor A buys only at prices well below his perceived base average.
Short-term investor (B) demand [Eq. (4b), solid light line] increases with both positive and negative price fluctuations around the moving-average price.Price dependence is linear for small price fluctuations but asymptotically constant for larger fluctuations, as discussed in Section III.
Both longand short-term investor supply functions [Eq.(5b), line with markers and dashed line] are symmetric about the initial purchase prices, proportional to number of shares pur- chased.Supply functions are highly non-linear (n= 3.5) so that significant supply appears only after significant price movement has occurred after initial purchases.Like demand, supply levels off at extreme price deviations.With the given para- meters, supply is initially smaller than demand in Figure 1; prices therefore rise in near-future time periods (Fig. 2).After more shares have traded at increasing prices, supply increases at all prices.Simultaneously, price moving-averages will con- verge towards the trading price range.Investor A demand decreases as prices rise; B demand does not decrease as much due to B's shorter time constant.The resulting price charts will show ----investor A demand ----investor B demand   rising prices until supply exceeds demand.More complex behavior results thereafter, dependent up- on the interplay of supply and demand from the two investor types.
Figure 2 shows the complete resulting price/ volume chart calculated from the model equations in Section II, using the initial parameters specified for Figure 1.Ct 22% for this example.The chart reproduces the classic head-and-shoulders forma- tion from chart technical analysis and the expected price drops following.Consistent with heuristic arguments of technical analysis, volume on the left shoulder is primarily investor A selling to investor B, as A's profit-stop objective is approached (slightly below 116% x 44.5 51.12).Volume on the right shoulder [t > 65] is lighter, arising from "late" B investor buying and none by A investors.The left shoulder is not as well-developed as the right in this particular calculation.Price curve os- cillations are smoother than usually observed in daily and weekly charts, more characteristic of intraday price charts.Smoothness is consistent with stock price movement over shorter periods of time, where the period-by-period model equations and parameters in Section II would be expected to hold most accurate.Reproduction of the irregular  1)-( 5) and indicated initial parameters in Table I.
backing and filling cycles associated with longer- term charts may require more computational power and possibly additional parameters (see also discussion below and Wang (preprint)).
Approximate calculations generated a price re- bound, a retracement expected in technical analy- sis, after the fall from the right shoulder.Due to limits on computational power, however, prices were not precisely projected below 44 in Figure 2. Similar head-and-shoulders patterns were also generated (not shown) with other sets of initial parameters: for example, by increasing initial A shares to 20.0, n to 4.2, and R to 11%.The pattern generated by this variation extended over a longer period of time.An intuitive explanation is as fol- lows: increasing initial shares and R effectively ex- pands share supply and trading activity which must equilibrate over longer time in developing into a head-and-shoulders; increasing n extends the price range and time before sentiment responds to price changes.In general, however, patterns change significantly with arbitrary variations of initial parameters.Section IV.2 below provides an illustration.

IV.2. Climax Sell-Off Pattern
Figure 3 shows supply and demand functions for investor types A and B, assuming original pur- chases of 1.7 shares at 43 by A and 1.1 shares at 40.5 and 3.3 shares at 41.5 each by B. For A and B respectively, initial moving-average prices are 43 and 41; time constants are 109 and 9.4.Other parameters are: CA-240, CB--7.5, R--15%, LA 33%, LB--5% and n-3.5 [see Tab.I].Supply functions are again negative-valued as in Figure 1.
Parameter CA and exponent (n-3.5) of price de- pendence are the same as in Figure 1, but unit price changes are a larger fraction of the type A moving-average; value investor demand [solid dark line] therefore is larger than in Figure 1.
Short-term investor (B) demand [solid light line]   has the same functional form as in Figure 1, but is smaller, due to smaller CB and LB.Long-term   supply [line with markers] is much smaller than in Figure due to larger LA; short-term investor supply [dashed line] is comparable in magnitude to LB in Figure 1.With the given parameters supply is again initially smaller than demand, and prices     I.
rise in near-future time periods.In comparison with Section IV.l, investor B is much more a short-term trader, given that Ce, Le, and investor B time constant are all smaller.
Figure 4 shows the resulting price/volume chart calculated from the model equations in Section II, using the initial parameters specified for Figure 3. Ct 30% for this example.A very realistic climax sell-off scenario is generated, followed by clear change to bullish trend.Generation of this scenario is again consistent with arguments of technical analysis.Overall sentiment is bearish, characterized by relatively large R and presence of only short-term traders and "strong hands" value investors (large LA).But total number of shares trading by A and B (1.7+3.3+1.1 =6.1) is lower than in Section IV.l, so that long-term funda- mentals are more bullish.Early price advances are not sustained.A final ascending-triangle bottom, a familiar oscillatory pattern from technical analysis, allows shares to be accumulated by "strong hands" and a bullish trend is established.As in real price charts, volume is high on the initial sharp sell-off, but less on successive price drops.
A slight inflection is visible in the price chart where prices rise through initial levels [time (t)260].Absence of more congestion at this price level, and the smoothness of the price curve, suggests that Figure 4, like Figure 2, is more characteristic of shorter-term price action with shorter times for development of support and resistance levels.
IV.3.Cup-and-Handle Pattern Figure 5 shows a third and final price chart.Supply and demand functions are not shown for this example.Original purchases are 7.2 shares at 43 by A and 12.8 shares at 46 by B. For A and B respectively, initial moving-average prices are 45 and 46; time constants are 94 and 20.Other parameters are: CA= 240, C.: 14, R:7.3%, LA= 16%, L,=5.8% and n:3.5.Several para- meters and exponent n (: 3.5) of price dependence are the same as for Figures and 2; R and the time constant for investor A are smaller.Total number of shares ( 20) is between the totals for the preceding two scenarios in Sections IV.1 and IV.2, implying a neutral to moderately bullish market environment given that several other parameters are the same.The actual price/volume chart calculation in Figure 5 confirms the bullish environment and reproduces the cup-and-handle pattern discussed extensively by O'Neil (1995) in connection with bullish stock situations.Ct-22% for this exam- ple.After an initial jump of prices upward, prices J.K. WANG settle between $49 and $50, then settle back down results generated in Section IV are expected to on lower volume into a rounded cupor saucer- be reproducible with appropriate modifications of shaped formation.After a few irregular tests of the various constant parameter values.Results of bottom (around $46), prices retest the initial high variations in Eqs. ( 4)-( 6), and interpretation in at $50, settle in the cup handle just above, then terms of investor behavioral characteristics, are climb further upward.Model calculation results discussed in another paper by Wang (preprint).indicate that A investors sell almost all of their As mentioned in the Introduction, the model shares by the end of the breakout from the pattern equations are elaborated from equations studied handle; most selling is at the $50 resistance level, by Day (1997), with which he modeled market Computational limitations prevented longer-term price response to excess supply/demand and re- study of the development of this scenario.Presulting support/resistance levels.With its con- sumably, parameters eventually change over very stant supply and demand functions Day's model long periods of time; or very long-term investors is appropriate only over very short time intervals (including insiders and a company itself through and when volume is small compared to total stock secondary offerings and buybacks) may begin to supply.The present paper incorporates effects on distribute their shares after an extended bullish investor sentiment of trading history and limited period, stock supply into the model, resulting in dynami- cally evolving and interacting supply and demand and support/resistance levels.Price jumps, sup- .DISCUSSION OF RESULTS port/resistance levels, and volume now all depend on past prices and trading volume in a complex, The results of this paper demonstrate that realistic non-reproducing manner.Relatively straightformarket price patterns are reproduced within a ward model equations and variables generating consistent mathematical model [Eqs.
(1)-( 5)] these results provide a connection between em- based on principles of technical analysis.Arbitrary pirical observations of technical analysts and changes in initial parameters lead to different general principles proposed by behavioral econo- patterns, confirming that certain patterns in mists.Functions and parameters are quantified technical analysis have strong significance and defining sentiment, share supply, and investor imply specific market conditions.Sensitivity to character.Resulting price and volume charts allow initial parameters, ostensibly lack of robustness, study of how these characteristics interact in actually confirms the implicit uncertainty asso- markets.ciated with the "art" of chart analysis.Certain Several thoughts arise regarding future study price activity may strongly indicate bearishness, of this model.In Section IV I have attributed for example, but the exact time and price of the unrealistic smoothness of price and volume in "top" can only be projected with some uncer- chart calculations as due to limits in computatainty.Different combinations of parameters can tional detail; support and resistance levels are not generate the same patterns on different time scales, well enough defined.As noted in earlier para- This is consistent with the usefulness of chart graphs, results have been obtained by Wang technical analysis on many different time scales.
(preprint) implying that realistic price fluctuations It should be noted that the functional forms can be associated with deterministic variations of supply and demand in Eqs.(4b) and (5b), in the supply functions.The smoothness also sug- respectively, were assumed solely for simplicity gests the intuition that timing of real trades of expression.If functional expressions with simi- depends probabilistically on supply and demand lar asymptotic behavior were substituted (e.g., functions.That is, given supply and demand 2(tan-7rx/2)/r instead of tanh x), the qualitative functions calculated in Eqs. ( 3)-( 6), trading volume also depends on some stochastic factor multiplied times supply/demand.Such a formula- tion would be reminiscent of quantum statistical models of materials, where electrons within a crystal react and change states depending both on probability and on fixed material properties.
Extensive work remains in order to develop understanding of very long-term free market price dynamics.In Figures 2, 4 and 5, prices diverge either up or down beyond chart boundaries; other parameter assumptions (not discussed) resulted in convergence towards finite constant values.Such price behavior is consistent with that observed over intermediate but not very long time scales in real markets.For most real market securities, different chart formations eventually occur over the extended price history, all of which must be associated with different sets of parameters.What are the equations determining long-term transfor- mations between "constant" parameter sets in terms of price and volume history?What are the global parameters and equations governing flow of money or investor demand among different stocks or sectors, leading to sector rotation, rela- tive strength and correlations?
In closing, I note that this paper has focused on the validity of technical analysis based on classical chart formations.For the future, more recently developed chart techniques, such as MACD, stochastics, point-and-figure, Gann theory, should be evaluated in conjunction with this model.Are there relationships governing the model parameters that systematically generate Fibonacci series ratios commonly identified in longer-term charts?For more thorough analysis of price patterns, the current model also must be extended to generate bar (and candlestick) charts, involving a succes- sion of time intervals separated by closed market periods.A related issue would then be how to define price gaps in chart calculations.It would also be of interest to incorporate bid/ask spreads and pricing by discrete fractions in the model.Clearly, the model presented is at an early stage of development and can be further improved in many ways.
Computer resources used to produce this paper were made available by Pinetree Management, Inc.

Figure
Figureshows example supply and demand

FIGURE
FIGURESupply and demand functions [volume V (number of shares) versus price P] at t--0 based on Eqs.(4)-(5) and indicated initial parameters in Table generatingHead-and-Shoulders price pattern.

FIGURE 2
FIGURE 2 Head-and-Shoulders price pattern [price P and volume V versus time t] generated from Eqs. (1)-(5) and indicated

FIGURE 3
FIGURE 3 Supply and demand functions [volume V (number of shares) versus price P] at 0 based on Eqs.(4)-(5) and indicated initial parameters inTable generating Climax Sell-Off price pattern.

FIGURE 4
FIGURE 4 Sell-Off price pattern [price P and volume V versus time t] generated from Eqs. (1)-(5) and indicated initial parameters in TableI.

FIGURE 5
FIGURE 5 Cup-and-Handle price pattern [price P and volume V versus time t] generated from Eqs. (1)-(5) and indicated initial parameters in TableI.
Table generating Head-and-Shoulders price pattern.
Table generating Climax Sell-Off price pattern.