{"id":8457,"date":"2020-10-16T22:57:31","date_gmt":"2020-10-16T20:57:31","guid":{"rendered":"https:\/\/quantpedia.com\/?p=8457"},"modified":"2025-06-04T14:01:14","modified_gmt":"2025-06-04T12:01:14","slug":"the-knapsack-problem-implementation-in-r","status":"publish","type":"post","link":"https:\/\/vvv.quantpedia.com\/es\/the-knapsack-problem-implementation-in-r\/","title":{"rendered":"The Knapsack problem implementation in R"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Our own research paper <a href=\"https:\/\/ssrn.com\/abstract=3650163\">ESG<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/ssrn.com\/abstract=3650163\" target=\"_blank\"> Scores<\/a><a href=\"https:\/\/ssrn.com\/abstract=3650163\"> and Price Momentum Are More Than Compatible<\/a> utilized the Knapsack problem to <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/quants-look-on-esg-investing-strategies\/\" target=\"_blank\" rel=\"noreferrer noopener\">make the ESG strategies more profitable<\/a> or <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/esg-scores-and-price-momentum-are-more-than-compatible\/\" target=\"_blank\" rel=\"noreferrer noopener\">Momentum strategies<\/a> significantly less risky.  The implementation of the Knapsack problem was created in R, using slightly modified Simulated annealing optimization algorithm. Recently, we have been asked about our implementation and the code. The code is commented and probably could be implemented more efficiently (in R or in another programming language). For example, R is more efficient with matrices, but the code would not be that &#8220;straightforward&#8221;. Lastly, the most important tuning parameter is the temperature decrease (the probability of accepting a new solution is falling with the rising number of iterations). Feel free to <a rel=\"noreferrer noopener\" href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/quantpedia-mission\/\" target=\"_blank\">contact<\/a><a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/quantpedia-mission\/\"> us<\/a> with any questions or new ideas!<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Commented and ready to be copied code:<\/p>\n\n\n\n<pre>##### Simulated annealing Knapsack optimization ####<br>### this parametrization minimizes the value ###<br>### in the application, pick the vector of values accordingly ### <br>### for example the inverse of ESG scores ###<br><br>#m is vector of weights<br>#c is vector of values<br>#M is weight cap<br>#numbit is number of iterations, 100000 was used in the Knapsack ESG-Momentum<br>#par is a plotting paramter, if the plotting is enabled, plots and returns each par\u00b4s result<br>#tau is initial temperature<br>#pt controls the temperature decrease; decrease is set to be linear and pt was set to be 2.5 in the paper<br>#plotting - logical, TRUE if plotting is enabled, FALSE if disabled<br>knap.sann&lt;-function(m,c,M,numbit,par,tau,pt,plotting){<br>#vectors for plotting<br>weight&lt;-rep(0,numbit\/par)<br>value&lt;-rep(0,numbit\/par)<br>#setting the n <br>n&lt;-length(m)<br>x&lt;-rep(0,n)<br>#solutions<br>bestval&lt;-0<br>bestsol&lt;-c(0)<br>for (i in 1:numbit){<br>y&lt;-x<br>#generating random item <br>p&lt;-sample(1:n,1)<br>y[p]&lt;-abs(y[p]-1)<br>#new item is placed into knapsack (or dropped from knapsack) only if it fits into knapsack, <br>#if it does not fits,<br>#one item from the knapsack is taken into hand and either chosen item (p) or item in the hand (hand) is dropped<br>while (t(y)%*%m&gt;M){<br>hand&lt;-sample(x,1)<br>y[sample(c(p,hand),1)]&lt;-0<br>}<br>#Simulated annealing part; section three in the paper ESG Scores and Price Momentum Are More Than Compatible <br>if (runif(1) &lt; exp((t(x)%*%c - t(y)%*%c) \/ (tau \/ (pt*i)))) {<br>if(t(y)%*%c&gt;bestval){<br>bestval&lt;-t(y)%*%c<br>bestsol&lt;-y<br>}<br>x &lt;- y<br>}<br>#plotting<br>if(plotting==TRUE){<br>if(i %% par ==0){<br>print(t(x)%*%c)<br>print(t(x)%*%m)<br>weight[i\/par]&lt;-t(x)%*%m<br>value[i\/par]&lt;-t(x)%*%c<br>}<br>}<br>}<br>if(plotting==TRUE){<br>osX&lt;-seq(1:length(weight))<br>par(mfrow=c(2,1))<br>plot(osX,weight)<br>lines(osX,rep(M,length(osX)),col=\"red\")<br>plot(osX,value)<br>}<br>#results<br>results &lt;- list()<br>results$first &lt;- bestsol<br>results$second &lt;- bestval<br>return(results) <br>#return(bestsol)<br>}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Author: <a href=\"https:\/\/www.linkedin.com\/in\/matus-padysak-14a44b185\/\">Matus Padysak<\/a>, Senior Analyst, Quantpedia.com<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"block-854363cc-8450-4dc0-a06a-c737766e9431\"><strong>Are you looking for more strategies to read about? <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/sign-up-for-our-newsletter\/\">Sign up for our newsletter<\/a> or visit our <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/blog\/\">Blog<\/a> or <a href=\"http:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/Screener\">Screener<\/a><\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"block-65925002-6290-4d3b-b5cd-f3a277851ec8\"><strong>Do you want to learn more about Quantpedia Premium service? Check <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/how-it-works\/\">how Quantpedia works<\/a>, <a href=\"http:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/Home\/About\">our mission<\/a> and <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/pricing\/\">Premium pricing offer<\/a>.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"block-34bf63ae-5a22-40a3-aeb4-769374e833d8\"><strong>Do you want to learn more about Quantpedia Pro service? Check its <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/how-it-works\/quantpedia-pro\/\">description<\/a>, watch <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/how-it-works\/quantpedia-explains\/\">videos<\/a>, review <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/how-it-works\/quantpedia-pro-reports\/\">reporting capabilities<\/a> and visit our <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/pricing-pro\/\">pricing offer<\/a>.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"block-21942b3a-14d9-4c0f-b8ef-04d64675e253\"><strong>Are you looking for historical data or backtesting platforms? Check our list of&nbsp;<a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/links-tools\/?category=algo-trading-discounts\">Algo Trading Discounts<\/a><\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Would you like free access to <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/pricing\/\" title=\"\">our services<\/a>? Then, <a href=\"https:\/\/lightspeed.com\/lp\/quantpedia-lightspeed-financial-services-group-one-free-year-promotion\" title=\"\">open an account with Lightspeed<\/a> and enjoy one year of Quantpedia Premium at no cost.<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"block-4c45d6c9-c8dd-4283-8743-bf573cfa4d45\"><strong>Or follow us on:<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"block-476e95ed-31a5-4c4d-b701-5203f9fb2e24\"><strong>Facebook <a href=\"https:\/\/www.facebook.com\/groups\/quantstrategies\">Group<\/a>, Facebook <a href=\"https:\/\/www.facebook.com\/quantpedia\/\">Page<\/a>, <a href=\"https:\/\/twitter.com\/quantpedia\">Twitter<\/a>, <a href=\"https:\/\/www.linkedin.com\/company\/quantpedia\">Linkedin<\/a>, <a href=\"https:\/\/quantpedia.medium.com\/\">Medium<\/a> or <a href=\"https:\/\/www.youtube.com\/channel\/UC_YubnldxzNjLkIkEoL-FXg\">Youtube<\/a><\/strong><\/p>\n\n\n","protected":false},"excerpt":{"rendered":"<p><strong>Our own research paper <a href=\"https:\/\/papers.ssrn.com\/sol3\/papers.cfm?abstract_id=3650163\"><strong>ESG Scores and Price Momentum Are More Than Compatible<\/strong><\/a> utilized the Knapsack problem to <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/quants-look-on-esg-investing-strategies\/\"><strong>make the ESG strategies more profitable<\/strong><\/a> or <a href=\"https:\/\/\\\/\\\/new-fmhwbzh6ghd9hede.swedencentral-01.azurewebsites.net\/esg-scores-and-price-momentum-are-more-than-compatible\/\"><strong>Momentum strategies<\/strong><\/a> significantly less risky. The implementation of the Knapsack problem was created in R, using slightly modified Simulated annealing optimization algorithm. Recently, we have been asked about our implementation and the code. The code is commented and probably could be implemented more efficiently (in R or in another programming language). For example, R is more efficient with matrices, but the code would not be that \u201cstraightforward\u201d. Lastly, the most important tuning parameter is the temperature decrease (the probability of accepting a new solution is falling with the rising number of iterations). <\/strong><\/p>","protected":false},"author":21001,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[155,161,159],"class_list":["post-8457","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-alternative-data","tag-esg-investing","tag-own-research"],"_links":{"self":[{"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/posts\/8457","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/users\/21001"}],"replies":[{"embeddable":true,"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/comments?post=8457"}],"version-history":[{"count":0,"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/posts\/8457\/revisions"}],"wp:attachment":[{"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/media?parent=8457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/categories?post=8457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/vvv.quantpedia.com\/es\/wp-json\/wp\/v2\/tags?post=8457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}