R-code

February 14, 2012

Here is some quick documentation for the code:
Code is designed to calculate and return vectors of expected prices and a range based on standard deviations fitting the data to the following model:
dx=A*t+B*dz; where dz=є√dt and є~N(0,sd^2)

Quick documentation for the functions:

calcSDreturn <- function(tick, t)
%% Calculates SD of returns based on the last t data points in the tick object, returns a single value

calcMeanreturn <- function(tick, t)
%% Calculates Mean of returns based on the last t data points in the tick object, returns a single value.

expectedValue <- function(tick,t,f)
%% Creates a vector of f expected prices, from starting the current day, projecting out into the future, based on the last t days of data.

upperBoundCI <- function(tick,t,sd,f)
%% Creates a vector of f expected prices, sd number of standard deviations above the mean, projected out f periods into the future, based on the last t days of data.

lowerBoundCI <- function(tick,t,sd,f)
%% Creates a vector of f expected prices, sd number of standard deviations below the mean, projected out f periods into the future, based on the last t days of data.

Once you have cut and paste the entire thing into the R console, you only need to select a ticker and run the last function. I have included examples with returns at the bottom:

install.packages(“quantmod”)
library(quantmod)

getSymbols(“SPY”)

calcSDreturn <- function(tick, t)
{
p<- as.double(tick[,4])
if (t > (length(p)-2))
{
stop(“The requested time period is longer than that of the data”)
}
rv<-vector()
for (i in 2:length(p))
{
rv[i]<-100*(log(p[i],base=10)-log(p[i-1],base=10))
}
r<-vector()
for (i in t:1)
{
r[i] <- rv[length(rv)-i+1]
}
sd<-sqrt(var(r))
return(sd)
return(rv)
}

calcMeanreturn <- function(tick, t)
{
p<- as.double(tick[,4])
if (t > (length(p)-2))
{
stop(“The requested time period is longer than that of the data”)
}
rv<-vector()
for (i in 2:length(p))
{
rv[i]<-100*(log(p[i],base=10)-log(p[i-1],base=10))
}
r<-vector()
for (i in t:1)
{
r[i] <- rv[length(rv)-i+1]
}
m<-mean(r)
return(m)
}

expectedValue <- function(tick,t,f)
{
p<- as.double(tick[,4])
a <- calcMeanreturn(tick, t)/t
x <-vector()
x[1]<-p[length(p)]
for(i in 2:f)
{
x[i]<-x[i-1]+a*x[i-1]
}
index<-last(index(tick))+(1:f)
z<-as.xts(x,index)
return(z)
}

upperBoundCI <- function(tick,t,sd,f)
{
p<- as.double(tick[,4])
a <- calcMeanreturn(tick, t)/t
b <- calcSDreturn(tick, t)/t
x<-vector()
x[1]<-p[length(p)]
for(i in 2:f)
{
x[i]<-x[i-1]+a*x[i-1]+(b*sd)*x[i-1]
}
index<-last(index(tick))+(1:f)
z<-as.xts(x,index)
return(z)
}

lowerBoundCI <- function(tick,t,sd,f)
{
p<- as.double(tick[,4])
a <- calcMeanreturn(tick, t)/t
b <- calcSDreturn(tick, t)/t
x<-vector()
x[1]<-p[length(p)]
for(i in 2:f)
{
x[i]<-x[i-1]+a*x[i-1]-(b*sd)*x[i-1]
}
index<-last(index(tick))+(1:f)
z<-as.xts(x,index)
return(z)
}

plotGBM<-function(tick,t,f,sd)
{
u<- upperBoundCI(tick,t,sd,f)
l<- lowerBoundCI(tick,t,sd,f)
p<- expectedValue(tick,t,f)
plot(c(p,l,u),type=’p’, main=”GBM Price Projection”, xlab=”Current day + t”, ylab=”Price”)
}

Example: I want to calculate the GBM model of returns in TLT for the next 20 trading days based on the last 60 trading days of data with a variance of one standard deviation from the mean:
getSymbols(“TLT”)
plotGBM(TLT,60,20,1)

This will return:
http://i.imgur.com/IsGu4.png

Using much more data for our projections will significantly lower the deviation:
plotGBM(TLT,300,20,1)

This will return:
http://i.imgur.com/1W2Qo.png

Several problems at the moment are:
1) I have not figured out how to do the indexing in a way that tracks the days the market is actually open, hence right now the x-axis is only an index of days out into the future rather than price on an actual trading day.
2) I have not been able to attach these plots to the chartSeries or any other candlestick plotting functions in R so right now I am stuck with just expected values verses those and underlying prices.

