Пример #1
0
// [[Rcpp::export]]
Rcpp::List asianOptionEngine(std::string averageType,
                             std::string type,
                             double underlying,
                             double strike,
                             double dividendYield, 
                             double riskFreeRate,
                             double maturity,
                             double volatility,
                             double first,
                             double length,
                             size_t fixings) {
                       
    QuantLib::Option::Type optionType = getOptionType(type);

    //from test-suite/asionoptions.cpp
    QuantLib::DayCounter dc = QuantLib::Actual360();
    QuantLib::Date today = QuantLib::Date::todaysDate();
    QuantLib::Settings::instance().evaluationDate() = today;

    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
        
    boost::shared_ptr<QuantLib::BlackScholesMertonProcess>
        stochProcess(new
                     QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                         QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                         QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                         QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));

    boost::shared_ptr<QuantLib::StrikedTypePayoff> 
        payoff(new QuantLib::PlainVanillaPayoff(optionType,strike));

    Rcpp::List rl = R_NilValue;
   
    if (averageType=="geometric"){
        boost::shared_ptr<QuantLib::PricingEngine> 
            engine(new
                   QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(stochProcess));
            
#ifdef QL_HIGH_RESOLUTION_DATE    
        // in minutes
        QuantLib::Date exDate(today.dateTime() + boost::posix_time::minutes(maturity * 360 * 24 * 60));
#else
        QuantLib::Date exDate = today + int(maturity * 360 + 0.5);
#endif                              
        boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
        QuantLib::ContinuousAveragingAsianOption option(QuantLib::Average::Geometric,
                                                        payoff, exercise);
        option.setPricingEngine(engine);
            
        rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                Rcpp::Named("delta") = option.delta(),
                                Rcpp::Named("gamma") = option.gamma(),
                                Rcpp::Named("vega") = option.vega(),
                                Rcpp::Named("theta") = option.theta(),
                                Rcpp::Named("rho") = option.rho(),
                                Rcpp::Named("divRho") = option.dividendRho());
            
    } else if (averageType=="arithmetic") {

        // TODO:  check fixings > 1, first, length
        if (first < 0) Rcpp::stop("Parameter 'first' must be non-negative.");
        if (length < 0) Rcpp::stop("Parameter 'length' must be non-negative.");
        if (fixings <= 1) Rcpp::stop("Parameter 'fixings' must be larger than one.");

        boost::shared_ptr<QuantLib::PricingEngine> engine =
            QuantLib::MakeMCDiscreteArithmeticAPEngine<QuantLib::LowDiscrepancy>(stochProcess)
            .withSamples(2047)
            .withControlVariate();
            
        //boost::shared_ptr<PricingEngine> engine =
        //    MakeMCDiscreteArithmeticASEngine<LowDiscrepancy>(stochProcess)
        //    .withSeed(3456789)
        //    .withSamples(1023);
            
        QuantLib::Time dt = length / (fixings - 1);

        std::vector<QuantLib::Time> timeIncrements(fixings);
        std::vector<QuantLib::Date> fixingDates(fixings);
        timeIncrements[0] = first;
        fixingDates[0] = today + QuantLib::Integer(timeIncrements[0] * 360 + 0.5);
        for (QuantLib::Size i=1; i<fixings; i++) {
            timeIncrements[i] = i*dt + first;
#ifdef QL_HIGH_RESOLUTION_DATE
            fixingDates[i]= QuantLib::Date(today.dateTime() + boost::posix_time::minutes(timeIncrements[i] * 360 * 24 * 60));
#else            
            fixingDates[i] = today + QuantLib::Integer(timeIncrements[i]*360+0.5);
#endif           
        }
        QuantLib::Real runningSum = 0.0;
        QuantLib::Size pastFixing = 0;

        boost::shared_ptr<QuantLib::Exercise> 
            exercise(new QuantLib::EuropeanExercise(fixingDates[fixings-1]));

        QuantLib::DiscreteAveragingAsianOption option(QuantLib::Average::Arithmetic, 
                                                      runningSum,
                                                      pastFixing, 
                                                      fixingDates,
                                                      payoff, 
                                                      exercise);
        option.setPricingEngine(engine);
        rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                Rcpp::Named("delta") = R_NaReal,
                                Rcpp::Named("gamma") = R_NaReal,
                                Rcpp::Named("vega") = R_NaReal,
                                Rcpp::Named("theta") = R_NaReal,
                                Rcpp::Named("rho") = R_NaReal,
                                Rcpp::Named("divRho") = R_NaReal);
    }
    return rl;
}
Пример #2
0
void game::run()
{
	//MissileDesc projectile(*this);
	towerDesc towr(this);

	std::string txt;

	std::string txt2 = "Life:";

	std::string txt3 = "Money:";

	std::string main = "Cam Pos";

	std::string txt4 = "Game Over";

	std::list<SceneObject *> troll;

	endgame = false;
	mouseUp = false;

	float dir = 0.0f;

	float spot_dir = 45.0f;
    float aspect_time = 0.0f;

	towerCount = 0;
	cost = 0;

	life = 20;
	money = 10;
	quit = false;
	cameraRestricted = false;
	
	selected_tower = "";

	std::stringstream ss2 (std::stringstream::in | std::stringstream::out);
	std::stringstream ss3 (std::stringstream::in | std::stringstream::out);

	/*GUI app;
	int retval = app.main(args);

	if (retval == 0)
	{
		return retval;
	}*/


	Quaternionf camera_orientation(55.0f, 0.0f, 0.0f, angle_degrees, order_YXZ);
		
	clan::OpenGLWindowDescription opengl_desc;
	opengl_desc.set_version(3, 2, false);
	clan::OpenGLTarget::set_description(opengl_desc);

	//Scene test;
	//clan::SceneCamera camera(test);
	//DisplayWindowDescription innerwindow("Hello World", Size(640, 480), true);
	//innerwindow.set_allow_resize(true);
	//innerwindow.set_fullscreen(true);

	clan::DisplayWindowDescription win_desc;
	win_desc.set_allow_resize(true);
	win_desc.set_title("Main");
	win_desc.set_size(clan::Size( 1100, 900 ), false);
	DisplayWindow window(win_desc);	
	//DisplayWindow window("main", 1200, 900, false, true);	
	//window.maximize();
	//DisplayWindow window(innerwindow);

	Rect viewport = window.get_viewport();

	GraphicContext gc = window.get_gc();

	ResourceManager resources;
	SceneCache::set(resources, std::shared_ptr<SceneCache>(new AppSceneCache()));

	ResourceManager sound_resources = XMLResourceManager::create(XMLResourceDocument("../Resources/resources.xml"));
	sound_resources_=&sound_resources;

	std::string shader_path = "../Resources/Scene3D";

	Scene scene(gc, resources, shader_path);

	sceneHolder = &scene;

	SceneCamera camera(scene);
	scene.set_camera(camera);
	scene.set_viewport(gc.get_size());

	camera.set_orientation(camera_orientation);
	camera.set_position(Vec3f(0.0f, 40.0f, down));

	Canvas canvas(window);

	image_hp = Image(canvas, "../Resources/Images/heart.png");
	image_hp.set_alignment(origin_center);
	image_hp.set_scale(0.07, 0.07);

	image_coin = Image(canvas, "../Resources/Images/coin.png");
	image_coin.set_alignment(origin_center);
	image_coin.set_scale(0.3, 0.3);


	GUIWindowManagerDirect direct(window, canvas);

	GUIManager maingui(direct, "../Resources");

	GUIComponent *win_comp = new GUIComponent(&maingui, win_desc, "");

	radial_menu = new RadialMenu(win_comp);

	radial_menu->func_selected.set(this, &game::on_radial_menu_itemselected);

	//GameComponent game_component(viewport, &maingui);

	/*Rect toolbar_rect = Rect((viewport.get_width() - 448) / 2, viewport.bottom - 56, (viewport.get_width() - 448) / 2 + 448, viewport.bottom);
	Toolbar toolbar(toolbar_rect, &game_component);	// GameComponent is the "desktop" that the toolbar sits on, as an owner

	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell1.png"), Sprite(canvas, "../Resources/Images/spell1_selected.png"), Sprite(canvas, "../Resources/Images/spell1_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell2.png"), Sprite(canvas, "../Resources/Images/spell2_selected.png"), Sprite(canvas, "../Resources/Images/spell2_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell3.png"), Sprite(canvas, "../Resources/Images/spell3_selected.png"), Sprite(canvas, "../Resources/Images/spell3_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell4.png"), Sprite(canvas, "../Resources/Images/spell4_selected.png"), Sprite(canvas, "../Resources/Images/spell4_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell5.png"), Sprite(canvas, "../Resources/Images/spell5_selected.png"), Sprite(canvas, "../Resources/Images/spell5_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell6.png"), Sprite(canvas, "../Resources/Images/spell6_selected.png"), Sprite(canvas, "../Resources/Images/spell6_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell7.png"), Sprite(canvas, "../Resources/Images/spell7_selected.png"), Sprite(canvas, "../Resources/Images/spell7_clicked.png"));
	*/

	InputDevice keyboard = window.get_ic().get_keyboard();
	InputDevice mouse = window.get_ic().get_mouse();
	clan::Font font(canvas, "Tahoma", 30); // The clan prefix is required on linux due to a namespace conflict

	SceneModel plane(gc, scene, "plane");
	SceneModel box(gc, scene, "box");
	SceneModel tower(gc, scene, "tower");
	SceneModel gate(gc,scene,"gate");

	SceneObject object(scene, plane, Vec3f(0.0f, 0.0f, 0.0f));
	
	object.rotate(180.0f, 0.0f, 0.0f);

	scene.show_skybox_stars(false);

	/*SceneObject box0(scene, tower, Vec3f(20.0f, 5.0f, 0.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject box1(scene, tower, Vec3f(-20.0f, 5.0f, 0.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject box2(scene, tower, Vec3f(0.0f, 5.0f, 20.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject box3(scene, tower, Vec3f(0.0f, 5.0f, -20.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject tower[10];*/

	SceneObject theGate(scene, gate, Vec3f(-75.0f,5.0f,60.0f), Quaternionf(0.0f,0.0f,0.0f,angle_degrees,order_YXZ));
	theGate.set_scale(Vec3f(1.0f,2.0f,2.0f));

	std::vector<SceneLight> omni_lights;
	for (int i = 0; i < 4; i++)
	{
		SceneLight omni(scene);
		omni.set_type(SceneLight::type_omni);
		omni.set_color(Vec3f(0.05f));
		omni.set_position(Quaternionf(45.0f, 45.0f + i * 90.0f, 0.0f, angle_degrees, order_YXZ).rotate_vector(Vec3f(0.0f, 0.0f, -100.0f)));
		omni.set_attenuation_end(200.0f);
		omni.set_ambient_illumination(0.025f);

		omni_lights.push_back(omni);
	}

	SceneLight spot(scene);
    spot.set_type(SceneLight::type_spot);
    spot.set_orientation(Quaternionf(45.0f, 45.0f, 0.0f, angle_degrees, order_YXZ));
    spot.set_position(spot.get_orientation().rotate_vector(Vec3f(-55.0f, 90.0f, -550.0f)));
	//spot.set_position(Vec3f(-250, 100, -430));
    spot.set_color(Vec3f(1.0f, 1.0f, 0.8f));
    spot.set_falloff(45.0f);
    spot.set_hotspot(15.0f);
    spot.set_attenuation_start(150.0f);
    spot.set_attenuation_end(1500.0f);
    spot.set_shadow_caster(true);
    spot.set_rectangle_shape(false);
	//spot.set_ambient_illumination(true);
    spot.set_aspect_ratio(1.0f);

	/*SceneLight spot(scene);
    spot.set_type(SceneLight::type_spot);
    spot.set_orientation(Quaternionf(30.0f, 30.0f, 0.0f, angle_degrees, order_YXZ));
    spot.set_position(spot.get_orientation().rotate_vector(Vec3f(0.0f, 0.0f, -100.0f)));
    spot.set_color(Vec3f(1.0f, 1.0f, 0.8f));
    spot.set_falloff(45.0f);
    spot.set_hotspot(15.0f);
    spot.set_attenuation_start(20.0f);
    spot.set_attenuation_end(200.0f);
    spot.set_shadow_caster(true);
    spot.set_rectangle_shape(false);
    spot.set_aspect_ratio(1.0f);*/

    /*SceneLight spot2(scene);
    spot2.set_type(SceneLight::type_spot);
    spot2.set_position(Vec3f(0.0f, 100.0f, 0.0f));
    spot2.set_color(Vec3f(1.0f, 1.0f, 1.0f) * 3.0f);
    spot2.set_falloff(35.0f);
    spot2.set_hotspot(30.0f);
    spot2.set_attenuation_start(20.0f);
    spot2.set_attenuation_end(130.0f);
    spot2.set_shadow_caster(true);
    spot2.set_rectangle_shape(false);
    spot2.set_ambient_illumination(0.025f);*/

	wm.NodeArray[0].setPos(75.0f,1.25f,0.0f);
	wm.NodeArray[1].setPos(-60.0f,1.25f,0.0f);
	wm.NodeArray[2].setPos(-55.0f,1.25f,-65.0f);
	wm.NodeArray[3].setPos(60.0f,1.25f,-60.0f);
	wm.NodeArray[4].setPos(55.0f,1.25f,65.0f);
	wm.NodeArray[5].setPos(-80.0f,1.25f,60.0f);
	
	Physics3DShape box_shape = Physics3DShape::box(Vec3f(5.0f));
	Physics3DShape plane_shape = Physics3DShape::box(Vec3f(75.0f, 1.0f, 75.0f));
	Physics3DShape sphere_shape = Physics3DShape::sphere(2.0f);

	Physics3DObject phys_plane(physics_world, plane_shape, Vec3f(0.0f, -0.5f, 0.0f));

	/*Physics3DObject phys_box0(physics_world, box_shape, Vec3f(20.0f, 5.0f, 0.0f), box0.get_orientation());
	Physics3DObject phys_box1(physics_world, box_shape, Vec3f(-20.0f, 5.0f, 0.0f), box1.get_orientation());
	Physics3DObject phys_box2(physics_world, box_shape, Vec3f(0.0f, 5.0f, 20.0f), box2.get_orientation());
	Physics3DObject phys_box3(physics_world, box_shape, Vec3f(0.0f, 5.0f, -20.0f), box3.get_orientation());
	Physics3DObject phys_box[10];*/

	Physics3DSweepTest sweep_test(physics_world);

	Physics3DRayTest raycast(physics_world);

	Slot slot_keyboard_key_down	= (window.get_ic().get_keyboard()).sig_key_down()	.connect(this,&game::on_key_down);
	Slot slot_keyboard_key_up	= (window.get_ic().get_keyboard()).sig_key_up()		.connect(this,&game::on_key_up);
	Slot slot_mouse_moved		= (window.get_ic().get_mouse()).sig_pointer_move()	.connect(this,&game::on_pointer_move);
	Slot slot_mouse_down			= (window.get_ic().get_mouse()).sig_key_down()		.connect(this,&game::on_pointer_down);
	Slot slot_mouse_up			= (window.get_ic().get_mouse()).sig_key_up()		.connect(this,&game::on_pointer_up);

	//________________________________________________________________
	//											           S O U N D S

	total_channels=3;
	current_channel=1;
	SoundBuffer music = SoundBuffer::resource("Music1",sound_resources);
	music.set_volume(0.3f);

	sound_session1.play();
	sound_session2.play();
	sound_session3.play();

	total_samples = 6;
	samples.resize(total_samples);
	samples[0] = SoundBuffer::resource("Explosion1",sound_resources);
	samples[1] = SoundBuffer::resource("Explosion2",sound_resources);
	samples[2] = SoundBuffer::resource("Hurt1",sound_resources);
	samples[3] = SoundBuffer::resource("Hurt2",sound_resources);
	samples[4] = SoundBuffer::resource("Powerup1",sound_resources);
	samples[5] = SoundBuffer::resource("Shoot1",sound_resources);
	
	for(int i = 0; i<total_samples; i++)
	{
		samples[i].set_volume(0.3f);
	}
	
	SoundBuffer_Session music_session = music.prepare();
	music_session_ = &music_session;

	music_session.set_looping(true);
	music_session.play();
	is_music_muted = false;

	/********Enemies(Jasper)************************/
	SceneObject enemyobj[30];
	wm.spawnCreeps();
	for(int i = 0; i < 30; i ++)
	{
		enemyobj[i] = SceneObject(scene, box);
		enemyobj[i].set_scale(Vec3f(0.25f));
		wm.enemyArray[i].setEnemyObject(&enemyobj[i]);
	}
	/***************************************/

	ElapsedTimer elapsed_timer;

	while (!quit)
	{
		float time_elapsed = elapsed_timer.seconds_elapsed();

		/*spot_dir = std::fmod(spot_dir + time_elapsed * 30.0f, 90.0f);
		aspect_time = std::fmod(aspect_time + time_elapsed * 0.2f, 2.0f);

		spot2.set_aspect_ratio(clamp(aspect_time >= 1.0f ? 2.0f - aspect_time : aspect_time, 0.1f, 1.0f));
		spot2.set_orientation(Quaternionf(65.0f + (spot_dir >= 45.0f ? 90.0f - spot_dir : spot_dir), 60.0f, dir * 4.0f, angle_degrees, order_YXZ));
		*/
		// Draw with the canvas:
		/*canvas.clear(Colorf::cadetblue);
		canvas.draw_line(0, 110, 640, 110, Colorf::yellow);
		font.draw_text(canvas, 100, 100, "Hello World!", Colorf::lightseagreen);
		// Draw any remaining queued-up drawing commands oQAn canvas:
		canvas.flush();*/

		if (!endgame)
		{
			if (mouse.get_x() <= 0 && !cameraRestricted)
			{
				mouse.set_position(0, mouse.get_y());
				camera.set_position(camera.get_position()+Vec3f(-mouse_move_speed, 0.0f, 0.0f));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "x=0", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}
			if (mouse.get_y() <= 0 && !cameraRestricted)
			{
				mouse.set_position(mouse.get_x(), 0);
				camera.set_position(camera.get_position()+Vec3f(0.0f, 0.0f, mouse_move_speed));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "y=0", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}
			if (mouse.get_x() >= window.get_gc().get_width()-1 && !cameraRestricted)
			{
				mouse.set_position(window.get_gc().get_width()-1, mouse.get_y());
				camera.set_position(camera.get_position()+Vec3f(mouse_move_speed, 0.0f, 0.0f));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "x=windowRight", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}
			if (mouse.get_y() >= window.get_gc().get_height()-1 && !cameraRestricted)
			{
				mouse.set_position(mouse.get_x(), window.get_gc().get_height()-1);
				camera.set_position(camera.get_position()+Vec3f(0.0f, 0.0f, -mouse_move_speed));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "y=windowBottom", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}

			if (mouseUp)
			{
				if (selected_tower == "Tower 1")
				{
					towr.set_type(towr.t_bullet);
					cost = 10;
				}
				else if (selected_tower == "Tower 2")
				{
					towr.set_type(towr.t_energy);
					cost = 15;
				}
				else if (selected_tower == "Tower 3")
				{
					towr.set_type(towr.t_rocket);
					cost = 20;
				}

				scene.unproject(mouse_pos, start, end);
				end *= 151;
				test = start + end;

				if (raycast.test(start, test))
				{
					if (towerCount < 10 && money >= cost)
					{
						towr.set_pos(Vec3f(raycast.get_hit_position().x, 5.0f, raycast.get_hit_position().z));
						towr.create(scene, tower, physics_world);

						money -= cost;
						towerCount++;
						cost = 0;
					}
				}
				mouseUp = false;
				//float x = mouse.get_x() - scene.world_to_projection().get_origin_x();
				//tower[0] = SceneObject(scene, box, Vec3f(camera.get_position().x, 5.0f, camera.get_position().z));
				//tower[0].set_position(Vec3f(0.0f, 5.0f, 0.0f));
				//window.flip();
				//canvas.clear(Colorf::cadetblue);
				/*canvas.draw_line(0, 110, 640, 110, Colorf::yellow);
				font.draw_text(canvas, 100, 100, "Hello World!", Colorf::lightseagreen);
				// Draw any remaining queued-up drawing commands oQAn canvas:
				canvas.flush();
				// Present the frame buffer content to the user:
				window.flip();*/
			}

			if (mouse.get_keycode(0))
			{
				
				//maingui.process_messages(0);
				//test.update();
				//show_radial_menu(mouse.get_position());
			}

			/*if (mouse.get_keycode(1))
			{
				scene.unproject(mouse.get_position(), start, end);
				end *= 151;
				Vec3f test = start + end;
				if (raycast.test(start, test))
				{
					Physics3DObject hit = raycast.get_hit_object();
					font.draw_text(canvas, 400, 100, "hit", Colorf::lightseagreen);
					//hit.set_position(Vec3f(0.0f, -10.0f, 0.0f));
					std::stringstream ss3 (std::stringstream::in | std::stringstream::out);
					ss3 << hit.get_position().y;
					txt3 = ss3.str();

					font.draw_text(canvas, 550, 100, txt3, Colorf::lightseagreen);
				}
				
				//projectile.set_pos(Vec3f(raycast.get_hit_position().x, 5.0f, raycast.get_hit_position().z));
				//projectile.fire(scene, box, physics_world);
			
				//canvas.clear(Colorf::white);
				//window.flip();
			}*/
			if (keyboard.get_keycode(keycode_control))
			{
				if (window.is_fullscreen())
				{
					//innerwindow.set_fullscreen(false);
					window.set_size(640, 480, true);
					window.restore();
				}
				else
					window.set_size(640, 480, false);
			}

			if (camera.get_position().x <= left)
			{
				camera.set_position(Vec3f(left, camera.get_position().y, camera.get_position().z));
			}
		
			if (camera.get_position().x >= right)
			{
				camera.set_position(Vec3f(right, camera.get_position().y, camera.get_position().z));
			}
		
			if (camera.get_position().z >= top)
			{
				camera.set_position(Vec3f(camera.get_position().x, camera.get_position().y, top));
			}

			if (camera.get_position().z <= down)
			{
				camera.set_position(Vec3f(camera.get_position().x, camera.get_position().y, down));
			}

			/*if(objects_for_deletion.size()>0)
			{
				std::list<Gameobject *>::iterator it;
				for(it=objects_for_deletion.begin(); it!= objects_for_deletion.end(); ++it)
				{
					delete (*it);
					//towerCount--;
				}

				objects_for_deletion.clear();
			}*/

			if(towerObjects.size()>0)
			{
				std::vector<Gameobject *>::iterator it;
				int counter = 0;
				for(it=towerObjects.begin(); it!= towerObjects.end(); ++it)
				{
					towerObjects.at(counter)->update(time_elapsed, wm.enemyArray, 30);
					counter++;
				}
			}

			if(missileObjects.size()>0)
			{
				std::list<Gameobject *>::iterator it;
				for(it=missileObjects.begin(); it!= missileObjects.end();)
				{
					//if (!(*it)->checkActive())
					(*it)->update(time_elapsed, wm.enemyArray);

					if ((*it)->checkActive())
					{
						delete(*it);
						it = missileObjects.erase(it);						
					}
					else
						it++;
				}
			}

			/*******Enemies(Updates)************************/
			wm.Update(1);
			//time_lasttime = time_elapsed;

			if(wm.life > 0)
			{
				// Put a screen here
				life -= wm.life;
				wm.life = 0;
			}

			if (wm.currLevel == 3)
			{
				endgame = true;
			}
			/***********************************************/

			//scene.update(gc, time_elapsed);

			txt3 = ":";
			ss3.str("");
			ss3.clear();
			ss3 << money;
			txt3 += ss3.str();

			font.draw_text(canvas, 550, 50, txt3, Colorf::lightseagreen);

			if (life < 0)
			{
				endgame = true;
			}

			scene.render(gc);

			/*canvas.clear(clan::Colorf(0.0f,0.0f,0.0f));
			std::stringstream ss (std::stringstream::in | std::stringstream::out);
			ss << game_time.get_time_elapsed();
			std::string troll = ss.str();
			font.draw_text(canvas, 100, 100, troll, Colorf::lightseagreen);*/
			//canvas.clear(clan::Colorf(0.0f,0.0f,0.0f));
			std::stringstream ss (std::stringstream::in | std::stringstream::out);
			ss << scene.world_to_projection().get_origin_x();
			txt = ss.str();

			txt2 = ":";
			ss2.str("");
			ss2.clear();
			ss2 << life;
			txt2 += ss2.str();

			font.draw_text(canvas, 150, 50, txt2, Colorf::lightseagreen);

			//maingui.process_messages(0);

			/*font.draw_text(canvas, 0, 100, main, Colorf::lightseagreen);
			font.draw_text(canvas, 150, 100, txt, Colorf::lightseagreen);
			font.draw_text(canvas, 250, 100, txt2, Colorf::lightseagreen);
			canvas.draw_line(0, 110, 640, 110, Colorf::yellow);*/

			maingui.render_windows();
			
			image_hp.draw(canvas, 100, 45); 
			image_coin.draw(canvas, 500, 45);
			
			window.flip();

			// Read messages from the windowing system message queue, if any are available:
			KeepAlive::process();
		}

		else
		{
			//maingui.render_windows();
			canvas.clear(Colorf::black);

			font.draw_text(canvas, 450, 400, txt4, Colorf::lightseagreen);

			window.flip();

			// Read messages from the windowing system message queue, if any are available:
			KeepAlive::process();
		}
	}
}
Пример #3
0
int
main(int argc, char *argv[])
{
	const int KERNEL_NPROC = 64;
	const int CHILD_STARTUP_SLEEP = 100;
	const int MIN_UPTIME = 1000;
	if(argc!=2) {
    	printf(1, "%s", "USAGE: graphs.c <int testnum>\n");
		exit();
	}
	int option = atoi(argv[1]);

	if(option == 0) {
		//SAME PERCENT RESERVE
		
		//Make this reserve 50
		int returnval = reserve(50);
		if(returnval < 0) {
			printf(1, "ERROR: reserve failed\n");
		}
		//Test 4 reserve procs with 50% reserve
		//Expect ~same number of times chosen
		const int NUM_PROC = 3;
		int pids[NUM_PROC+1];
		int chosen[NUM_PROC+1];
		int time[NUM_PROC+1];
		int charge[NUM_PROC+1];
		int i;
		int pid;
		pids[0] = getpid();
                
                for(i=0; i<NUM_PROC; i++) {
			pid = fork();
			if(pid == 0) {
				//child
				returnval = reserve(50);
				if(returnval < 0) {
					printf(1, "ERROR: reserve failed\n");
				}
				break;
			}
			else {
				//parent
				pids[i+1] = pid;
			}
		}
		if(pid == 0) {
			sleep(CHILD_STARTUP_SLEEP*2);
			while(1) {
			}		
		}
		else {
			while(1) {
				sleep(MIN_UPTIME);
				struct pstat p;
				struct pstat *stats = &p;
				int returnval = getpinfo(stats);
				if(returnval < 0) {
					continue;
				}
				int count = 0;
				for(i=0; i<KERNEL_NPROC; i++) {
					int j;
					for(j=0; j<NUM_PROC+1; j++) {
						if(pids[j] == stats->pid[i] || getpid() == stats->pid[i]) {
							chosen[j] = stats->chosen[i];
							time[j] = stats->time[i];
							charge[j] = stats->charge[i];
							count++;
						}
					}
				}
				for(i=0; i<NUM_PROC+1; i++) {
					//pid,chosen,time,charge
					printf(1, "%d,%d,%d,%d\n", pids[i], chosen[i], time[i], charge[i]);
				}
			}
		}
	}

	/*else if(option == 2) {
		//DIFF BID SPOT
		
		//Make this spot with bid 50
		int returnval;
		returnval = spot(50);
		if(returnval < 0) {
			printf(1, "ERROR: spot failed\n");
		}
		//Expect significant difference in number of times chosen between bid levels
		const int NUM_PROC = 10;
		int pids[NUM_PROC+1];
		int chosen[NUM_PROC+1];
		int time[NUM_PROC+1];
		int charge[NUM_PROC+1];
		int i;
		int pid;
		int bid = 20;
		
		pids[0] = getpid();

                for(i=0; i<NUM_PROC; i++) {
			pid = fork();
			if(pid == 0) {
				//child
				returnval = spot(bid);
				if(returnval < 0) {
					printf(1, "ERROR: spot failed\n");
				}
				break;
			}
			else {
				//parent
				if(i==4) {
					bid+=10;
				}
				pids[i+1] = pid;
			}
		}
		if(pid == 0) {
			sleep(CHILD_STARTUP_SLEEP);
			while(1) {
			}
		}
		else {
			while(1) {
				sleep(MIN_UPTIME);
				struct pstat p;
				struct pstat *stats = &p;
				int returnval = getpinfo(stats);
				if(returnval < 0) {
					printf(1, "getpinfo failed\n");
					continue;
				}
				int count = 0;
				for(i=0; i<KERNEL_NPROC; i++) {
					int j;
					for(j=0; j<NUM_PROC+1; j++) {
						if(pids[j] == stats->pid[i]) {
							chosen[j] = stats->chosen[i];
							time[j] = stats->time[i];
							charge[j] = stats->charge[i];
							count++;
						}
					}
				}
				for(i=0; i<NUM_PROC+1; i++) {
					//pid,chosen,time,charge
					printf(1, "%d,%d,%d,%d\n", pids[i], chosen[i], time[i], charge[i]);
				}
			}
		}
	}

	else if(option == 3) {
		//DIFF PERCENT RESERVE
	
		//Make this reserve with 10 percent
		int returnval;
		returnval = reserve(10);
		if(returnval < 0) {
			printf(1, "ERROR: reserve failed\n");
		}
		//Test different reservation sizes
		//Sizes are 10 (parent proc), 20, 30, 40, 50, 50
		const int NUM_PROC = 5;
		int pids[NUM_PROC+1];
		int chosen[NUM_PROC+1];
		int time[NUM_PROC+1];
		int charge[NUM_PROC+1];
		int i;
		int pid;
		int percent = 20;
		
		pids[0] = getpid();

                for(i=0; i<NUM_PROC; i++) {
			pid = fork();
			if(pid == 0) {
				//child
				returnval = reserve(percent);
				if(returnval < 0) {
					printf(1, "ERROR: spot failed\n");
				}
				break;
			}
			else {
				//parent
				if(i<NUM_PROC-2) {
					percent+=10;
				}
				pids[i+1] = pid;
			}
		}
		if(pid == 0) {
			sleep(CHILD_STARTUP_SLEEP);
			while(1){
			}
		}
		else {
			while(1) {
				sleep(MIN_UPTIME);
				struct pstat p;
				struct pstat *stats = &p;
				int returnval = getpinfo(stats);
				if(returnval < 0) {
					continue;
				}
				int count = 0;
				for(i=0; i<KERNEL_NPROC; i++) {
					int j;
					//Find pid in pstat
					for(j=0; j<NUM_PROC+1; j++) {
						if(pids[j] == stats->pid[i]) {
							chosen[j] = stats->chosen[i];
							time[j] = stats->time[i];
							charge[j] = stats->charge[i];
							count++;
						}
					}
				}
				for(i=0; i<NUM_PROC+1; i++) {
					//pid,chosen,time,charge
					printf(1, "%d,%d,%d,%d\n", pids[i], chosen[i], time[i], charge[i]);
				}
			}
		}
	}*/

	/*else if(option == 4) {
		//RESERVE CALL TOO LOW


		//Test user attempting to reserve a percentage < 0
		//Expect -1 to be returned from the reserve call
		int flag = reserve(-1);
		if(flag < 0) {
			printf(1, "Test succeeded, reserve call failed.\n");
		}
		else {
			printf(1, "ERROR: test failed. Reserve call did not fail when percentage < 0 was input.");
		}
		exit();
	}

	else if(option == 5) {
		//RESERVE CALL TOO HIGH

		//Test user attempting to reserve a percentage > 100
		//Expect -1 to be returned from the reserve call
		int flag = reserve(101);
		if(flag < 0) {
			printf(1, "Test succeeded, reserve call failed.\n");
		}
		else {
			printf(1, "ERROR: test failed. Reserve call did not fail when a percantage > 100 was input.");
		}
		exit();
	}

	else if(option == 6) {
		//RESERVE SUM TOO HIGH

		//Make this reserve of 100
		int returnval = reserve(100);
		if(returnval < 0) {
			printf(1, "ERROR: reserve failed\n");
		}
		//Test user attempting to reserve too much cpu (currentreservation + newreservation > 200)
		//Expect -1 to be returned from second child's reserve call
		const int NUM_PROC = 2;
		int pids[NUM_PROC];
		int i;
		int pid;
        for(i=0; i<NUM_PROC; i++) {
			pid = fork();
			if(pid == 0) {
				//child
				int flag = reserve(100);
				if(i==0 && flag < 0) {
					printf(1, "ERROR: incorrect reserve failed\n");
				}
				if(i==1 && flag < 0) {
					printf(1, "Test succeeded, reserve call failed.\n");
				}
				else if(i==1) {
					printf(1, "ERROR: test failed. Reserve call did not fail when the total process percent exceeded 200.");
				}
				break;
			}
			else {
				pids[i] = pid;
				sleep(100);
			}
		}
		if(pid == 0) {
			while(1);
		}
		else {
			sleep(500);
			for(i=0; i<NUM_PROC; i++) { 
				kill(pids[i]);
				wait();
			}
			exit();
		}
	}*/

	else if(option == 7) {
		//CHARGE TEST

		//Make this reserve with 100
		int returnval = reserve(100);
		if(returnval < 0) {
			printf(1,"ERROR: spot call failed\n");
		}
		//Test charge in dollars
		//Expecting time*bid/nanodollars = charge
		//NOTE: ADD 10 to time and 1 to chosen to insure no error
		struct pstat p;
		struct pstat *stats = &p;
                //returnval = getpinfo(stats);
		int prevchosen = 0;
		int prevtime = 0;
		int i;
		int pid = fork();
		if(pid == 0) {
			returnval = spot(100);
			if(returnval < 0) {
				printf(1,"ERROR: reserve call failed\n");
			}
			while(1) {
			}
		}
		sleep(MIN_UPTIME);
		returnval = getpinfo(stats);
		if(returnval >= 0) {
			for(i=0; i<KERNEL_NPROC; i++) {
				if(pid == stats->pid[i]) {
					printf(1, "%d,%d,%d,%d\n", stats->pid[i], stats->chosen[i]-prevchosen, stats->time[i]-prevtime, stats->charge[i]);
				}
			}
		}
		else {
			printf(1, "ERROR: getpinfo failed\n");
		}
		while(1);
	}
	else if(option == 9) {
		//STARVATION TEST EXTRA CREDIT

		int returnval = reserve(100);
		if(returnval < 0) {
			printf(1, "ERROR: reserve failed\n");
		}
		//Test starvation
		//Expect ~same number of times chosen
		const int NUM_PROC = 4;
		int pids[NUM_PROC+1];
		int chosen[NUM_PROC+1];
		int time[NUM_PROC+1];
		int charge[NUM_PROC+1];
		int i;
		int pid;
		pids[0] = getpid();
        for(i=0; i<NUM_PROC; i++) {
			pid = fork();
			if(pid == 0) {
				//child
				if(i==0) {
					returnval = reserve(100);
					if(returnval < 0) {
						printf(1, "ERROR: reserve failed\n");
					}
				}
				else {
					returnval = spot(100);
					if(returnval < 0) {
						printf(1, "ERROR: reserve failed\n");
					}
				}
				break;
			}
			else {
				//parent
				if(i==0) {
					sleep(20);
				}
				pids[i+1] = pid;
			}
		}
		if(pid == 0) {
			while(1) {
			}		
		}
		else {
			while(1) {
				sleep(MIN_UPTIME);
				struct pstat p;
				struct pstat *stats = &p;
				int returnval = getpinfo(stats);
				if(returnval < 0) {
					continue;
				}
				int count = 0;
				for(i=0; i<KERNEL_NPROC; i++) {
					int j;
					for(j=0; j<NUM_PROC+1; j++) {
						if(pids[j] == stats->pid[i] || getpid() == stats->pid[i]) {
							chosen[j] = stats->chosen[i];
							time[j] = stats->time[i];
							charge[j] = stats->charge[i];
							count++;
						}
					}
				}
				for(i=0; i<NUM_PROC+1; i++) {
					//pid,chosen,time,charge
					printf(1, "%d,%d,%d,%d\n", pids[i], chosen[i], time[i], charge[i]);
				}
			}
		}
	}
 return 0;
}
Пример #4
0
RcppExport SEXP AsianOption(SEXP optionParameters){

    try{
        Rcpp::List rparam(optionParameters);

        std::string avgType = Rcpp::as<std::string>(rparam["averageType"]);
        std::string type = Rcpp::as<std::string>(rparam["type"]);
        double underlying = Rcpp::as<double>(rparam["underlying"]);
        double strike = Rcpp::as<double>(rparam["strike"]);
        QuantLib::Spread dividendYield = Rcpp::as<double>(rparam["dividendYield"]);
        QuantLib::Rate riskFreeRate = Rcpp::as<double>(rparam["riskFreeRate"]);
        QuantLib::Time maturity = Rcpp::as<double>(rparam["maturity"]);
        //        int length = int(maturity*360 + 0.5); // FIXME: this could be better
        double volatility = Rcpp::as<double>(rparam["volatility"]);

        QuantLib::Option::Type optionType = getOptionType(type);

        //from test-suite/asionoptions.cpp
        QuantLib::DayCounter dc = QuantLib::Actual360();
        QuantLib::Date today = QuantLib::Date::todaysDate();
        QuantLib::Settings::instance().evaluationDate() = today;

        boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
        boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
        boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
        boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
        boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
        
        boost::shared_ptr<QuantLib::BlackScholesMertonProcess>
            stochProcess(new
                         QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));

        boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType,strike));

      

        QuantLib::Average::Type averageType = QuantLib::Average::Geometric;
        Rcpp::List rl = R_NilValue;
   
        if (avgType=="geometric"){
            averageType = QuantLib::Average::Geometric;
            boost::shared_ptr<QuantLib::PricingEngine> 
                engine(new
                       QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(stochProcess));
            
            QuantLib::Date exDate = today + int(maturity * 360 + 0.5);
            boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
            QuantLib::ContinuousAveragingAsianOption option(averageType, payoff, exercise);
            option.setPricingEngine(engine);
            
            rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                    Rcpp::Named("delta") = option.delta(),
                                    Rcpp::Named("gamma") = option.gamma(),
                                    Rcpp::Named("vega") = option.vega(),
                                    Rcpp::Named("theta") = option.theta(),
                                    Rcpp::Named("rho") = option.rho(),
                                    Rcpp::Named("divRho") = option.dividendRho(),
                                    Rcpp::Named("parameters") = optionParameters);
            
        } else if (avgType=="arithmetic"){
            averageType = QuantLib::Average::Arithmetic;

            boost::shared_ptr<QuantLib::PricingEngine> engine =
                QuantLib::MakeMCDiscreteArithmeticAPEngine<QuantLib::LowDiscrepancy>(stochProcess)
                .withSamples(2047)
                .withControlVariate();
            
            //boost::shared_ptr<PricingEngine> engine =
            //    MakeMCDiscreteArithmeticASEngine<LowDiscrepancy>(stochProcess)
            //    .withSeed(3456789)
            //    .withSamples(1023);
            
            QuantLib::Size fixings = Rcpp::as<double>(rparam["fixings"]);
            QuantLib::Time length = Rcpp::as<double>(rparam["length"]);
            QuantLib::Time first = Rcpp::as<double>(rparam["first"]);
            QuantLib::Time dt = length / (fixings - 1);

            std::vector<QuantLib::Time> timeIncrements(fixings);
            std::vector<QuantLib::Date> fixingDates(fixings);
            timeIncrements[0] = first;
            fixingDates[0] = today + QuantLib::Integer(timeIncrements[0] * 360 + 0.5);
            for (QuantLib::Size i=1; i<fixings; i++) {
                timeIncrements[i] = i*dt + first;
                fixingDates[i] = today + QuantLib::Integer(timeIncrements[i]*360+0.5);
            }
            QuantLib::Real runningSum = 0.0;
            QuantLib::Size pastFixing = 0;

            boost::shared_ptr<QuantLib::Exercise> 
                exercise(new QuantLib::EuropeanExercise(fixingDates[fixings-1]));

            QuantLib::DiscreteAveragingAsianOption option(QuantLib::Average::Arithmetic, 
                                                          runningSum,
                                                          pastFixing, 
                                                          fixingDates,
                                                          payoff, 
                                                          exercise);
            option.setPricingEngine(engine);
            rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                    Rcpp::Named("delta") = R_NaN,
                                    Rcpp::Named("gamma") = R_NaN,
                                    Rcpp::Named("vega") = R_NaN,
                                    Rcpp::Named("theta") = R_NaN,
                                    Rcpp::Named("rho") = R_NaN,
                                    Rcpp::Named("divRho") = R_NaN,
                                    Rcpp::Named("parameters") = optionParameters);
        } else {
            throw std::range_error("Unknown average type " + type);
        }      
    
        return rl;

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
    void AnalyticCompoundOptionEngine::calculate() const {

        QL_REQUIRE(strikeDaughter()>0.0,
                   "Daughter strike must be positive");

        QL_REQUIRE(strikeMother()>0.0,
                   "Mother strike must be positive");

        QL_REQUIRE(spot() >= 0.0, "negative or null underlying given");

        /* Solver Setup ***************************************************/
        Date helpDate(process_->riskFreeRate()->referenceDate());
        Date helpMaturity=helpDate+(maturityDaughter()-maturityMother())*Days;
        Real vol =process_->blackVolatility()->blackVol(helpMaturity,
                                                        strikeDaughter());

        Time helpTimeToMat=process_->time(helpMaturity);
        vol=vol*std::sqrt(helpTimeToMat);

        DiscountFactor dividendDiscount =
            process_->dividendYield()->discount(helpMaturity);

        DiscountFactor riskFreeDiscount =
            process_->riskFreeRate()->discount(helpMaturity);


        boost::shared_ptr<ImpliedSpotHelper> f(
                new ImpliedSpotHelper(dividendDiscount, riskFreeDiscount,
                                      vol, payoffDaughter(), strikeMother()));

        Brent solver;
        solver.setMaxEvaluations(1000);
        Real accuracy = 1.0e-6;

        Real X=0.0;
        Real sSolved=0.0;
        sSolved=solver.solve(*f, accuracy, strikeDaughter(), 1.0e-6, strikeDaughter()*1000.0);
        X=transformX(sSolved); // transform stock to return as in Wystup's book
        /* Solver Setup Finished*****************************************/

        Real phi=typeDaughter(); // -1 or 1
        Real w=typeMother(); // -1 or 1

        Real rho=std::sqrt(residualTimeMother()/residualTimeDaughter());
        BivariateCumulativeNormalDistributionDr78 N2(w*rho) ;

        DiscountFactor ddD=dividendDiscountDaughter();
        DiscountFactor rdD=riskFreeDiscountDaughter();
        //DiscountFactor ddM=dividendDiscountMother();
        DiscountFactor rdM=riskFreeDiscountMother();

        Real XmSM=X-stdDeviationMother();
        Real S=spot();
        Real dP=dPlus();
        Real dPT12=dPlusTau12(sSolved);
        Real vD=volatilityDaughter();

        Real dM=dMinus();
        Real strD=strikeDaughter();
        Real strM=strikeMother();
        Real rTM=residualTimeMother();
        Real rTD=residualTimeDaughter();

        Real rD=riskFreeRateDaughter();
        Real dD=dividendRateDaughter();

        Real tempRes=0.0;
        Real tempDelta=0.0;
        Real tempGamma=0.0;
        Real tempVega=0.0;
        Real tempTheta=0.0;
        Real N2XmSM=N2(-phi*w*XmSM,phi*dP);
        Real N2X=N2(-phi*w*X,phi*dM);
        Real NeX=N_(-phi*w*e(X));
        Real NX=N_(-phi*w*X);
        Real NT12=N_(phi*dPT12);
        Real ndP=n_(dP);
        Real nXm=n_(XmSM);
        Real invMTime=1/std::sqrt(rTM);
        Real invDTime=1/std::sqrt(rTD);

        tempRes=phi*w*S*ddD*N2XmSM-phi*w*strD*rdD*N2X-w*strM*rdM*NX;
        tempDelta=phi*w*ddD*N2XmSM;
        tempGamma=(ddD/(vD*S))*(invMTime*nXm*NT12+w*invDTime*ndP*NeX);
        tempVega=ddD*S*((1/invMTime)*nXm*NT12+w*(1/invDTime)*ndP*NeX);

        tempTheta+=phi*w*dD*S*ddD*N2XmSM-phi*w*rD*strD*rdD*N2X-w*rD*strM*rdM*NX;
        tempTheta-=0.5*vD*S*ddD*(invMTime*nXm*NT12+w*invDTime*ndP*NeX);

        results_.value=tempRes;
        results_.delta=tempDelta;
        results_.gamma=tempGamma;
        results_.vega=tempVega;
        results_.theta=tempTheta;
    }
