使用包“nloptr”进行优化

时间:2015-11-22 20:14:02

标签: r optimization

我试图从Excel的“Solver”加载项中复制R中的结果。我不知道优化的内部工作原理(数学上),因此我在大多数帖子结果以及我收到的错误消息时都会感到困惑。我尝试使用optimx包,但显然不允许对优化中的约束进行过多控制,所以现在我正在尝试nloptr包。

基本上,我要做的是复制最佳投资组合计算(财务)。以下是我的代码示例:

ret.cov <- cov(as.matrix(ret.p[,1:30]))
wts <- rep(1/portfolioSize, times = portfolioSize)
sharpe <- function(wts) {
  mean.p <- sum(colMeans(ret.p[,1:30])*wts)
  var.p <- t(wts) %*% (ret.cov %*% (wts))
  sd.p <- sqrt(var.p)
  SR <- (mean.p - Rf)/sd.p
  return(as.numeric(SR))
}
fun.eq <- function(wts) {
  sum(wts) == 1
}

optim.p <- nloptr(x0 = wts, eval_f = sharpe, lb = 0, ub = 1, eval_g_eq = fun.eq)

sharpe(as.numeric(optim.p$solution))
  1. 计算30只股票的协方差矩阵及其回报
  2. 初始化这些股票的权重以进行优化(等于加权开始)
  3. 设置一个最大化的函数,用于计算投资组合的夏普比率
  4. 尝试(???)指定nloptr的相等函数,该函数指出wts向量的总和必须等于1。
  5. 尝试最大化功能(虽然我认为它默认最小化,但我不知道如何改变它以最大化)。
  6. 检查结果,最大化的夏普比率
  7. 当我在nloptr函数之外尝试时,Sharpe计算功能正常工作。问题是各种各样的,从需要指定正确使用的算法到不接受我提供的相等函数的函数。

    所以,我的问题是:

    1. 如何将nloptr更改为最大化而不是最小化?
    2. 如何编写一个相等函数来指定输入向量(权重)的总和必须等于1?
    3. 在此处使用opts = list()指定的正确算法是什么? Excel使用称为“GRG Nonlinear”的东西。
    4. 提前谢谢!

1 个答案:

答案 0 :(得分:0)

希望它仍然相关...... 你没有提供数据,所以我无法运行,但我会尝试提供帮助。

