Skip to content

Commit 61b0043

Browse files
authored
Update dist.cpp
1 parent 92f2b3f commit 61b0043

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

Distribution/dist.cpp

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,14 @@ std::string address(std::string ticker){
2222
return url;
2323
}
2424

25+
// Takes part in decrypting bytes to be transferred into a string result
2526
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) {
2627
size_t totalSize = size * nmemb;
2728
response->append((char*)contents, totalSize);
2829
return totalSize;
2930
}
3031

32+
// Sends a rest request to polygon to fetch the stock data
3133
std::string RequestData(const std::string& url) {
3234
CURL* curl;
3335
CURLcode res;
@@ -55,16 +57,21 @@ std::string RequestData(const std::string& url) {
5557
return response; // Return the response
5658
}
5759

60+
// Sleep timer
5861
void Sleep(int wait_time){
5962
std::this_thread::sleep_for(std::chrono::seconds(wait_time));
6063
}
6164

65+
// Imports historical stock price data from Polygon.io and sorts them into a map with the key being the stock ticker
66+
// and the value being the vector of close prices
6267
std::map<std::string, std::vector<double>> ImportHistoricalData(std::vector<std::string> tickers, int wait_time){
6368
std::map<std::string, std::vector<double>> result;
6469
std::cout << "Stock data is loading" << std::endl;
6570
for(auto & stock : tickers){
6671
Sleep(wait_time);
6772
std::cout << stock << " is imported" << std::endl;
73+
74+
// Fetch stock price data and parse string result as JSON with Boost
6875
std::string response = RequestData(address(stock));
6976
ptree data;
7077
std::stringstream ss(response);
@@ -74,6 +81,7 @@ std::map<std::string, std::vector<double>> ImportHistoricalData(std::vector<std:
7481
for(ptree::const_iterator jt = it->second.begin(); jt != it->second.end(); ++jt){
7582
for(ptree::const_iterator kt = jt->second.begin(); kt != jt->second.end(); ++kt){
7683
if(kt->first == "l"){
84+
// Pull close prices for the stock into the map
7785
result[stock].push_back(atof(kt->second.get_value<std::string>().c_str()));
7886
}
7987
}
@@ -85,7 +93,10 @@ std::map<std::string, std::vector<double>> ImportHistoricalData(std::vector<std:
8593
return result;
8694
}
8795

96+
// Calculates the distribution charts per ticker and stores the results in the modify map
8897
void ComputeData(std::vector<double> close, std::string ticker, std::map<std::string, std::map<std::string, std::vector<double>>> & modify){
98+
99+
// Computes the average of a given vector of values
89100
auto average = [](std::vector<double> x){
90101
double total = 0;
91102
for(auto & i : x){
@@ -95,6 +106,7 @@ void ComputeData(std::vector<double> close, std::string ticker, std::map<std::st
95106
return total;
96107
};
97108

109+
// Computes the standard deviation of a given vector of values
98110
auto volatility = [&](std::vector<double> x){
99111
double mu = average(x);
100112
double total = 0;
@@ -105,23 +117,30 @@ void ComputeData(std::vector<double> close, std::string ticker, std::map<std::st
105117
return pow(total, 0.5);
106118
};
107119

120+
// Stochastic parameter in Geometric Brownian Motion which returns a value between -10 to 10 percent
108121
auto dWT = [](){
109122
int num = 10;
110123
double dw = (rand() % (2*num + 1)) - num;
111124
return dw/100.0;
112125
};
113126

127+
// Takes in the stock returns and the number of bins and generates a histogram
114128
auto histogram = [](std::vector<double> returns, int bins){
115129
std::map<std::string, std::vector<double>> res;
130+
131+
// Sort the returns and set the bounds of the histogram
116132
std::sort(returns.begin(), returns.end());
117133
double m0 = returns[0];
118134
double m1 = returns[returns.size() - 1];
119135
double dm = (m1 - m0)/((double) bins);
136+
137+
// Count the frequency of each return group occuring, return group is between 'a' and 'b'
120138
for(int i = 0; i < bins; ++i){
121139
double a = m0 + i*dm;
122140
double b = m0 + (i+1)*dm;
123141
int count = 0;
124142
for(auto & r : returns){
143+
// Counts the frequency
125144
if(i == bins - 1){
126145
if(r >= a && r <= b){
127146
count += 1;
@@ -132,17 +151,22 @@ void ComputeData(std::vector<double> close, std::string ticker, std::map<std::st
132151
}
133152
}
134153
}
154+
// Pushes x and y parameters in histogram map
135155
double mid = 0.5*(a + b);
136156
res["x"].push_back(mid);
137157
res["y"].push_back(count);
138158
}
139159
return res;
140160
};
141-
161+
142162
std::vector<double> ror, ror_predict, stock_paths;
163+
164+
// Calculates the rate of return of the current selected stock
143165
for(int i = 1; i < close.size(); ++i){
144166
ror.push_back(close[i]/close[i-1] - 1.0);
145167
}
168+
169+
// Sets the parameters for the Geometric Brownian Motion equation
146170
double S = close[close.size() - 1];
147171
double mu = average(ror);
148172
double t = 1.0/12.0;
@@ -151,9 +175,12 @@ void ComputeData(std::vector<double> close, std::string ticker, std::map<std::st
151175
int P = 100;
152176
double dt = t / (double) N;
153177

154-
// mu*S*dt + v*S*dWT()
178+
// Formula = mu*S*dt + v*S*dWT()
179+
180+
// Makes sure each run is random
155181
srand(time(NULL));
156182

183+
// Running the GBM simulation
157184
for(int p = 0; p < P; ++p){
158185
double S0 = S;
159186
for(int t = 0; t < N; ++t){
@@ -162,13 +189,18 @@ void ComputeData(std::vector<double> close, std::string ticker, std::map<std::st
162189
stock_paths.push_back(S0);
163190
}
164191

192+
// Computing the rate of return from the predicted stock paths
165193
for(int i = 1; i < stock_paths.size(); ++i){
166194
ror_predict.push_back(stock_paths[i]/stock_paths[i-1] - 1.0);
167195
}
168196

197+
// Generating the histogram with 30 bins for both groups (historical and predicted)
169198
std::map<std::string, std::vector<double>> RHist = histogram(ror, 30);
170199
std::map<std::string, std::vector<double>> RPred = histogram(ror_predict, 30);
171200

201+
// Storing everything in the modify result map which has the first key being a stock ticker
202+
// and the second key being x,y hist/pred
203+
172204
modify[ticker]["xhist"] = RHist["x"];
173205
modify[ticker]["yhist"] = RHist["y"];
174206
modify[ticker]["xpred"] = RPred["x"];
@@ -179,27 +211,35 @@ void ComputeData(std::vector<double> close, std::string ticker, std::map<std::st
179211

180212
int main()
181213
{
214+
// Selected stocks to be examined
182215
std::vector<std::string> tickers = {"MSFT","AAPL","NVDA","AMZN","IBM","ORCL"};
216+
217+
// Building the plot grid for the histograms
183218
std::vector<PyObject*> plots;
184219
std::vector<int> pnum = {231, 232, 233, 234, 235, 236};
185220
for(auto & number : pnum){
186221
plots.push_back(plt::chart2D(number));
187222
}
188223

224+
// Set sleep time
189225
int sleep_for_time = 10;
190226

227+
// Import the historical data and declare storage map
191228
std::map<std::string, std::vector<double>> close = ImportHistoricalData(tickers, sleep_for_time);
192229
std::map<std::string, std::map<std::string, std::vector<double>>> modify;
193-
230+
231+
// Build a vector of threads to calculate all inputted stocks simulations at the same time
194232
std::vector<std::thread> items;
195233
for(auto & ticker : tickers){
196234
items.emplace_back(ComputeData, close[ticker], ticker, std::ref(modify));
197235
}
198236

237+
// Join the threads upon completion to end each thread
199238
for(auto & plane : items){
200239
plane.join();
201240
}
202241

242+
// Plot the distributions
203243
for(int i = 0; i < plots.size(); ++i){
204244
PyObject * ax = plots[i];
205245
std::string tick = tickers[i];
@@ -211,4 +251,4 @@ int main()
211251
plt::show();
212252

213253
return 0;
214-
}
254+
}

0 commit comments

Comments
 (0)