Пример #6
0
GLight::GLight(const Any& any) {
    any.verifyName("GLight");

    if (any.type() == Any::TABLE) {
        *this = GLight();
        Vector3 spotTarget;
        bool hasSpotTarget = false;
        for (Any::AnyTable::Iterator it = any.table().begin(); it.hasMore(); ++it) {
            const std::string& key = toLower(it->key);
            if (key == "position") {
                position = it->value;
            } else if (key == "rightdirection") {
                rightDirection = it->value;
            } else if (key == "spotdirection") {
                spotDirection = Vector3(it->value).directionOrZero();
            } else if (key == "spottarget") {
                spotTarget = it->value;
                hasSpotTarget = true;
            } else if (key == "spotcutoff") {
                spotCutoff = it->value.number();
            } else if (key == "spotsquare") {
                spotSquare = it->value.boolean();
            } else if (key == "attenuation") {
                attenuation[0] = it->value[0].number();
                attenuation[1] = it->value[1].number();
                attenuation[2] = it->value[2].number();
            } else if (key == "color") {
                color = it->value;
            } else if (key == "enabled") {
                enabled = it->value.boolean();
            } else if (key == "specular") {
                specular = it->value.boolean();
            } else if (key == "diffuse") {
                diffuse = it->value.boolean();
            } else {
                any.verify(false, "Illegal key: " + it->key);
            }
        }
        if (hasSpotTarget) {
            spotDirection = (spotTarget - position.xyz()).direction();
        }
    } else if (toLower(any.name()) == "glight::directional") {

        *this = directional(any[0], any[1], 
            (any.size() > 2) ? any[2] : Any(true), 
            (any.size() > 3) ? any[3] : Any(true));

    } else if (toLower(any.name()) == "glight::point") {

        *this = point(any[0], any[1], 
            (any.size() > 2) ? any[2] : Any(1), 
            (any.size() > 3) ? any[3] : Any(0), 
            (any.size() > 4) ? any[4] : Any(0.5f), 
            (any.size() > 5) ? any[5] : Any(true), 
            (any.size() > 6) ? any[6] : Any(true));

    } else if (toLower(any.name()) == "glight::spot") {

        *this = spot(any[0], any[1], any[2], any[3],
            (any.size() > 4) ? any[4] : Any(1), 
            (any.size() > 5) ? any[5] : Any(0), 
            (any.size() > 6) ? any[6] : Any(0), 
            (any.size() > 7) ? any[7] : Any(true), 
            (any.size() > 8) ? any[8] : Any(true));
    } else {
        any.verify(false, "Unrecognized name");
    }
}
Пример #7
0
void spread(void)
{
    float min_cost;
    int ros_max, ros_base, dir;
    int row, col;
    int cell_count = 0, ncells = 0;
    struct cell_ptrHa *to_cell, *old_to_cell;
    struct costHa *pres_cell;

    /* initialize using arbitrary value, this value is never used except for debug */
    min_cost = 0;

    ncells = nrows * ncols;
    G_message
	("Finding spread time - number of cells visited in percentage ...  %3d%%",
	 0);
    pres_cell = (struct costHa *)G_malloc(sizeof(struct costHa));
    get_minHa(heap, pres_cell, heap_len);
    G_debug(2, "begin spread: cost(%d,%d)=%f", pres_cell->row, pres_cell->col,
	    pres_cell->min_cost);
    G_debug(2,
	    "              heap_len=%ld pres_cell->min_cost=%f time_lag=%d",
	    heap_len, pres_cell->min_cost, time_lag);
    while (heap_len-- > 0 && pres_cell->min_cost < init_time + time_lag + 1.0) {
	ros_max = DATA(map_max, pres_cell->row, pres_cell->col);
	ros_base = DATA(map_base, pres_cell->row, pres_cell->col);
	dir = DATA(map_dir, pres_cell->row, pres_cell->col);

	/*Select end cells of links of the present cell */
	select_linksB(pres_cell, least / 2, comp_dens);

#ifdef DEBUG
	to_cell = front_cell;
	while (to_cell != NULL) {
	    printf("(%d,%d) ", to_cell->row, to_cell->col);
	    to_cell = to_cell->next;
	}
#endif
	/*Get a cell in the list each time, and compute culmulative costs
	 *via the current spread cell*/
	to_cell = front_cell;
	while (to_cell != NULL) {
	    /*calculate cumulative costs,
	     *function returns -1 if detected a barrier */
	    if (cumulative
		(pres_cell, to_cell, ros_max, ros_base, dir,
		 &min_cost) == -1) {
		old_to_cell = to_cell;
		to_cell = to_cell->next;
		front_cell = to_cell;
		G_free(old_to_cell);
		continue;
	    }

	    G_debug(2, "	finish a link: cost(%d,%d)->(%d,%d)=%f",
		    pres_cell->row, pres_cell->col, to_cell->row,
		    to_cell->col, min_cost);
	    /*update the cumulative time/cost */
	    update(pres_cell, to_cell->row, to_cell->col, to_cell->angle,
		   min_cost);
	    old_to_cell = to_cell;
	    to_cell = to_cell->next;
	    front_cell = to_cell;
	    G_free(old_to_cell);
	}

	/*compute spotting fires */
	if (spotting)
	    spot(pres_cell, dir);

	/*mark a visited cell */
	DATA(map_visit, pres_cell->row, pres_cell->col) = YES;
#if 0
	if (display)
	    draw_a_cell(pres_cell->row, pres_cell->col,
			(int)pres_cell->min_cost);
#endif

	cell_count++;
	if ((100 * cell_count / ncells) % 2 == 0 &&
	    (100 * (cell_count + (int)(0.009 * ncells)) / ncells) % 2 == 0) {
	    G_percent(cell_count, ncells, 2);
	}

	get_minHa(heap, pres_cell, heap_len);
	G_debug(2,
		"in while:     heap_len=%ld pres_cell->min_cost=%f time_lag=%d",
		heap_len, pres_cell->min_cost, time_lag);
    }				/*end 'while (heap_len-- >0)' */
    G_free(pres_cell);

    /*Assign min_cost values to un-reached area */
    for (row = 0; row < nrows; row++) {
	for (col = 0; col < ncols; col++) {
	    if (!DATA(map_visit, row, col)) {
		DATA(map_out, row, col) = (float)BARRIER;
		if (x_out)
		    DATA(map_x_out, row, col) = 0;
		if (y_out)
		    DATA(map_y_out, row, col) = 0;
	    }
	}
    }
    G_debug(2, "end spread");
}				/*end spread () */
 Real AnalyticCompoundOptionEngine::dPlus() const{
     Real forward = spot() * dividendDiscountDaughter() / riskFreeDiscountDaughter();
     Real sd=stdDeviationDaughter();
     return std::log(forward/strikeDaughter())/sd+0.5*sd;
 }
