Code:
public static void shortNBuy(Vector<Stock> stocks, Vector<String> stockNames, int[] buys, int[] shorts,
int perc, Vector<String> days, Vector<Double> dailyReturn)
{
//Initialization
Vector<Stock> dayStocks = new Vector<Stock>();
Vector<Stock> prevBuy = new Vector<Stock>();
Vector<Stock> prevShort = new Vector<Stock>();
Vector<Stock> newBuy = new Vector<Stock>();
Vector<Stock> newShort = new Vector<Stock>();
int prevDaySize = 0;
for(int date = smallestDay; date < biggestDay; date++)
{
//If it is not the first day, set the previous day's lists.
if(date != smallestDay)
{
prevBuy = new Vector<Stock>(newBuy);
prevShort = new Vector<Stock>(newShort);
prevDaySize = dayStocks.size();
}
//reset day's lists.
newBuy = new Vector<Stock>();
newShort = new Vector<Stock>();
dayStocks = getOneDate(stocks, date);
if(dayStocks.size() > 1 && date != biggestDay)
{
int percToTrade = dayStocks.size() / perc;
//Cannot work with 0 buy/sell.
if(percToTrade <= 0)
percToTrade = 1;
//Buy the bottom percentage.
for(int i = 0; i < percToTrade-1; i++)
{
String ticker = dayStocks.elementAt(i).getTicker();
newBuy.add(dayStocks.elementAt(i));
int index = stockNames.indexOf(ticker);
buys[index] += 1;
}
//Short the top percentage.
for(int i = dayStocks.size() - percToTrade-1; i < dayStocks.size(); i++)
{
if(i < 0)
break;
String ticker = dayStocks.elementAt(i).getTicker();
newShort.add(dayStocks.elementAt(i));
int index = stockNames.indexOf(ticker);
shorts[index] += 1;
}
}
//If it is the first day, there are no returns to evaluate.
if(date == smallestDay || prevDaySize <= 0 || prevBuy.size() <= 0 || prevShort.size() <= 0)
continue;
double prevAvgBuy = 0.0, prevAvgShort = 0.0;
for(int i = 0; i < prevBuy.size(); i++)
{
prevAvgBuy += prevBuy.elementAt(i).getRet();
}
for(int i = 0; i < prevShort.size(); i++)
{
prevAvgShort += prevShort.elementAt(i).getRet();
}
prevAvgBuy /= prevBuy.size();
prevAvgShort /= prevShort.size();
//To get return, bottom stocks (bought) - top stocks (short).
//Because bottoms stocks are negative in data, you add them.
//EX: -1 + 2 = 1 / Low - High.
double retu = prevAvgBuy + prevAvgShort;
days.add(""+date);
dailyReturn.add(retu);
}
}
Bookmarks