Quantitative research or backtest requires masses of historical data. When it comes to test a strategy on equities, adjusted stock prices would be more preferrable in order to have an accurate profit and loss, without adjusting position and the parameters of the model.
One of my data collection program, which automatically fetches data from Bloomberg using its API, supports getting adjusted prices. There are only three lines of code that enable this feature, with setting three parameters adjustmentNormal, adjustmentAbnormal, and adjustmentSplit to true.
ServicerefDataService=session.getService("//blp/refdata");Requestrequest=refDataService.createRequest("HistoricalDataRequest");.....// Remember to set the three parameters to truerequest.set("adjustmentNormal",true);request.set("adjustmentAbnormal",true);request.set("adjustmentSplit",true);
Bear in mind that adjustmentNormal, adjustmentAbnormal, and adjustmentSplit should be explicitly set to false if you want original stock price.
Here is my implementation of P&L calculation for real-time marketdata and trade log streaming, as you can see from the two member functions: def update_by_tradefeed() and def update_by_marketdata().
The traded quantity is a signed number: positive for buy and negative for sell. That means the net position is negative if the transactioin short sells some products.
If the trade feed takes close action, need to be careful of whether the close quantity is larger than the net position. In this case, the average open price should also be updated to the close price.
The PnlSnapshot class for a product:
classPnlSnapshot:def__init__(self,ticker,buy_or_sell,traded_price,traded_quantity):self.m_ticker=tickerself.m_net_position=0self.m_avg_open_price=0self.m_net_investment=0self.m_realized_pnl=0self.m_unrealized_pnl=0self.m_total_pnl=0self.update_by_tradefeed(buy_or_sell,traded_price,traded_quantity)# buy_or_sell: 1 is buy, 2 is selldefupdate_by_tradefeed(self,buy_or_sell,traded_price,traded_quantity):# buy: positive position, sell: negative positionquantity_with_direction=traded_quantityifbuy_or_sell==1else(-1)*traded_quantityis_still_open=(self.m_net_position*quantity_with_direction)>=0# net investmentself.m_net_investment=max(self.m_net_investment,abs(self.m_net_position*self.m_avg_open_price))# realized pnlifnotis_still_open:# Remember to keep the sign as the net positionself.m_realized_pnl+=(traded_price-self.m_avg_open_price)*min(abs(quantity_with_direction),abs(self.m_net_position))*(abs(self.m_net_position)/self.m_net_position)# total pnlself.m_total_pnl=self.m_realized_pnl+self.m_unrealized_pnl# avg open priceifis_still_open:self.m_avg_open_price=((self.m_avg_open_price*self.m_net_position)+(traded_price*quantity_with_direction))/(self.m_net_position+quantity_with_direction)else:# Check if it is close-and-openiftraded_quantity>abs(self.m_net_position):self.m_avg_open_price=traded_price# net positionself.m_net_position+=quantity_with_directiondefupdate_by_marketdata(self,last_price):self.m_unrealized_pnl=(last_price-self.m_avg_open_price)*self.m_net_positionself.m_total_pnl=self.m_realized_pnl+self.m_unrealized_pnl
In C++, it is a good practice to evaluate if the passed instance is exactly itself at the very beginning of defining a operator= method:
classPriceCalculator{// ...
};classStock{// ...
Stock&operator=(constStock&rhs);PriceCalculator*pc;};Stock&Stock::operator=(constStock&rhs){if(this==&rhs)return*this;// best practice
deletepc;pc=newPriceCalculator(*rhs.pc);// still problematic!
return*this;}
Price calculation is an essential part of online stores. The value of a price changes under various conditions, such as adding tips, some percentages off, or tax refund. It is usually re-calculated in run-time once online customers select different plans or purchase extra services. In this sense, a dynamic calculator that is flexible enough to be called by client programmers is appealing.
Air ticket is a typical example. The price at first sight is a raw price, remaining to be updated by adding tax, insurance, etc. In essence, adding features to a price acts like extending properties or methods to an object. Using prototype chain can accomplish it. The code below defines some features at the outset. These “features” can be easily integrated into an existing object by a shared method: addFeature(), which creates a new object inherited from the existing object.
...
As browsers parse and render page code sequentially, the parsing and execution of Javascript (whether inline or external) code might block rendering the page and downloading other resources (e.g. images) if the js code was not properly placed. Creating dynamic script elements, due to its intrinsic asynchronous loading pattern, has been widely recognized as an efficient approach to nicely work around this problem (non-blocking).
In order to load a collection of external js files by this manner, I wrote a simple loader that takes an array of filenames, in which the js files are parsed and executed in order.
...
The constructor property could be very useful when the type of an variable needs to be identified. In constructing a class and its instance, or even establishing inheritance by using prototypes, constructor deserves more attention because it can be changed by default or by you.
An instance never has a constructor property unless it is manually given. When the constructor of an instance is accessed, it is traced in the whole prototype chain.
If there is no any prototype chain manually attached to the function (class), the constructor of an instance is the class itself.
Compressed script files are essential components to a website with high performance. This is extremely true for single-page web apps that strongly rely on a bunch of js files.
I wrote jcompressor, a node package that is capable of compressing all .js files in a folder. With just several hits you can build all .js files in minimal size for production environment at ease. Check out jcompressor on GitHub: jcompressor.
I tried to use npm to install a node module globally on Ubuntu. Some errors occurred and I found the major reason was that the version of node.js was a bit too old. Fortunately, it is quite straightforward to update node.js. In Terminal issue the following command lines:
The memory management seems a neglectable issue for JavaScript programmers since the garbage collector lies there to automatically release the unnecessary memory. However, it is also very easy to write some code that leads to memory leak, especially when dealing with the event delegation in DOM. An overview of the mechanism of Garbage Collection in JavaScript is beneficial when we want to probe our code to inspect some potential memory problems.
Consulting the article here, I made a summary about the principles used to release the allocated memory. There are three major criteria for judging if a variable can be destroyed, indicating different number of variables whose memory should be collected.
In Javascript, an object doesn’t hold the slice() method, while arrays and strings do. Employing apply or call can easily make slice() work for objects, e.g. Array.prototype.slice.call(arguments, 1), which is a commonly used manner to cope with the arguments object in a function. However, the following usage is a bit weird:
//an object with non-numerical keysvarobj1={name:'lichgo',age:24};[].slice.call(obj1,1);//[]//another object with numerical keys (the same as arguments object)varobj2={0:'lichgo',1:24};[].slice.call(obj2,1);//[]
When executing the codes wrapped in with(object) statement of Javascript, the execution context’s scope chain contains at least three variable objects, with the passed object’s scope on the top of the scope chain while the activation object and global object following. The codes below demonstrate how the program operates under the scope chain.
The result of the following simple javascript codes may be a bit confusing.
varname='Jason';//Anonymous function 1 (AF1)(function(){console.log(name);//undefinedvarname='Eric';})();
So what is the exact reason behind? Some programmers might argue that it is because the anonymous functions do not share the same scope with the global environment outside, so the variable name defined outside is invisible to the anonymous function here. It is not true. The codes below prove my answer.
...