Пример #9
0
// [[Rcpp::export]]
Rcpp::List europeanOptionEngine(std::string type,
                                double underlying,
                                double strike,
                                double dividendYield,
                                double riskFreeRate,
                                double maturity,
                                double volatility,
                                Rcpp::Nullable<Rcpp::NumericVector> discreteDividends,
                                Rcpp::Nullable<Rcpp::NumericVector> discreteDividendsTimeUntil) {

#ifdef QL_HIGH_RESOLUTION_DATE    
    // in minutes
    boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); 
#else
    int length           = int(maturity*360 + 0.5); // FIXME: this could be better
#endif
    
    QuantLib::Option::Type optionType = getOptionType(type);
    QuantLib::Date today = QuantLib::Date::todaysDate();
    QuantLib::Settings::instance().evaluationDate() = today;

    // new framework as per QuantLib 0.3.5
    QuantLib::DayCounter dc = QuantLib::Actual360();
    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote( underlying ));
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote( volatility ));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote( dividendYield ));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote( riskFreeRate ));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);

    bool withDividends = discreteDividends.isNotNull() && discreteDividendsTimeUntil.isNotNull();
    
#ifdef QL_HIGH_RESOLUTION_DATE
    QuantLib::Date exDate(today.dateTime() + length);