To adapt this code to any model you would like, you only need to change the formula used by the calcMeanreturn() and calcSDreturn() functions. Alternatively, if you wish to vary the way the model forecasts the stock prices you can change the loops in the expectedValue() and lowerBoundCI()/upperBoundCI() functions.

Advertisements

Charting Fix January 23rd

January 24, 2012

First I want to say I see far fewer attractive set ups today than I did last week. I remain stubbornly short via TZA with an average cost of just over $24 and one bullet left in the barrel to add if we get a final spike. Now that that is out of the way, here are some attractive looking charts I see.


Daily Charting Fix

January 19, 2012

Here are the charts I have found tonight. The theme is short squeezes. None of the charts posted here have under 10% of the float short, so there is the potential for explosive upside. I did not check earnings, nor fundamentals, I am posting these as technical setups only. If you like my work, please RT and/or follow me on twitter. Appreciated.


Late Night Charting

January 18, 2012

Here are some of the more attractive set ups I am seeing from the list of stocks I follow (by no means all of them), in addition to the charts below I also like the consolidation in major Canadian banks, notably TSE:RY TSE:CM TSE:BNS. Having said that there have been a lot of failed breakouts with indices struggling to make new highs and personally I am bearish on my outlook. Nevertheless practice makes perfect and so charting is vital. Here are the charts in Album format:


Some stocks to watch

January 10, 2012

Here are some set ups I see. There appear to be a lot of apparently bullish consolidation patterns out there in the charts, but on the flip side some leadership is breaking down. Volume is non-existent, and we also have indices buoyed by massive squeezes in some heavily shorted names. Uploaded as a gallery for your browsing convince. Notes are on chart where I have thoughts.


Employment Situation Summary breakdown

January 6, 2012

From http://www.bls.gov/news.release/empsit.nr0.htm

The report is unchanged, other than the boldingwhich I have added to place emphasis where I think it is relevant.

In summary:

– Unemployment seems to be declining while labor force participation continues its decline.

– A large percentage of jobs were added in as seasonal hiring, as we would expect.

– The large annual increase in retail and leisure/hospitality does not bode well in the long run for “growing” out of a deficit.

– Manufacturing finally saw an uptick in both employment and work hours. This needs to be sustained for economic prosperity.

– Government employment fell as states and municpalities struggle with their own budget issues, expect this trend to continue in 2012.

– 2.5 million people, who are acknowledged as unemployed, are simply not counted. This puts the true rate at around 10.13% when these people are accounted for.

Employment Situation Summary

THE EMPLOYMENT SITUATION — DECEMBER 2011  Nonfarm payroll employment rose by 200,000 in December, and the unemployment rate, at 8.5 percent, continued to trend down, the U.S. Bureau of Labor Statistics reported today. Job gains occurred in transportation and warehousing, retail trade, manufacturing, health care, and mining.

Both the number of unemployed persons (13.1 million) and the unemployment rate (8.5 percent) continued to trend down in December.

The unemployment rate has declined by 0.6 percentage point since August. (See table A-1.)

Among the major worker groups, the unemployment rate for adult men decreased to 8.0 percent in December. The jobless rates for adult women (7.9 percent), teenagers (23.1 percent), whites (7.5 percent), blacks (15.8 percent), and Hispanics (11.0 percent) showed little change. The jobless rate for Asians was 6.8 percent, not seasonally adjusted. (See tables A-1, A-2, and A-3.)

The number of long-term unemployed (those jobless for 27 weeks or more) was little changed at 5.6 million and accounted for 42.5 percent of the unemployed. (See table A-12.)

The civilian labor force participation rate (64.0 percent) and the employment- population ratio (58.5 percent) were both unchanged over the month. (See table A-1.)

The number of persons employed part time for economic reasons (sometimes referred to as involuntary part-time workers) declined by 371,000 to 8.1 million in December. These individuals were working part time because their hours had been cut back or because they were unable to find a full-time job. (See table A-8.)

About 2.5 million persons were marginally attached to the labor force in December, little different from a year earlier. (The data are not seasonally adjusted.) These individuals were not in the labor force, wanted and were available for work, and had looked for a job sometime in the prior 12 months. They were not counted as unemployed because they had not searched for work in the 4 weeks preceding the survey. (See table A-16.)

Among the marginally attached, there were 945,000 discouraged workers in December, a decrease of 373,000 from a year earlier. (The data are not seasonally adjusted.) Discouraged workers are persons not currently looking for work because they believe no jobs are available for them. The remaining 1.6 million persons marginally attached to the labor force in December had not searched for work in the 4 weeks preceding the survey for reasons such as school attendance or family responsibilities. (See table A-16.)

Establishment Survey Data

