Selling Stocks to Maximize Profit Algorithm – Greedy

I am trying to find an efficient algorithm that takes the prices p1 . . . pn and the function values f (1) . . . f (x) and determines the best way to sell x shares by day n.

Problem set-up.

I’m given the market prices for this stock over the next n days, let these be p1, p2 …pn. I also know the function f(y) which predicts the effect of selling y shares on a single day: if you sell y shares, it permanently decreases the price of the stock by f(y) from that day onwards.

So, if I sell y1 shares on day 1, the price per share for the transaction is p1 −f(y1) and the corresponding profit for that day is y1 · (p1 − f(y1)). If I then sell y2 shares on day 2, the price per share for that transaction is p2 − f(y1) − f(y2). Note that the decreases in price accumulates.

Assume that p1 …pn decreases monotonically and f(1) …f(x) increases monotonically. (Prices are generally going down and it goes down even more if I sell more shares). I can also assume that no matter how I sell your stocks, it is impossible for me to reduce the price of the stock to 0 (or negative numbers). (meaning, pi is larger than the cumulative decrease in price from any possible sequences of sales in the first i days) In other words, the algorithm finds integers y1 . . . yn, where yi corresponds to the number of shares sold on day i, such that:

  • All x shares are sold: 􏰀ni = 1 yi = x.
  • The total profit is maximized.

I know some about the stereotypical “buy-sell stocks” algorithm, but this seems like a bit of a different beast. I think this might be a greedy algorithm that takes a graph. Anything will help 🙂

Facebook Marketplace Accounts are in stocks $15

Our provided services are:
Instant Delivery after getting payment. Sometimes it may take Maximum 15 min – 2 Hours (depend on quantity).
All Sales are final. No refunds are available after purchase.
100% replacement within 24 hours.
Accessible from any country.
All accounts are manually created & full fresh.

Price is 15$ per account.

Skype – GoldRoger3636

Payment Method: Paypal, BTC , payoneer

Sortings stocks into quantiles based on their signal

This function sorts stocks into quantiles. To do so I used this function that accepts sig_df (dataframe with the timeseries of stocks signal) and number of quantiles as imput:

qs = ['Q' + str(i) for i in range(1, len(perc)+1)] q_labels= list(itertools.chain.from_iterable( itertools.repeat(x, int(sig_df.shape[1]/q_num)) for x in qs))  rank_labels = ['rank_{}'.format(i) for i in range(sig_df.shape[1])]  bucketed_names = pd.DataFrame(         sig_df.columns.values[np.argsort(-sig_df.values, axis=1)],          columns=[q_labels, rank_labels]         ) 

The second function computes portfolio returns, based on the names bucketed in the function above. It accepts two input a df containing stocks return and the output from the function above. To do so I used:

bucketed_returns = dict() for i in range(1, int(ret_df.shape[1]/bucketed_names.Q1.shape[1])):     Q = []      for row in bucketed_names['Q' + str(i)].itertuples():         temp = ret_df.loc[list(row[:1]) ,list(row[1:])]         Q.append(float(, weights)))         bucketed_returns['Q' + str(i)] = Q           bucketed_returns = pd.DataFrame(bucketed_returns) 

To optimize this code I thought about multiprocessing – not able to code that – or maybe there could be a better way remaining in pandas/numpy environment.

Databse design for stocks [on hold]

I am a beginner in database design.

I am wondering what is the best design method to store data for stock market information. I want to create a new database to store historical prices and many other fundamentals data for multiple stock symbols.

Stock symbol may change over time and I am confused on what unique identifier to use or how to manage it. CUSIPs number may also change.

Should I create a reference table where I create one key value for each stock, then build my other tables with this key value? How to properly manage that primary table since I don’t know when changes are made on stock symbols.

I use a python to get and store the data in sql server.


Implement system to get most traded stocks in C#

Please suggest way to solve a coding question, I came across. Question is as follows:

Implement a class StockMarket that has the two following functions:

 class StockMarket  {   public:  void addTrade(string stockName, int share);  - This function keeps track the number of shares transacted for a stock by adding the trade information  void printTop(int numberOfStock);  - This function prints the top numberOfStock stocks that has the highest number of transacted shares   } 

And here’s a sample calling sequence that uses the above class:

 StockMarket stockMarket = new StockMarket();  stockMarket.addTrade("GOOGLE", 50);  stockMarket.addTrade("APPLE", 150);  stockMarket.addTrade("GOOGLE", 100);  stockMarket.addTrade("MSFT", 250);  stockMarket.addTrade("GOOGLE", 200);   stockMarket.printTop(2); 

Expected output: GOOGLE 350 MSFT 250

I followed 2 approaches to solve this problem:

  1. Create Dictionary with Key – CompanyName and value – number of shares. While giving top results, I sorted dictionary by descending and returned results.

Time Complexity: Add – O(1) | GetTop – O(nlogn) + O(k)

  1. Create SortedSet with custom comparer to sort stocks with descending order. I am facing challanges to update SortedSet. I am not able to remove old entries with time less than O(n).

Please find below my current code :

public class StockNodeComparer : IComparer<StockNode> {     public int Compare(StockNode s1, StockNode s2)     {         int result = s2.value.CompareTo(s1.value);          if (result == 0)         {             return 1;         }         else         {             return result;         }     } } public class StockNode {     public int value;     public string name;     public StockNode(string n, int i)     {         name = n;         value = i;     } }  public class StockContainer {     public Dictionary<string, StockNode> map;     public SortedSet<StockNode> sortedStockList;      public StockContainer()     {         map = new Dictionary<string, StockNode>();         sortedStockList = new SortedSet<StockNode>(new StockNodeComparer());     }      public void AddValue(string s, int x)     {         if(map.ContainsKey(s))         {             int tempVal = map[s].value;             sortedStockList.Remove(map[s]);             var tempNode = new StockNode(s, tempVal + x);             AddNodeInDict(s, ref tempNode);             sortedStockList.Add(tempNode);         }         else         {             var tempNode = new StockNode(s, x);             AddNodeInDict(s, ref tempNode);             sortedStockList.Add(tempNode);         }                 }      private void AddNodeInDict(string s, ref StockNode tempNode)     {         map[s] = tempNode;     }      public void GetTop(int k)     {         int i = 0;         while(i<k)         {             Console.WriteLine(sortedStockList.ElementAt(sortedStockList.Count - i).name);         }     } }