#else 
    QuantLib::Date exDate = today + length;
#endif

    boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
    boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType, strike));
    
    if (withDividends) {
        Rcpp::NumericVector divvalues(discreteDividends), divtimes(discreteDividendsTimeUntil);
        int n = divvalues.size();
        std::vector<QuantLib::Date> discDivDates(n);
        std::vector<double> discDividends(n);
        for (int i = 0; i < n; i++) {
#ifdef QL_HIGH_RESOLUTION_DATE
            boost::posix_time::time_duration discreteDividendLength = boost::posix_time::minutes(boost::uint64_t(divtimes[i] * 360 * 24 * 60));
            discDivDates[i] = QuantLib::Date(today.dateTime() + discreteDividendLength);
#else
            discDivDates[i] = today + int(divtimes[i] * 360 + 0.5); 
#endif    
            discDividends[i] = divvalues[i];
        }
        
        boost::shared_ptr<QuantLib::BlackScholesMertonProcess> 
            stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                                 QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                                 QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                                 QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));
        
        boost::shared_ptr<QuantLib::PricingEngine> engine(new QuantLib::AnalyticDividendEuropeanEngine(stochProcess));
        
        QuantLib::DividendVanillaOption option(payoff, exercise, discDivDates, discDividends);
        option.setPricingEngine(engine);
        
        return Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                  Rcpp::Named("delta") = option.delta(),
                                  Rcpp::Named("gamma") = option.gamma(),
                                  Rcpp::Named("vega") = option.vega(),
                                  Rcpp::Named("theta") = option.theta(),
                                  Rcpp::Named("rho") = option.rho(),
                                  Rcpp::Named("divRho") = R_NaReal);
    }
    else {
        
        boost::shared_ptr<QuantLib::VanillaOption> option = makeOption(payoff, exercise, spot, qTS, rTS, volTS);
        
        return Rcpp::List::create(Rcpp::Named("value") = option->NPV(),
                                  Rcpp::Named("delta") = option->delta(),
                                  Rcpp::Named("gamma") = option->gamma(),
                                  Rcpp::Named("vega") = option->vega(),
                                  Rcpp::Named("theta") = option->theta(),
                                  Rcpp::Named("rho") = option->rho(),
                                  Rcpp::Named("divRho") = option->dividendRho());
    }
    
}
Пример #10
0
// [[Rcpp::export]]
Rcpp::List americanOptionEngine(std::string type,
                                double underlying,
                                double strike,
                                double dividendYield,
                                double riskFreeRate,
                                double maturity,
                                double volatility,
                                int timeSteps,
                                int gridPoints,
                                std::string engine,
                                Rcpp::Nullable<Rcpp::NumericVector> discreteDividends,
                                Rcpp::Nullable<Rcpp::NumericVector> discreteDividendsTimeUntil) {

#ifdef QL_HIGH_RESOLUTION_DATE    
    // in minutes
    boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); 
