-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_structures.c
More file actions
1086 lines (912 loc) · 26.9 KB
/
data_structures.c
File metadata and controls
1086 lines (912 loc) · 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ============================================================================
* File: data_structures.c
* Description: Implementation of core data structures
* ============================================================================
*/
#include "data_structures.h"
// ============================================================================
// DYNAMIC ARRAY IMPLEMENTATION
// ============================================================================
/**
* Create a new dynamic array with given capacity
*/
DynamicArray* create_dynamic_array(int initial_capacity) {
DynamicArray *arr = (DynamicArray*)malloc(sizeof(DynamicArray));
if (!arr) return NULL;
arr->data = (double*)malloc(initial_capacity * sizeof(double));
if (!arr->data) {
free(arr);
return NULL;
}
arr->size = 0;
arr->capacity = initial_capacity;
return arr;
}
/**
* Resize dynamic array when capacity is reached
*/
void resize_dynamic_array(DynamicArray *arr) {
arr->capacity *= 2;
double *new_data = (double*)realloc(arr->data, arr->capacity * sizeof(double));
if (new_data) {
arr->data = new_data;
}
}
/**
* Add element to end of dynamic array
*/
void push_back(DynamicArray *arr, double value) {
if (arr->size >= arr->capacity) {
resize_dynamic_array(arr);
}
arr->data[arr->size++] = value;
}
/**
* Get element at index
*/
double get_at(DynamicArray *arr, int index) {
if (index >= 0 && index < arr->size) {
return arr->data[index];
}
return 0.0;
}
/**
* Set element at index
*/
void set_at(DynamicArray *arr, int index, double value) {
if (index >= 0 && index < arr->size) {
arr->data[index] = value;
}
}
/**
* Free dynamic array memory
*/
void free_dynamic_array(DynamicArray *arr) {
if (arr) {
free(arr->data);
free(arr);
}
}
// ============================================================================
// CIRCULAR QUEUE IMPLEMENTATION
// ============================================================================
/**
* Create circular queue with given capacity
*/
CircularQueue* create_circular_queue(int capacity) {
CircularQueue *queue = (CircularQueue*)malloc(sizeof(CircularQueue));
if (!queue) return NULL;
queue->data = (double*)malloc(capacity * sizeof(double));
if (!queue->data) {
free(queue);
return NULL;
}
queue->front = 0;
queue->rear = -1;
queue->size = 0;
queue->capacity = capacity;
queue->sum = 0.0;
return queue;
}
/**
* Check if queue is full
*/
int is_queue_full(CircularQueue *queue) {
return queue->size == queue->capacity;
}
/**
* Check if queue is empty
*/
int is_queue_empty(CircularQueue *queue) {
return queue->size == 0;
}
/**
* Add element to queue (O(1))
*/
int enqueue(CircularQueue *queue, double value) {
if (is_queue_full(queue)) {
// Remove oldest element
double old_value = dequeue(queue);
}
queue->rear = (queue->rear + 1) % queue->capacity;
queue->data[queue->rear] = value;
queue->size++;
queue->sum += value;
return 1;
}
/**
* Remove element from queue (O(1))
*/
double dequeue(CircularQueue *queue) {
if (is_queue_empty(queue)) {
return 0.0;
}
double value = queue->data[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size--;
queue->sum -= value;
return value;
}
/**
* Get average of all elements in queue (O(1))
*/
double get_queue_average(CircularQueue *queue) {
if (queue->size == 0) return 0.0;
return queue->sum / queue->size;
}
/**
* Free circular queue memory
*/
void free_circular_queue(CircularQueue *queue) {
if (queue) {
free(queue->data);
free(queue);
}
}
// ============================================================================
// MIN HEAP IMPLEMENTATION
// ============================================================================
/**
* Create min heap with given capacity
*/
MinHeap* create_min_heap(int capacity) {
MinHeap *heap = (MinHeap*)malloc(sizeof(MinHeap));
if (!heap) return NULL;
heap->nodes = (HeapNode*)malloc(capacity * sizeof(HeapNode));
if (!heap->nodes) {
free(heap);
return NULL;
}
heap->size = 0;
heap->capacity = capacity;
return heap;
}
/**
* Heapify subtree rooted at index (min heap)
*/
void min_heapify(MinHeap *heap, int index) {
int smallest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
if (left < heap->size && heap->nodes[left].price < heap->nodes[smallest].price) {
smallest = left;
}
if (right < heap->size && heap->nodes[right].price < heap->nodes[smallest].price) {
smallest = right;
}
if (smallest != index) {
HeapNode temp = heap->nodes[index];
heap->nodes[index] = heap->nodes[smallest];
heap->nodes[smallest] = temp;
min_heapify(heap, smallest);
}
}
/**
* Insert element into min heap
*/
void insert_min_heap(MinHeap *heap, double price, int timestamp) {
if (heap->size >= heap->capacity) return;
int i = heap->size++;
heap->nodes[i].price = price;
heap->nodes[i].timestamp = timestamp;
// Fix min heap property
while (i > 0 && heap->nodes[(i - 1) / 2].price > heap->nodes[i].price) {
HeapNode temp = heap->nodes[i];
heap->nodes[i] = heap->nodes[(i - 1) / 2];
heap->nodes[(i - 1) / 2] = temp;
i = (i - 1) / 2;
}
}
/**
* Extract minimum element from heap
*/
HeapNode extract_min(MinHeap *heap) {
HeapNode min_node = {0, 0};
if (heap->size == 0) return min_node;
min_node = heap->nodes[0];
heap->nodes[0] = heap->nodes[--heap->size];
min_heapify(heap, 0);
return min_node;
}
/**
* Peek at minimum element without removing
*/
HeapNode peek_min(MinHeap *heap) {
HeapNode min_node = {0, 0};
if (heap->size > 0) {
min_node = heap->nodes[0];
}
return min_node;
}
/**
* Free min heap memory
*/
void free_min_heap(MinHeap *heap) {
if (heap) {
free(heap->nodes);
free(heap);
}
}
// ============================================================================
// MAX HEAP IMPLEMENTATION
// ============================================================================
/**
* Create max heap with given capacity
*/
MaxHeap* create_max_heap(int capacity) {
MaxHeap *heap = (MaxHeap*)malloc(sizeof(MaxHeap));
if (!heap) return NULL;
heap->nodes = (HeapNode*)malloc(capacity * sizeof(HeapNode));
if (!heap->nodes) {
free(heap);
return NULL;
}
heap->size = 0;
heap->capacity = capacity;
return heap;
}
/**
* Heapify subtree rooted at index (max heap)
*/
void max_heapify(MaxHeap *heap, int index) {
int largest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
if (left < heap->size && heap->nodes[left].price > heap->nodes[largest].price) {
largest = left;
}
if (right < heap->size && heap->nodes[right].price > heap->nodes[largest].price) {
largest = right;
}
if (largest != index) {
HeapNode temp = heap->nodes[index];
heap->nodes[index] = heap->nodes[largest];
heap->nodes[largest] = temp;
max_heapify(heap, largest);
}
}
/**
* Insert element into max heap
*/
void insert_max_heap(MaxHeap *heap, double price, int timestamp) {
if (heap->size >= heap->capacity) return;
int i = heap->size++;
heap->nodes[i].price = price;
heap->nodes[i].timestamp = timestamp;
// Fix max heap property
while (i > 0 && heap->nodes[(i - 1) / 2].price < heap->nodes[i].price) {
HeapNode temp = heap->nodes[i];
heap->nodes[i] = heap->nodes[(i - 1) / 2];
heap->nodes[(i - 1) / 2] = temp;
i = (i - 1) / 2;
}
}
/**
* Extract maximum element from heap
*/
HeapNode extract_max(MaxHeap *heap) {
HeapNode max_node = {0, 0};
if (heap->size == 0) return max_node;
max_node = heap->nodes[0];
heap->nodes[0] = heap->nodes[--heap->size];
max_heapify(heap, 0);
return max_node;
}
/**
* Peek at maximum element without removing
*/
HeapNode peek_max(MaxHeap *heap) {
HeapNode max_node = {0, 0};
if (heap->size > 0) {
max_node = heap->nodes[0];
}
return max_node;
}
/**
* Free max heap memory
*/
void free_max_heap(MaxHeap *heap) {
if (heap) {
free(heap->nodes);
free(heap);
}
}
// ============================================================================
// LINKED LIST (TRADE HISTORY) IMPLEMENTATION
// ============================================================================
/**
* Create new trade list
*/
TradeList* create_trade_list() {
TradeList *list = (TradeList*)malloc(sizeof(TradeList));
if (!list) return NULL;
list->head = NULL;
list->tail = NULL;
list->count = 0;
return list;
}
/**
* Add trade to list
*/
void add_trade(TradeList *list, Trade trade) {
TradeNode *new_node = (TradeNode*)malloc(sizeof(TradeNode));
if (!new_node) return;
new_node->trade = trade;
new_node->next = NULL;
if (list->tail == NULL) {
list->head = new_node;
list->tail = new_node;
} else {
list->tail->next = new_node;
list->tail = new_node;
}
list->count++;
}
/**
* Print all trades
*/
void print_trade_list(TradeList *list) {
if (!list || !list->head) {
printf("No trades in history.\n");
return;
}
printf("\n=== TRADE HISTORY ===\n");
printf("%-10s %-8s %-12s %-10s %-8s %-12s %-10s\n",
"Symbol", "Action", "Date", "Price", "Qty", "Total", "Commission");
printf("-------------------------------------------------------------------------\n");
TradeNode *current = list->head;
while (current) {
Trade t = current->trade;
printf("%-10s %-8s %04d-%02d-%02d $%-9.2f %-8d $%-11.2f $%-9.2f\n",
t.symbol, t.action, t.date.year, t.date.month, t.date.day,
t.price, t.quantity, t.total_value, t.commission);
current = current->next;
}
printf("-------------------------------------------------------------------------\n");
printf("Total Trades: %d\n\n", list->count);
}
/**
* Get trade count
*/
int get_trade_count(TradeList *list) {
return list ? list->count : 0;
}
/**
* Free trade list memory
*/
void free_trade_list(TradeList *list) {
if (!list) return;
TradeNode *current = list->head;
while (current) {
TradeNode *temp = current;
current = current->next;
free(temp);
}
free(list);
}
// ============================================================================
// HASH TABLE IMPLEMENTATION
// ============================================================================
/**
* Hash function for stock symbols
*/
unsigned int hash_function(const char *symbol) {
unsigned int hash = 0;
while (*symbol) {
hash = (hash * 31) + *symbol;
symbol++;
}
return hash % HASH_TABLE_SIZE;
}
/**
* Create hash table
*/
HashTable* create_hash_table(int size) {
HashTable *ht = (HashTable*)malloc(sizeof(HashTable));
if (!ht) return NULL;
ht->table = (HashNode**)calloc(size, sizeof(HashNode*));
if (!ht->table) {
free(ht);
return NULL;
}
ht->size = size;
return ht;
}
/**
* Insert stock into hash table
*/
void insert_stock(HashTable *ht, Stock *stock) {
unsigned int index = hash_function(stock->symbol);
HashNode *new_node = (HashNode*)malloc(sizeof(HashNode));
if (!new_node) return;
strcpy(new_node->symbol, stock->symbol);
new_node->stock = stock;
new_node->next = ht->table[index];
ht->table[index] = new_node;
}
/**
* Lookup stock in hash table (O(1) average)
*/
Stock* lookup_stock(HashTable *ht, const char *symbol) {
unsigned int index = hash_function(symbol);
HashNode *node = ht->table[index];
while (node) {
if (strcmp(node->symbol, symbol) == 0) {
return node->stock;
}
node = node->next;
}
return NULL;
}
/**
* Free hash table memory
*/
void free_hash_table(HashTable *ht) {
if (!ht) return;
for (int i = 0; i < ht->size; i++) {
HashNode *node = ht->table[i];
while (node) {
HashNode *temp = node;
node = node->next;
free(temp);
}
}
free(ht->table);
free(ht);
}
// ============================================================================
// BINARY SEARCH TREE IMPLEMENTATION
// ============================================================================
/**
* Create BST
*/
BST* create_bst() {
BST *bst = (BST*)malloc(sizeof(BST));
if (!bst) return NULL;
bst->root = NULL;
bst->size = 0;
return bst;
}
/**
* Insert node into BST
*/
BSTNode* insert_bst_node(BSTNode *root, double price) {
if (root == NULL) {
BSTNode *new_node = (BSTNode*)malloc(sizeof(BSTNode));
new_node->price = price;
new_node->count = 1;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
if (fabs(price - root->price) < 0.01) {
root->count++;
} else if (price < root->price) {
root->left = insert_bst_node(root->left, price);
} else {
root->right = insert_bst_node(root->right, price);
}
return root;
}
/**
* Search for price in BST
*/
BSTNode* search_bst(BSTNode *root, double price) {
if (root == NULL || fabs(root->price - price) < 0.01) {
return root;
}
if (price < root->price) {
return search_bst(root->left, price);
}
return search_bst(root->right, price);
}
/**
* Find minimum price in BST
*/
BSTNode* find_min_bst(BSTNode *root) {
if (root == NULL) return NULL;
while (root->left != NULL) {
root = root->left;
}
return root;
}
/**
* Find maximum price in BST
*/
BSTNode* find_max_bst(BSTNode *root) {
if (root == NULL) return NULL;
while (root->right != NULL) {
root = root->right;
}
return root;
}
/**
* Inorder traversal of BST
*/
void inorder_traversal(BSTNode *root) {
if (root != NULL) {
inorder_traversal(root->left);
printf("%.2f (count: %d) ", root->price, root->count);
inorder_traversal(root->right);
}
}
/**
* Free BST memory
*/
void free_bst(BSTNode *root) {
if (root != NULL) {
free_bst(root->left);
free_bst(root->right);
free(root);
}
}
// Continued in next artifact due to length...
/*
* ============================================================================
* File: data_structures.c - Part 2
* Description: Portfolio, Stock, and Utility Functions
* ============================================================================
*/
// ============================================================================
// PORTFOLIO IMPLEMENTATION
// ============================================================================
/**
* Create new portfolio with initial capital
*/
Portfolio* create_portfolio(double initial_capital) {
Portfolio *portfolio = (Portfolio*)malloc(sizeof(Portfolio));
if (!portfolio) return NULL;
portfolio->holdings = (Holding*)malloc(MAX_STOCKS * sizeof(Holding));
if (!portfolio->holdings) {
free(portfolio);
return NULL;
}
portfolio->num_holdings = 0;
portfolio->capacity = MAX_STOCKS;
portfolio->cash_balance = initial_capital;
portfolio->initial_capital = initial_capital;
portfolio->total_value = initial_capital;
portfolio->total_return = 0.0;
portfolio->total_return_percentage = 0.0;
return portfolio;
}
/**
* Add holding to portfolio
*/
void add_holding(Portfolio *portfolio, const char *symbol, int quantity, double price) {
if (!portfolio || portfolio->num_holdings >= portfolio->capacity) return;
// Check if holding already exists
Holding *existing = get_holding(portfolio, symbol);
if (existing) {
// Update existing holding
double total_cost = existing->total_invested + (quantity * price);
int total_qty = existing->quantity + quantity;
existing->quantity = total_qty;
existing->average_price = total_cost / total_qty;
existing->total_invested = total_cost;
existing->current_value = total_qty * price;
existing->current_price = price;
} else {
// Add new holding
Holding *h = &portfolio->holdings[portfolio->num_holdings];
strcpy(h->symbol, symbol);
h->quantity = quantity;
h->average_price = price;
h->current_price = price;
h->total_invested = quantity * price;
h->current_value = quantity * price;
h->profit_loss = 0.0;
h->profit_loss_percentage = 0.0;
portfolio->num_holdings++;
}
portfolio->cash_balance -= (quantity * price);
}
/**
* Update holding with current price
*/
void update_holding(Portfolio *portfolio, const char *symbol, double current_price) {
Holding *h = get_holding(portfolio, symbol);
if (h) {
h->current_price = current_price;
h->current_value = h->quantity * current_price;
h->profit_loss = h->current_value - h->total_invested;
h->profit_loss_percentage = (h->profit_loss / h->total_invested) * 100.0;
}
}
/**
* Remove holding from portfolio
*/
void remove_holding(Portfolio *portfolio, const char *symbol) {
if (!portfolio) return;
for (int i = 0; i < portfolio->num_holdings; i++) {
if (strcmp(portfolio->holdings[i].symbol, symbol) == 0) {
// Add proceeds to cash
portfolio->cash_balance += portfolio->holdings[i].current_value;
// Shift remaining holdings
for (int j = i; j < portfolio->num_holdings - 1; j++) {
portfolio->holdings[j] = portfolio->holdings[j + 1];
}
portfolio->num_holdings--;
break;
}
}
}
/**
* Get holding by symbol
*/
Holding* get_holding(Portfolio *portfolio, const char *symbol) {
if (!portfolio) return NULL;
for (int i = 0; i < portfolio->num_holdings; i++) {
if (strcmp(portfolio->holdings[i].symbol, symbol) == 0) {
return &portfolio->holdings[i];
}
}
return NULL;
}
/**
* Calculate total portfolio value and returns
*/
void calculate_portfolio_value(Portfolio *portfolio) {
if (!portfolio) return;
double holdings_value = 0.0;
for (int i = 0; i < portfolio->num_holdings; i++) {
holdings_value += portfolio->holdings[i].current_value;
}
portfolio->total_value = portfolio->cash_balance + holdings_value;
portfolio->total_return = portfolio->total_value - portfolio->initial_capital;
portfolio->total_return_percentage =
(portfolio->total_return / portfolio->initial_capital) * 100.0;
}
/**
* Print portfolio summary
*/
void print_portfolio(Portfolio *portfolio) {
if (!portfolio) return;
printf("\n");
printf("╔════════════════════════════════════════════════════════════════╗\n");
printf("║ PORTFOLIO SUMMARY ║\n");
printf("╚════════════════════════════════════════════════════════════════╝\n\n");
printf("Initial Capital: $%12.2f\n", portfolio->initial_capital);
printf("Cash Balance: $%12.2f\n", portfolio->cash_balance);
if (portfolio->num_holdings > 0) {
printf("\n%-10s %8s %12s %12s %12s %12s %10s\n",
"Symbol", "Qty", "Avg Price", "Curr Price", "Invested", "Value", "P/L %");
printf("─────────────────────────────────────────────────────────────────────────────\n");
for (int i = 0; i < portfolio->num_holdings; i++) {
Holding h = portfolio->holdings[i];
printf("%-10s %8d $%11.2f $%11.2f $%11.2f $%11.2f %9.2f%%\n",
h.symbol, h.quantity, h.average_price, h.current_price,
h.total_invested, h.current_value, h.profit_loss_percentage);
}
printf("─────────────────────────────────────────────────────────────────────────────\n");
}
printf("\nTotal Portfolio Value: $%12.2f\n", portfolio->total_value);
printf("Total Return: $%12.2f (%.2f%%)\n",
portfolio->total_return, portfolio->total_return_percentage);
printf("\n");
}
/**
* Free portfolio memory
*/
void free_portfolio(Portfolio *portfolio) {
if (portfolio) {
free(portfolio->holdings);
free(portfolio);
}
}
// ============================================================================
// DATE UTILITY FUNCTIONS
// ============================================================================
/**
* Create date structure
*/
Date create_date(int year, int month, int day) {
Date date;
date.year = year;
date.month = month;
date.day = day;
return date;
}
/**
* Compare two dates
* Returns: -1 if d1 < d2, 0 if equal, 1 if d1 > d2
*/
int compare_dates(Date d1, Date d2) {
if (d1.year != d2.year) return (d1.year < d2.year) ? -1 : 1;
if (d1.month != d2.month) return (d1.month < d2.month) ? -1 : 1;
if (d1.day != d2.day) return (d1.day < d2.day) ? -1 : 1;
return 0;
}
/**
* Print date in YYYY-MM-DD format
*/
void print_date(Date date) {
printf("%04d-%02d-%02d", date.year, date.month, date.day);
}
/**
* Convert string to date (format: YYYY-MM-DD)
*/
Date string_to_date(const char *date_str) {
Date date = {0, 0, 0};
if (date_str && strlen(date_str) >= 10) {
sscanf(date_str, "%d-%d-%d", &date.year, &date.month, &date.day);
}
return date;
}
// ============================================================================
// STOCK FUNCTIONS
// ============================================================================
/**
* Create new stock with symbol
*/
Stock* create_stock(const char *symbol) {
Stock *stock = (Stock*)malloc(sizeof(Stock));
if (!stock) return NULL;
strncpy(stock->symbol, symbol, MAX_SYMBOL_LENGTH - 1);
stock->symbol[MAX_SYMBOL_LENGTH - 1] = '\0';
stock->prices = (PriceData*)malloc(INITIAL_CAPACITY * sizeof(PriceData));
if (!stock->prices) {
free(stock);
return NULL;
}
stock->size = 0;
stock->capacity = INITIAL_CAPACITY;
return stock;
}
/**
* Add price data to stock
*/
void add_price_data(Stock *stock, PriceData data) {
if (!stock) return;
if (stock->size >= stock->capacity) {
stock->capacity *= 2;
PriceData *new_prices = (PriceData*)realloc(stock->prices,
stock->capacity * sizeof(PriceData));
if (new_prices) {
stock->prices = new_prices;
}
}
stock->prices[stock->size++] = data;
}
/**
* Get price data at specific date
*/
PriceData* get_price_at_date(Stock *stock, Date date) {
if (!stock) return NULL;
for (int i = 0; i < stock->size; i++) {
if (compare_dates(stock->prices[i].date, date) == 0) {
return &stock->prices[i];
}
}
return NULL;
}
/**
* Free stock memory
*/
void free_stock(Stock *stock) {
if (stock) {
free(stock->prices);
free(stock);
}
}
// ============================================================================
// STATISTICAL FUNCTIONS
// ============================================================================
/**
* Calculate mean of array
*/
double calculate_mean(double *data, int size) {
if (size <= 0) return 0.0;
double sum = 0.0;
for (int i = 0; i < size; i++) {
sum += data[i];
}
return sum / size;
}
/**
* Calculate variance
*/
double calculate_variance(double *data, int size) {
if (size <= 1) return 0.0;
double mean = calculate_mean(data, size);
double sum_sq_diff = 0.0;
for (int i = 0; i < size; i++) {
double diff = data[i] - mean;
sum_sq_diff += diff * diff;
}
return sum_sq_diff / (size - 1);
}
/**
* Calculate standard deviation
*/
double calculate_std_dev(double *data, int size) {
return sqrt(calculate_variance(data, size));
}
/**
* Calculate covariance between two arrays
*/
double calculate_covariance(double *data1, double *data2, int size) {
if (size <= 1) return 0.0;
double mean1 = calculate_mean(data1, size);
double mean2 = calculate_mean(data2, size);
double covar = 0.0;
for (int i = 0; i < size; i++) {
covar += (data1[i] - mean1) * (data2[i] - mean2);
}
return covar / (size - 1);
}
/**
* Calculate correlation coefficient
*/
double calculate_correlation(double *data1, double *data2, int size) {
if (size <= 1) return 0.0;