3

my goal is to write an algorithm in Mathematica that will search for stocks whose current price is trading below or above 2 Standard Deviations of the Mean. I literally started to learn the program yesterday but I have been scouring the internet ever since for help. I have the code, but I am getting errors along the way. can someone help me? Below is my current code

Today = Date[]
StartDate = Today-{0,3,0,0,0,0}
NYSEMem = FinancialData["NYSE","Members"]
CurrentPrice = FinancialData[NYSEMem,"Price"]
HistoricalPrice = FinancialData[NYSEMem,{{StartDate},{Today}}]
StandardDeviation$ = StandardDeviation[HistoricalPrice]
MeanPrice = Mean[HistoricalData]
SellSignal = [MeanPrice]-[StandardDeviation$]*2
BuySignal = [MeanPrice]+[StandardDeviation$]*2
If[CurrentPrice>SellSignal,"Sell",False]
If[CurrenPrice<BuySignal,"Buy",False]
Sjoerd C. de Vries
  • 16,122
  • 3
  • 42
  • 94
Brandon
  • 31
  • 1
  • 2

2 Answers2

4

Very brave to jump straight in the deep waters, but I'd suggest trying to learn the basics first. You say you've been "scouring the internet for help" but did you tried Mathematica's on-board documentation center? It has thousands pages of help, just one key press away.

Anyway as to your code, a few tips:

  • Don't end a variable with a $. Though not wrong in principle, they are used for system variables
  • The line SellSignal = [MeanPrice]-[StandardDeviation$]*2, and the one following it contain function call brackets without corresponding function names. You probably don't intend to have these brackets there
  • The ,False part in If[CurrentPrice>SellSignal,"Sell",False] and the next line is unnecessary and can be deleted here
  • The earlier date calculation can be better done with the dedicated DatePlus function, which takes things like leap years etc. into account
  • You probably don't want to see all the output of all the lines. You may suppress output using ';' (which also acts to separate compound statements)
  • An asterisk for multiplication is unnecessary. A space will do, just as in math. a*b, a b, a 2, 2 a and 2a (without a space) are all correct multiplications.
  • The data you receive from some of the calls include both prices and dates. You are also trying to average the dates and find their standard deviation.
  • Though it is allowed to start a variable with an uppercase letter you better avoid doing that in order to prevent using Mathematica's own keywords (which all start with an uppercase letter).
  • I don't think your buy and sell signals are very smart. You might think of selling when prices are historically high, but you're doing it when they are above the historic low watermark.
  • Same for buying. Also, when current price is between your two signals the program provides conflicting advice.
  • You need a construction to repeat the calculations for every NYSE member

Some very very basic code to get you started:

StartDate = DatePlus[Date[], {-3, "Month"}];
NYSEMem = Select[FinancialData["NYSE", "Members"], (\[Not] StringMatchQ[#, ___ ~~ 
       "^" ~~ ___] &)]; (* Throw away indices *)
Do[
 currentPrice = Check[FinancialData[stock, "Price"], $Failed];
 historicalPrice = 
  Check[FinancialData[stock, {StartDate, Date[]}], $Failed];
 If[currentPrice == $Failed || historicalPrice == $Failed || 
   currentPrice == Missing["NotAvailable"] || 
   historicalPrice == Missing["NotAvailable"], 
  Continue[]]; (* Shamefully inadequate error handling *)
 standardDeviationPrice = StandardDeviation[historicalPrice[[All, 2]]];
 meanPrice = Mean[historicalPrice[[All, 2]]]; 
            (* Mean of the second column of the data matrix *)
 sellSignal = meanPrice + 2 standardDeviationPrice; 
             (* swapped + and - in these two lines, plug your own method here *)
 buySignal = meanPrice - 2 standardDeviationPrice;
 Print[stock, ": ", 
  If[currentPrice > sellSignal, "Sell", 
   If[currentPrice < buySignal, "Buy", "Neutral"]]];
 , {stock, NYSEMem}
 ]

Please note that Stackoverflow is intended for people who have faithfully tried to do their best to do some research in the problems they encounter. I have the feeling that you don't really meet this criterion. My urgent request is: read some basic introductory text about Mathematica (for instance Getting started and Core Language Overview).