#else
    int length = int(maturity * 360 + 0.5); // FIXME: this could be better
    
#endif
    QuantLib::Option::Type optionType = getOptionType(type);

    // new framework as per QuantLib 0.3.5, updated for 0.3.7
    // updated again for 0.9.0, see eg test-suite/americanoption.cpp
    QuantLib::Date today = QuantLib::Date::todaysDate();
    QuantLib::Settings::instance().evaluationDate() = today;
    QuantLib::DayCounter dc = QuantLib::Actual360();
    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today,qRate,dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today,rRate,dc);
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
    
    bool withDividends = discreteDividends.isNotNull() && discreteDividendsTimeUntil.isNotNull();
    
#ifdef QL_HIGH_RESOLUTION_DATE
    QuantLib::Date exDate(today.dateTime() + length);
#else 
    QuantLib::Date exDate = today + length;
#endif

    boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType, strike));
    boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::AmericanExercise(today, exDate));

    boost::shared_ptr<QuantLib::BlackScholesMertonProcess> 
        stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));
    
    if (withDividends) {
        Rcpp::NumericVector divvalues(discreteDividends), divtimes(discreteDividendsTimeUntil);
        int n = divvalues.size();
        std::vector<QuantLib::Date> discDivDates(n);
        std::vector<double> discDividends(n);
        for (int i = 0; i < n; i++) {
#ifdef QL_HIGH_RESOLUTION_DATE
            boost::posix_time::time_duration discreteDividendLength = boost::posix_time::minutes(boost::uint64_t(divtimes[i] * 360 * 24 * 60));
            discDivDates[i] = QuantLib::Date(today.dateTime() + discreteDividendLength);
#else
            discDivDates[i] = today + int(divtimes[i] * 360 + 0.5); 
#endif    
            discDividends[i] = divvalues[i];
        }

        QuantLib::DividendVanillaOption option(payoff, exercise, discDivDates, discDividends);
        if (engine=="BaroneAdesiWhaley") { 
            Rcpp::warning("Discrete dividends, engine switched to CrankNicolson");
            engine = "CrankNicolson";
        }
       
        if (engine=="CrankNicolson") { // FDDividendAmericanEngine only works with CrankNicolson
            // suggestion by Bryan Lewis: use CrankNicolson for greeks
            boost::shared_ptr<QuantLib::PricingEngine> 
            fdcnengine(new QuantLib::FDDividendAmericanEngine<QuantLib::CrankNicolson>(stochProcess, timeSteps, gridPoints));
            option.setPricingEngine(fdcnengine);
            return Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                      Rcpp::Named("delta") = option.delta(),
                                      Rcpp::Named("gamma") = option.gamma(),
                                      Rcpp::Named("vega") = R_NaReal,
                                      Rcpp::Named("theta") = R_NaReal,
                                      Rcpp::Named("rho") = R_NaReal,
                                      Rcpp::Named("divRho") = R_NaReal);
        } else {
            throw std::range_error("Unknown engine " + engine);
        }
        
    } else {
        QuantLib::VanillaOption option(payoff, exercise);
        
        if (engine=="BaroneAdesiWhaley") {
            // new from 0.3.7 BaroneAdesiWhaley
            
            boost::shared_ptr<QuantLib::PricingEngine> engine(new QuantLib::BaroneAdesiWhaleyApproximationEngine(stochProcess));
            option.setPricingEngine(engine);
            return Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                      Rcpp::Named("delta") = R_NaReal,
                                      Rcpp::Named("gamma") = R_NaReal,
                                      Rcpp::Named("vega") = R_NaReal,
                                      Rcpp::Named("theta") = R_NaReal,
                                      Rcpp::Named("rho") = R_NaReal,
                                      Rcpp::Named("divRho") = R_NaReal);
        } else if (engine=="CrankNicolson") {
            // suggestion by Bryan Lewis: use CrankNicolson for greeks
            boost::shared_ptr<QuantLib::PricingEngine> 
            fdcnengine(new QuantLib::FDAmericanEngine<QuantLib::CrankNicolson>(stochProcess, timeSteps, gridPoints));
            option.setPricingEngine(fdcnengine);
            return Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                      Rcpp::Named("delta") = option.delta(),
                                      Rcpp::Named("gamma") = option.gamma(),
                                      Rcpp::Named("vega") = R_NaReal,
                                      Rcpp::Named("theta") = R_NaReal,
                                      Rcpp::Named("rho") = R_NaReal,
                                      Rcpp::Named("divRho") = R_NaReal);
        } else {
            throw std::range_error("Unknown engine " + engine);
        }
    }
    
    
}
Пример #11
0
// [[Rcpp::export]]
Rcpp::List binaryOptionEngine(std::string binType,
                              std::string type,
                              std::string excType,
                              double underlying,
                              double strike,
                              double dividendYield, 
                              double riskFreeRate,
                              double maturity,
                              double volatility,
                              double cashPayoff) {

#ifdef QL_HIGH_RESOLUTION_DATE    
    // in minutes
    boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); 