1)为了最大化,只需最小化-sharpe
2)eval_g_eq需要采用h(x)= 0的格式,这意味着您需要在fun.eq上将- (void)viewDidLoad{ [super viewDidLoad]; NSLog(@"viewDidLoad"); [self performSelector:@selector(startScanning) withObject:nil afterDelay:5.0]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)centralManagerDidUpdateState:(CBCentralManager *)central { NSLog(@"centralManagerDidUpdateState"); if (central.state == CBCentralManagerStatePoweredOn) { NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey, nil]; [self.bluetoothManager scanForPeripheralsWithServices:nil options:options]; } else { return; } } -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{ //NSLog(@"didDiscoverPeripheral %@ && UUID = ",peripheral.name, [peripheral.identifier UUIDString]); if(peripheral.name){ [peripheral readRSSI]; [self.beaconPeripherals addObject:peripheral]; self.beacons = [NSArray arrayWithArray:self.beaconPeripherals]; [self reloadBeacons]; } } - (void) startScanning{ if(self.bluetoothManager){ [self.bluetoothManager stopScan]; [self.beaconPeripherals removeAllObjects]; } self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil]; self.beaconPeripherals = [[NSMutableArray alloc]init]; self.beacons = [[NSArray alloc]init]; } - (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error{ NSLog(@"RSSI update %@",peripheral.RSSI); } #pragma mark - CLLocationManager delegates -(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{ NSLog(@"*****didEnterRegion******"); [self performActionForEvent:EventEnter withIdentifier:region.identifier]; } -(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region { NSLog(@"***********didExitRegion***********"); [self performActionForEvent:EventExit withIdentifier:region.identifier]; } -(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region { NSLog(@"didStartMonitoringForRegion"); } -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"didFailWithError"); } -(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region { NSLog(@"didRangeBeacons with size %i", beacons.count); if ([beacons count] > 0) { NSLog(@"beacons founds: %lu",(unsigned long)[beacons count]); CLBeacon *beacon = [beacons objectAtIndex:0]; NSLog(@"Beacons UUID: %@",beacon.proximityUUID); NSLog(@"Beacons Major: %@",beacon.major); NSLog(@"Beacons Minor: %@",beacon.minor); for(int i = 0; i < [beacons count]; i++) //scanned beacons in Ranging { for(int j=0; j<[self.beacons count]; j++) //stored beacons in database { if (([[[beacons[i] proximityUUID] UUIDString] caseInsensitiveCompare:[((CBPeripheral *)self.beacons[j]).identifier UUIDString]]==NSOrderedSame) && ([[beacons[i] major] unsignedShortValue] == [[self.beacons[j] major] unsignedShortValue]) && ([[beacons[i] minor] unsignedShortValue] == [[self.beacons[j] minor] unsignedShortValue]) && ([[(Beacons *)self.beacons[j] enable]boolValue])) { NSLog(@"Found Beacon and enabled"); NSLog(@"Beacon UUID: %@",[beacons[i] proximityUUID]); NSLog(@"Beacon Major: %@",[beacons[i] major]); NSLog(@"Beacon Minor: %@",[beacons[i] minor]); //Finding Scanned Beacon Proximity and converting it to the Event of stored Beacon if ([beacons[i] proximity] == CLProximityImmediate) { NSLog(@"Immidiate Proximity: %@",beacon.proximityUUID); [self.beaconsRange replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:At_Beacon]]; //[self.beaconsTableView reloadData]; if ([[self.beacons[j] event] isEqualToString:EventImmidiate]) { NSLog(@"Close Event matched"); // [self performAction:[(Beacons *)self.beacons[j] action]]; } } else if ([beacons[i] proximity] == CLProximityNear) { NSLog(@"Near Proximity: %@",beacon.proximityUUID); [self.beaconsRange replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:NEAR]]; //[self.beaconsTableView reloadData]; if ([[self.beacons[j] event] isEqualToString:EventNear]) { NSLog(@"Near Event matched"); //[self performAction:[(Beacons *)self.beacons[j] action]]; } } else if ([beacons[i] proximity] == CLProximityFar) { NSLog(@"Far Proximity: %@",beacon.proximityUUID); [self.beaconsRange replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:FAR]]; //[self.beaconsTableView reloadData]; } else if ([beacons[i] proximity] == CLProximityUnknown) { NSLog(@"Unknown Proximity: %@",beacon.proximityUUID); [self.beaconsRange replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:UNKNOWN]]; //[self.beaconsTableView reloadData]; } } } } } else { NSLog(@"No beacon found!"); } } -(void)reloadBeacons { if(!self.locationManager){ self.locationManager = [[CLLocationManager alloc]init]; // New iOS 8 request for Always Authorization, required for iBeacons to work! if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [self.locationManager requestAlwaysAuthorization]; } self.locationManager.pausesLocationUpdatesAutomatically = NO; self.locationManager.delegate = self; self.regions = [[NSMutableArray alloc]initWithCapacity:[[Utility getBeaconsUUIDS] count]]; for (int index = 0; index < [[Utility getBeaconsUUIDS] count]; index++) { [self.regions addObject:[NSNull null]]; } } //[self.beaconsTableView reloadData]; //This will put a delay of 5 seconds between Action trigger. double delayInSeconds = 5.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ if (shouldStopAction) { //If the view is disappeared then dont perfom Action isActionPerformed = YES; } else { //if the view is appeared then perform Action isActionPerformed = NO; } }); self.beaconsRange = [[NSMutableArray alloc] initWithCapacity:[self.beacons count]]; for (int index = 0; index < [self.beacons count]; index++) { [self.beaconsRange addObject:[NSNull null]]; } /* * Create Regions for each unique Beacon UUID provided in the app and these should be fixed and known * and assign each region unique identifier * if Beacon is saved with one of these provided UUIDs then register Region having that UUID * Unregister Region if there is not any saved or enabled Beacon found having that UUID */ for(int regionIndex = 0; regionIndex < [[Utility getBeaconsUUIDS]count]; regionIndex++ ) { BOOL isBeaconFound = NO; BOOL isBeaconEnable = NO; for(int beaconIndex = 0; beaconIndex < [self.beacons count]; beaconIndex++) { if ([[[[Utility getBeaconsUUIDS] objectAtIndex:regionIndex] UUIDString] caseInsensitiveCompare:[((CBPeripheral *)self.beacons[beaconIndex]).identifier UUIDString]]==NSOrderedSame) { isBeaconFound = YES; isBeaconEnable = YES; // // if ([[(Beacons *)[self.beacons objectAtIndex:beaconIndex]enable]boolValue]) { // isBeaconEnable = YES; // } } } //if Beacon/Beacons Found in Region (regionIndex) and //atleast one Beacon is enabled in that Region then check the corresponding Region // if Region is not exist already then create Region and start Monitoring and Ranging if (isBeaconFound && isBeaconEnable) { NSLog(@"Atleast one Beacon is enable in Region %d with UUID %@",regionIndex, [[[Utility getBeaconsUUIDS]objectAtIndex:regionIndex]UUIDString]); if ([[self.regions objectAtIndex:regionIndex] isEqual:[NSNull null]]) { NSLog(@"Creating Region %d with UUID %@",regionIndex,[[[Utility getBeaconsUUIDS]objectAtIndex:regionIndex]UUIDString]); [self.regions replaceObjectAtIndex:regionIndex withObject:[Utility getRegionAtIndex:regionIndex]]; [self.locationManager startMonitoringForRegion:[self.regions objectAtIndex:regionIndex]]; [self.locationManager startRangingBeaconsInRegion:[self.regions objectAtIndex:regionIndex]]; } else { NSLog(@"Region %d already exist with UUID %@",regionIndex,[[[Utility getBeaconsUUIDS]objectAtIndex:regionIndex]UUIDString]); } } // if NO Beacon found or No Beacon is enable in Region (regionIndex) then check the corresponding Region // if Region exist already then stop Monitoring and Ranging and assign nil to Region else { NSLog(@"No beacon is found or enable in Region %d with UUID %@",regionIndex,[[[Utility getBeaconsUUIDS]objectAtIndex:regionIndex]UUIDString]); if (![[self.regions objectAtIndex:regionIndex] isEqual:[NSNull null]]) { NSLog(@"Region %d with UUID %@ already exist and now removing it",regionIndex, [[[Utility getBeaconsUUIDS]objectAtIndex:regionIndex]UUIDString]); [self.locationManager stopMonitoringForRegion:[self.regions objectAtIndex:regionIndex]]; [self.locationManager stopRangingBeaconsInRegion:[self.regions objectAtIndex:regionIndex]]; [self.regions replaceObjectAtIndex:regionIndex withObject:[NSNull null]]; } } } } 更改为sum(wts) == 1
3)有很多不错的选择。我使用NLOPT_LN_COBYLA