Total nonfarm payroll employment increased by 200,000 in December. Over the past 12 months, nonfarm payroll employment has risen by 1.6 million. Employment in the private sector rose by 212,000 in December and by 1.9 million over the year. Government employment changed little over the month but fell by 280,000 over the year. (See table B-1.)

Employment in transportation and warehousing rose sharply in December (+50,000). Almost all of the gain occurred in the couriers and messengers industry (+42,000); seasonal hiring was particularly strong in December.

Retail trade continued to add jobs in December, with a gain of 28,000. Employment in the industry has increased by 240,000 over the past 12 months. Over the month, job gains continued in general merchandise stores (+13,000) and in clothing and clothing accessories stores (+11,000). Employment in sporting goods, hobby, book, and music stores fell by 10,000.

In December, manufacturing employment expanded by 23,000, following 4 months of little change. Employment increased in December in transportation equipment (+9,000), fabricated metals (+6,000), and machinery (+5,000).

Mining employment rose by 7,000 over the month. Over the year, mining added 89,000 jobs.

Health care continued to add jobs in December (+23,000); employment in hospitals increased by 10,000. Over the year, health care employment has risen by 315,000.

Within leisure and hospitality, employment in food services and drinking places continued to trend up in December (+24,000). Over the year, food services and drinking places has added 230,000 jobs.

Construction employment changed little in December. Within the industry, nonresidential specialty trade contractors added 20,000 jobs over the month, mostly offsetting losses over the prior 2 months.

Employment in professional and business services changed little in December for the second month in a row. The industry added 42,000 jobs per month, on average, during the first 10 months of 2011.

Government employment changed little in December but was down by 280,000 over the year. Job losses in 2011 occurred in local government; state government, excluding education; and the U.S. Postal Service.

The average workweek for all employees on private nonfarm payrolls increased by 0.1 hour to 34.4 hours in December. The manufacturing workweek increased by 0.1 hour to 40.5 hours. Factory overtime decreased by 0.1 hour to 3.2 hours. The average workweek for production and nonsupervisory employees on private nonfarm payrolls edged up by 0.1 hour to 33.7 hours. (See tables B-2 and B-7.)

In December, average hourly earnings for all employees on private nonfarm payrolls rose by 4 cents, or 0.2 percent, to $23.24. Over the past 12 months, average hourly earnings have increased by 2.1 percent. In December, average hourly earnings of private-sector production and nonsupervisory employees were unchanged at $19.54. (See tables B-3 and B-8.)

The change in total nonfarm payroll employment for October was revised from +100,000 to +112,000, and the change for November was revised from +120,000 to +100,000.


How deep does the rabbit hole go?

December 18, 2011

Via Barons regarding MF global customers silver and gold bullion now being seized by trustee.

 

The Silver Rush at MF Global
By ERIN E. ARVEDLUND
December 17, 2011

It’s one thing for $1.2 billion to vanish into thin air through a series of complex trades, the well-publicized phenomenon at bankrupt MF Global. It’s something else for a bar of silver stashed in a vault to instantly shrink in size by more than 25%.

That, in essence, is what’s happening to investors whose bars of silver and gold were held through accounts with MF Global.

The trustee overseeing the liquidation of the failed brokerage has proposed dumping all remaining customer assets—gold, silver, cash, options, futures and commodities—into a single pool that would pay customers only 72% of the value of their holdings. In other words, while traders already may have paid the full price for delivery of specific bars of gold or silver—and hold “warehouse receipts” to prove it—they’ll have to forfeit 28% of the value.

That has investors fuming. “Warehouse receipts, like gold bars, are our property, 100%,” contends John Roe, a partner in BTR Trading, a Chicago futures-trading firm. He personally lost several hundred thousand dollars in investments via MF Global; his clients lost even more. “We are a unique class, and instead, the trustee is doing a radical redistribution of property,” he says.

Roe and others point out that, unlike other MF Global customers, who held paper assets, those with warehouse receipts have claims on assets that still exist and can be readily identified.

The tussle has been obscured by former CEO Jon Corzine’s appearances on Capitol Hill. But it’s a burning issue for the Commodity Customer Coalition, a group that says it represents some 8,000 investors—many of them hedge funds—with exposure to MF Global. “I’ve issued a declaration of war,” says James Koutoulas, lead attorney for the group, and CEO of Typhon Capital Management.

At stake is an unspecified, but apparently large, volume of gold and silver bars slated for delivery to traders through accounts at MF Global, which filed for bankruptcy on Oct. 31. Adding insult to the injury: Of the 28% haircut, attorney and liquidation trustee James Giddens has frozen all asset classes, meaning that traders have sat helplessly as silver prices have dropped 31% since late August, and gold has fallen 16%. To boot, the traders are still being assessed fees for storage of the commodities…