#else
    int length = int(maturity*360 + 0.5); // FIXME: this could be better, but same rounding in QL
#endif
    QuantLib::Option::Type optionType = getOptionType(type);

    // new QuantLib 0.3.5 framework: digitals, updated for 0.3.7
    // updated again for QuantLib 0.9.0, 
    // cf QuantLib-0.9.0/test-suite/digitaloption.cpp
    QuantLib::Date today = QuantLib::Date::todaysDate();
    QuantLib::Settings::instance().evaluationDate() = today;

    QuantLib::DayCounter dc = QuantLib::Actual360();
    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today,qRate,dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today,rRate,dc);
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);

    boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff;
    if (binType=="cash") {
        boost::shared_ptr<QuantLib::StrikedTypePayoff> con(new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff));
        payoff = con;
    } else if (binType=="asset") {
        boost::shared_ptr<QuantLib::StrikedTypePayoff> aon(new QuantLib::AssetOrNothingPayoff(optionType, strike));
        payoff = aon;
    } else if (binType=="gap") {
        boost::shared_ptr<QuantLib::StrikedTypePayoff> gap(new QuantLib::GapPayoff(optionType, strike, cashPayoff));
        payoff = gap;
    } else {
        throw std::range_error("Unknown binary option type " + binType);
    }