Sjoerd C. de Vries
  • 16,122
  • 3
  • 42
  • 94
  • 2
    _"It has several thousands of pages of help, just one key press away."_ Read the documentation to find out which key :) – abcd Jun 07 '11 at 17:30
  • ;-) Just the key used in any other help system (F1 Windows, Help key, Macs) – Sjoerd C. de Vries Jun 07 '11 at 17:32
  • Thanks Man, What do I need to do to have it list the stings I want? – Brandon Jun 07 '11 at 17:47
  • @Brandon Also, please note that Mathematica v8 comes with a nice package for financial analysis. – Dr. belisarius Jun 07 '11 at 17:57
  • Thanks I just input the signals wrong thanks for pointing that out tome as that is what I initially intended for. how can I call for the prices without listing the dates? how do I construct it so that it repeats the calculations for every member?also how can i fix the conflicting buy sell signals? – Brandon Jun 07 '11 at 18:20
  • heres my updated code with your edits:today= Date[] startdate= today-{0,3,0,0,0,0} nysemem= FinancialData["NYSE","Members"]';' currentprice= FinancialData[nysemem,"Price"] historicalprice= FinancialData[nysemem,{{startdate},{today}}] standarddeviationprice= StandardDeviation[historicalprice] meanprice= Mean[historicalprice] sellsignal= meanprice+standarddeviationprice*2 buysignal= meanprice-standarddeviationprice*2 If[currentprice>sellsignal,"Sell"] If[currenprice – Brandon Jun 07 '11 at 18:21
  • I really appreciate your help. Please believe me when I say I have been researching this nonstop for the past 2 days.. I even downloaded the mathematica cookbook and came to no conclusions, The amount of documentation is limited in the financial sense. Also having really never coded anything I am really struggling. I had been trying to model this in excel but the data feed from thinkorswim requires windows, and it doesnt give the true values of the 90 day SD anyhow. – Brandon Jun 07 '11 at 19:13
  • 1
    @brandon But you shouldn't really expect to be able to program in a programming language by jumping in an advanced function library without doing the basics first. You are prone to make all the usual (and avoidable) beginner mistakes. I added some links to basic help texts that you really should have seen. – Sjoerd C. de Vries Jun 07 '11 at 19:17
  • @brandon The Mathematica Cookbook isn't really meant for starters AFAIK. – Sjoerd C. de Vries Jun 07 '11 at 19:42
  • @Sjoerd I really had no intention of being able to thoroughly understand this application in such a short matter of time. I had downloaded the application over the weekend just for fun trying to see its capabilities mostly playing with the wolfram alpha input. However on monday I came into work and my boss noticed it on my computer and told me I needed to test it for certain applications by the end of the week to see if we could justify purchasing it. Now I can go to the basics and build a foundation. Thanks again for all the help. – Brandon Jun 07 '11 at 19:50
  • 1
    @Brandon If you're not an experienced programmer (and most programming languages don't count as "experience" here) it'll take you three to four weeks just to get along the basics. If your company needs that kind of help, it's better to contract someone knowledgeable. – Dr. belisarius Jun 07 '11 at 22:27
3

Here you have your program running:

Today              = Date[];
StartDate          = Today - {0, 3, 0, 0, 0, 0};
NYSEMem            = FinancialData["NYSE", "Members"];
NYSEMem            = NYSEMem[[1000 ;; 1001]];
CurrentPrice       = FinancialData[#, "Price"] & /@ NYSEMem;
HistoricalPrice    = FinancialData[#, {StartDate, Today}] & /@ NYSEMem;
StandardDeviation$ = StandardDeviation[#[[All, 2]]] & /@ HistoricalPrice;
MeanPrice          = Mean[#[[All, 2]]] & /@ HistoricalPrice;
SellSignal         = MeanPrice - StandardDeviation$*2
BuySignal          = MeanPrice + StandardDeviation$*2
Do[
   If[CurrentPrice[[i]] > SellSignal[[i]], Print["Sell ", NYSEMem[[i]]]];
   If[CurrentPrice[[i]] < BuySignal[[i]],  Print["Buy ",  NYSEMem[[i]]]],
 {i, 2}]

But please note I modified just the minimum to get it running without using idioms. This is not, by any standard, a good program. I did it just to let you play a little with it and learn some constructs.

HTH!

Dr. belisarius
  • 60,527
  • 15
  • 115
  • 190
  • This answer, together with **@Sjoerd's recommendations** should keep you on the path :) – Dr. belisarius Jun 07 '11 at 18:53
  • Thanks, It gives me a buy and sell for the same tickers though... Can you explain to me what certain things do within the program and why you use them? Remember I am completely new to this. ; – Brandon Jun 07 '11 at 19:04