#ifdef QL_HIGH_RESOLUTION_DATE
    QuantLib::Date exDate(today.dateTime() + length);
#else
    QuantLib::Date exDate = today + length;
#endif    
    boost::shared_ptr<QuantLib::Exercise> exercise;
    if (excType=="american") {
        boost::shared_ptr<QuantLib::Exercise> amEx(new QuantLib::AmericanExercise(today, exDate));
        exercise = amEx;
    } else if (excType=="european") {
        boost::shared_ptr<QuantLib::Exercise> euEx(new QuantLib::EuropeanExercise(exDate));
        exercise = euEx;
    } else {
        throw std::range_error("Unknown binary exercise type " + excType);
    }

    boost::shared_ptr<QuantLib::BlackScholesMertonProcess> 
        stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));

    boost::shared_ptr<QuantLib::PricingEngine> engine;
    if (excType=="american") {
        boost::shared_ptr<QuantLib::PricingEngine> amEng(new QuantLib::AnalyticDigitalAmericanEngine(stochProcess));
        engine = amEng;
    } else if (excType=="european") {
        boost::shared_ptr<QuantLib::PricingEngine> euEng(new QuantLib::AnalyticEuropeanEngine(stochProcess));
        engine = euEng;
    } else {
        throw std::range_error("Unknown binary exercise type " + excType);
    }

    QuantLib::VanillaOption opt(payoff, exercise);
    opt.setPricingEngine(engine);

    Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = opt.NPV(),
                                       Rcpp::Named("delta") = opt.delta(),
                                       Rcpp::Named("gamma") = opt.gamma(),
                                       Rcpp::Named("vega") = (excType=="european") ? opt.vega() : R_NaN,
                                       Rcpp::Named("theta") = (excType=="european") ? opt.theta() : R_NaN,
                                       Rcpp::Named("rho") = (excType=="european") ? opt.rho() : R_NaN,
                                       Rcpp::Named("divRho") = (excType=="european") ? opt.dividendRho() : R_NaN);
    return rl;
}
Пример #12
0
// [[Rcpp::export]]
Rcpp::List barrierOptionEngine(std::string barrType,
                               std::string type,
                               double underlying,
                               double strike,
                               double dividendYield, 
                               double riskFreeRate,
                               double maturity,
                               double volatility,
                               double barrier, 
                               double rebate) {

#ifdef QL_HIGH_RESOLUTION_DATE    
    // in minutes
    boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); 
#else
    int length = int(maturity*360 + 0.5); // FIXME: this could be better
#endif
        
    QuantLib::Barrier::Type barrierType = QuantLib::Barrier::DownIn;
    if (barrType=="downin") {
        barrierType = QuantLib::Barrier::DownIn;
    } else if (barrType=="upin") {
        barrierType = QuantLib::Barrier::UpIn;
    } else if (barrType=="downout") {
        barrierType = QuantLib::Barrier::DownOut;
    } else if (barrType=="upout") {
        barrierType = QuantLib::Barrier::UpOut;
    } else {
        throw std::range_error("Unknown barrier type " + type);
    }

    QuantLib::Option::Type optionType = getOptionType(type);

    // new QuantLib 0.3.5 framework, updated for 0.3.7
    // updated again for QuantLib 0.9.0, 
    // cf QuantLib-0.9.0/test-suite/barrieroption.cpp
    QuantLib::Date today = QuantLib::Date::todaysDate();
    QuantLib::Settings::instance().evaluationDate() = today;
    QuantLib::DayCounter dc = QuantLib::Actual360();
    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today,rRate,dc);
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);

#ifdef QL_HIGH_RESOLUTION_DATE
    QuantLib::Date exDate(today.dateTime() + length);
#else
    QuantLib::Date exDate = today + length;
#endif    
    
    boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
        
    boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType, strike));
    
    boost::shared_ptr<QuantLib::BlackScholesMertonProcess> 
        stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));

    // Size timeSteps = 1;
    // bool antitheticVariate = false;
    // bool controlVariate = false;
    // Size requiredSamples = 10000;
    // double requiredTolerance = 0.02;
    // Size maxSamples = 1000000;
    // bool isBiased = false;

    boost::shared_ptr<QuantLib::PricingEngine> engine(new QuantLib::AnalyticBarrierEngine(stochProcess));

    // need to explicitly reference BarrierOption from QuantLib here
    QuantLib::BarrierOption barrierOption(barrierType,
                                          barrier,
                                          rebate,
                                          payoff,
                                          exercise);
    barrierOption.setPricingEngine(engine);

    Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = barrierOption.NPV(),
                                       Rcpp::Named("delta") = R_NaReal,
                                       Rcpp::Named("gamma") = R_NaReal,
                                       Rcpp::Named("vega") = R_NaReal,
                                       Rcpp::Named("theta") = R_NaReal,
                                       Rcpp::Named("rho") = R_NaReal,
                                       Rcpp::Named("divRho") = R_NaReal);
    return rl;
}
Пример #13
0
double Stock::price() const{
    return spot();
}