Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Функции для упрощения работы пользователя с программой

Читайте также:
  1. Defining functions Определение функции
  2. I. Методические рекомендации по выполнению самостоятельной работы студентов.
  3. I. Общая характеристика работы
  4. I. ОБЩАЯ ХАРАКТЕРИСТИКА РАБОТЫ
  5. II. Задания для самостоятельной работы
  6. II. Задания для самостоятельной работы.
  7. II. Задания для самостоятельной работы.

Предусмотрено наличие всплывающих подсказок при наведении указателя на какой-либо компонент или пункт меню, помогающих пользователю ориентироваться в приложении.

Есть статусная панель, в которой тоже отображаются подсказки пользователю.

На панели инструментов расположены основные кнопки для быстроты доступа к нужным функциям.

Предусмотрена проверка на корректный ввод и отображение сообщений с описанием возникшей ошибки. Например,

Прочитав сообщение, нужно нажать «OK» и исправить указанную ошибку.

Для проверки работоспособности программы служат файлы: example1.tpr, example2d.tpr, example10.tpr, example11.tpr.

Также рассмотрен пример портфеля инвестиций из ценных бумаг реальных компаний, основные показатели которых были оценены экспертами. Эти показатели приведены в таблицах 2 и 3.

Таблица 2. Доходность и риск

 

Таблица 3. Матрица коэффициентов корреляции

Данные этого примера сохранены в файле equity.tpr.

 

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, ExtCtrls, Menus, TeeProcs, TeEngine, Chart, Spin,

Grids, ComCtrls, ToolWin, Series, Math, ImgList, AppEvnts;

type

TForm_Risk_or_Profit = class(TForm)

ToolBar1: TToolBar;

StatusBar1: TStatusBar;

SG_Input_date: TStringGrid;

SG_Correlation: TStringGrid;

SE_Input_count: TSpinEdit;

Chart1: TChart;

MainMenu1: TMainMenu;

NFile: TMenuItem;

NOpen: TMenuItem;

N4: TMenuItem;

NExit: TMenuItem;

NOperations: TMenuItem;

NReadyPortfolio: TMenuItem;

NHelp: TMenuItem;

NAbout: TMenuItem;

NSave: TMenuItem;

LCount: TLabel;

LTable: TLabel;

LCorrelation: TLabel;

BCalculation: TButton;

RG_Risk_or_Profit: TRadioGroup;

LRG: TLabel;

E_Risk_or_Profit: TEdit;

BClear: TButton;

LResult: TLabel;

SG_Result: TStringGrid;

Series1: TLineSeries;

Series2: TLineSeries;

BDrawGraph: TButton;

OpenDialog1: TOpenDialog;

SaveDialog1: TSaveDialog;

EditResult: TEdit;

LComment: TLabel;

ToolButtonOpen: TToolButton;

ToolButtonSave: TToolButton;

ToolButton3: TToolButton;

ToolButtonReadyPortfolio: TToolButton;

ToolButton5: TToolButton;

ToolButtonAbout: TToolButton;

ToolButton7: TToolButton;

ToolButtonExit: TToolButton;

ApplicationEvents1: TApplicationEvents;

ImageList1: TImageList;

procedure NReadyPortfolioClick(Sender: TObject);

procedure NExitClick(Sender: TObject);

procedure FormCreate(Sender: TObject);

procedure SG_Input_dateKeyPress(Sender: TObject; var Key: Char);

procedure SG_CorrelationKeyPress(Sender: TObject; var Key: Char);

procedure E_Risk_or_ProfitKeyPress(Sender: TObject; var Key: Char);

procedure SE_Input_countChange(Sender: TObject);

procedure BClearClick(Sender: TObject);

procedure BCalculationClick(Sender: TObject);

procedure Graph;

function Get_Date:boolean;

procedure BDrawGraphClick(Sender: TObject);

procedure SG_CorrelationSelectCell(Sender: TObject; ACol,

ARow: Integer; var CanSelect: Boolean);

procedure SG_CorrelationMouseUp(Sender: TObject; Button: TMouseButton;

Shift: TShiftState; X, Y: Integer);

procedure SG_CorrelationExit(Sender: TObject);

procedure NOpenClick(Sender: TObject);

procedure NSaveClick(Sender: TObject);

procedure NAboutClick(Sender: TObject);

procedure ApplicationEvents1Hint(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

type myarray=array [1..100] of real;

myarr=array [1..100,1..100] of real;

var

Form_Risk_or_Profit: TForm_Risk_or_Profit;

SEValue:integer;

M,BE,BM,deviation_of_stocks:myarray;

B,E,B1,E1:myarr;

mp,ebe,mbm,ebm,x,mbe:real;

mPr,risk:real;

number_of_stocks,SelectedRow,SelectedCol:integer;

implementation

uses Unit2, UAboutMe;

{$R *.dfm}

procedure TForm_Risk_or_Profit.NReadyPortfolioClick(Sender: TObject);

var i,j:integer;

begin

Form_Risk_or_Profit.Visible:=False;

Form_for_ready_portfolio.SE_Input_count.Value:=SEValue;

Form_for_ready_portfolio.Show;

for i:=1 to SEValue do

begin

Form_for_ready_portfolio.SG_Input_date.Cells[i,2]:=SG_Input_date.Cells[i,1];

Form_for_ready_portfolio.SG_Input_date.Cells[i,3]:=SG_Input_date.Cells[i,2];

for j:=1 to SEValue do

begin

Form_for_ready_portfolio.SG_Correlation.Cells[i,j]:=SG_Correlation.Cells[i,j];

end;

end;

end;

procedure TForm_Risk_or_Profit.NExitClick(Sender: TObject);

begin

Close;

end;

procedure TForm_Risk_or_Profit.FormCreate(Sender: TObject);

begin

SG_Input_date.Cells[0,0]:='Показатель | Номер бумаги';

SG_Input_date.Cells[0,1]:='Доходность';

SG_Input_date.Cells[0,2]:='Риск';

SG_Result.Cells[0,0]:='Номер бумаги';

SG_Result.Cells[0,1]:='Доля';

SelectedRow:=1;

SelectedCol:=1;

end;

procedure TForm_Risk_or_Profit.SG_Input_dateKeyPress(Sender: TObject;

var Key: Char);

begin

case key of

'0'..'9',#8,',':;

else key:=#0;

end;

end;

procedure TForm_Risk_or_Profit.SG_CorrelationKeyPress(Sender: TObject;

var Key: Char);

begin

case key of

'0'..'9',#8,',','-':;

else key:=#0;

end;

end;

procedure TForm_Risk_or_Profit.E_Risk_or_ProfitKeyPress(Sender: TObject;

var Key: Char);

begin

case key of

'0'..'9',#8,',':;

else key:=#0;

end;

end;

procedure TForm_Risk_or_Profit.SE_Input_countChange(Sender: TObject);

var i:integer;

begin

SEValue:=SE_Input_count.Value;

for i:=1 to SEValue do

begin

SG_Input_date.Cells[i,0]:=inttostr(i);

SG_Result.Cells[i,0]:=inttostr(i);

SG_Correlation.Cells[0,i]:=inttostr(i);

SG_Correlation.Cells[i,0]:=inttostr(i);

SG_Correlation.Cells[i,i]:='1';

end;

SG_Input_date.ColCount:=SEValue+1;

SG_Correlation.ColCount:=SEValue+1;

SG_Correlation.RowCount:=SEValue+1;

SG_Result.ColCount:=SEValue+1;

end;

procedure TForm_Risk_or_Profit.BClearClick(Sender: TObject);

var i,j:integer;

begin

for i:=1 to SEValue do

for j:=1 to SEValue do

begin

SG_Input_date.Cells[i,j]:='';

SG_Correlation.Cells[i,j]:='';

SG_Result.Cells[i,j];

end;

Series1.Clear;

E_Risk_or_Profit.Clear; SE_Input_count.Value:=2;

end;

function minRisk(mp:real):real;

begin

minRisk:=sqrt((mp*mp*ebe-2*mp*mbe+mbm)/(ebe*mbm-mbe*mbe));

end;

Function bisection(a,b,risk:real):real;

var y1,y2,c:real;

begin

y1:=MinRisk(a)-risk;

y2:=MinRisk(b)-risk;

while abs(y2)>0.000001 do

begin

c:=(a+b)/2;

y2:=MinRisk(c)-risk;

if y1*y2<0

then b:=c

else begin a:=c; y1:=y2; end;

end;

bisection:=c;

end;

function TForm_Risk_or_Profit.Get_Date:boolean;

var i,j:integer;

begin

result:=True;

number_of_stocks:=SE_Input_count.Value;

for i:=1 to number_of_stocks do

begin

E[i,i]:=1;

try

M[i]:=strtofloat(SG_Input_date.Cells[i,1]);

except

showmessage('Извините, Вы не ввели доходность '+intToStr(i)+'-й бумаги!');

result:=False;

exit;

end;

try

deviation_of_stocks[i]:=strtofloat(SG_Input_date.Cells[i,2]);

except

showmessage('Извините, Вы не ввели риск '+intToStr(i)+'-й бумаги!');

result:=False;

exit;

end;

B[i,i]:=sqr(deviation_of_stocks[i]);

end;

for i:=1 to number_of_stocks do

begin

for j:=i+1 to number_of_stocks do

begin

try B[i,j]:=strtofloat(SG_Correlation.Cells[j,i])*deviation_of_stocks[i]*deviation_of_stocks[j];

except

showmessage('Извините, Вы не ввели корреляцию '+intToStr(i)+'-ой и '+intToStr(j)+'-ой бумаг!');

result:=False;

exit;

end;

B[j,i]:=B[i,j];

E[i,j]:=0;

E[j,i]:=0;

end;

end;

end;

procedure base;

var i,j,k,l,a:integer;

begin

for i:=1 to number_of_stocks do

begin

for j:=1 to number_of_stocks do

begin

for k:=1 to number_of_stocks do

begin

B1[j,k]:=B[j,k];

E1[j,k]:=E[j,k];

end;

end;

for l:=1 to number_of_stocks do

begin

B[i,l]:=B1[i,l]/B1[i,i];

E[i,l]:=E1[i,l]/B1[i,i];

for a:=1 to number_of_stocks do

begin

if a<>i then

begin

B[a,l]:=(B1[a,l]-(B1[a,i]*B1[i,l]/B1[i,i]));

E[a,l]:=(E1[a,l]-(B1[a,i]*E1[i,l]/B1[i,i]));

end;

end;

end;

end;

for i:=1 to number_of_stocks do

begin

BE[i]:=0;

for j:=1 to number_of_stocks do

begin

BE[i]:=BE[i]+E[i,j];

end;

end;

for i:=1 to number_of_stocks do

begin

BM[i]:=0;

for j:=1 to number_of_stocks do

begin

BM[i]:=BM[i]+M[j]*E[i,j];

end;

end;

ebe:=0;

ebm:=0;

mbm:=0;

mbe:=0;

for i:=1 to number_of_stocks do

begin

ebe:=ebe+BE[i];

ebm:=ebm+BM[i];

mbm:=mbm+M[i]*BM[i];

mbe:=mbe+M[i]*BE[i];

end;

end;

procedure TForm_Risk_or_Profit.Graph;

var i:integer;

min,max,profit:real;

begin

max:=m[1];

for i:=2 to number_of_stocks do

begin

if m[i]>max then max:=m[i];

end;

min:=m[1];

for i:=2 to number_of_stocks do

begin

if m[i]<min then min:=m[i];

end;

profit:=mbe/ebe;

repeat

Series1.AddXY(minRisk(profit),profit);

profit:=profit+(max-min)/100;

until profit>=max;

profit:=min;

repeat

Series2.AddXY(minRisk(profit),profit);

profit:=profit+(max-min)/100;

until profit>=mbe/ebe;

end;

function Max_Profit(risk:real):real;

var i:integer;

max:real;

begin

max:=m[1];

for i:=2 to number_of_stocks do

begin

if m[i]>max then

max:=m[i];

end;

mPr:=bisection(mbe/ebe,max,risk);

result:=mPr;

end;

procedure TForm_Risk_or_Profit.BCalculationClick(Sender: TObject);

var i:integer;

max,min:real;

a:boolean;

begin

if Get_Date then

begin

base;

LComment.Caption:='';

case RG_Risk_or_Profit.ItemIndex of

0:begin

try

mp:=strtofloat(E_Risk_or_Profit.Text);

except

Application.MessageBox('Извините, Вы не ввели желаемую доходность!','Ошибка!');

exit;

end;

//проверка, лежит ли введенная доходность между минимальной и максимальной

max:=m[1];

for i:=2 to number_of_stocks do

begin

if m[i]>max then max:=m[i];

end;

min:=m[1];

for i:=2 to number_of_stocks do

begin

if m[i]<min then min:=m[i];

end;

if (mp<min)or(mp>max) then

begin

Application.MessageBox('Извините, желаемая доходность должна быть в пределах эффективностей ценных бумаг!','Ошибка!');

exit;

end;

if mp<mbe/ebe then

LComment.Caption:='Внимание! Указанная доходность НЕ лежит на эффективной границе!'+#9#13

+'Полученному уровню риска соответствует бОльшая доходность, равная '+floattostr(roundto(max_Profit(minrisk(mp)),-4))+#9#13#9#13;

EditResult.Text:=' Минимальный риск портфеля: '+floattostr(roundto(minrisk(mp),-4));

end;

1:begin

try

risk:=strtofloat(E_Risk_or_Profit.Text);

except

Application.MessageBox('Извините, Вы не ввели допустимый уровень риска','Ошибка!');

exit;

end;

mp:=Max_Profit(risk);

EditResult.Text:=' Максимальная доходность портфеля: '+floattostr(roundto(mp,-4));

end;

end;

a:=false;

for i:=1 to number_of_stocks do

begin

x:=((mbm-mp*ebm)*BE[i]+(mp*ebe-mbe)*BM[i])/(ebe*mbm-mbe*mbe);

if x<0 then a:=true;

 

SG_Result.Cells[i,1]:=floattostr(roundto(x,-4));

end;

if a then

LComment.Caption:=LComment.Caption+' Так как доля бумаг отрицательна, то необходимо провести сделку "short sale",'+#9#13

+' исключить бумаги этого вида из портфеля и решить задачу заново.';

end;

end;

procedure TForm_Risk_or_Profit.BDrawGraphClick(Sender: TObject);

begin

if Get_Date then

begin

Series1.Clear;

Series2.Clear;

base;

graph;

end;

end;

procedure TForm_Risk_or_Profit.SG_CorrelationSelectCell(Sender: TObject;

ACol, ARow: Integer; var CanSelect: Boolean);

begin

if ACol=ARow

then begin CanSelect:=False; exit; end;

SG_CorrelationExit(Sender);

SelectedRow:=ARow;

SelectedCol:=ACol;

end;

procedure TForm_Risk_or_Profit.SG_CorrelationMouseUp(Sender: TObject;

Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

begin

SG_CorrelationExit(Sender);

end;

procedure TForm_Risk_or_Profit.SG_CorrelationExit(Sender: TObject);

begin

try

if abs(StrToFloat(SG_Correlation.Cells[SelectedCol,SelectedRow]))<=1 then SG_Correlation.Cells[SelectedRow,SelectedCol]:=SG_Correlation.Cells[SelectedCol,SelectedRow]

else

begin

ShowMessage('Извините, корреляция не может быть больше 1!');

SG_Correlation.Cells[SelectedCol,SelectedRow]:='0';

SG_Correlation.Cells[SelectedRow,SelectedCol]:='0';

end;

except

SG_Correlation.Cells[SelectedCol,SelectedRow]:='0';

SG_Correlation.Cells[SelectedRow,SelectedCol]:='0';

end;

end;

procedure TForm_Risk_or_Profit.NOpenClick(Sender: TObject);

var f:file of real;

i,j:integer;

a:real;

begin

if OpenDialog1.Execute

then

begin

BClearClick(Sender);

AssignFile(f,OpenDialog1.FileName);

try

reset(f);

except

Application.MessageBox('Извините, невозможно открыть файл!','Ошибка!');

end;

read(f,a);

SEValue:=round(a);

SE_Input_count.Value:=SEValue;

//считываем из файла доходности

for i:=1 to SEValue do

begin

read(f,a);

SG_Input_date.Cells[i,1]:=FloatToStr(a);

end;

//считываем из файла риски

for i:=1 to SEValue do

begin

read(f,a);

SG_Input_date.Cells[i,2]:=FloatToStr(a);

end;

//считываем из файла корреляцию

for i:=1 to SEValue do

for j:=1 to SEValue do

begin

read(f,a);

SG_Correlation.Cells[i,j]:=FloatToStr(a);

end;

closefile(f);

end;

end;

procedure TForm_Risk_or_Profit.NSaveClick(Sender: TObject);

var f:file of real;

i,j:integer;

a:real;

begin

if SaveDialog1.Execute

then

begin

if ExtractFileExt(SaveDialog1.FileName)=''

then SaveDialog1.FileName:=SaveDialog1.FileName+'.tpr';

AssignFile(f,SaveDialog1.FileName);

rewrite(f);

a:=SEValue;

write(f,a);

//записываем в файл доходности

for i:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Input_date.Cells[i,1]);

except

a:=0;

end;

write(f,a);

end;

//записываем в файл риски

for i:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Input_date.Cells[i,2]);

except

a:=0;

end;

write(f,a);

end;

//записываем в файл корреляцию

for i:=1 to SEValue do

for j:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Correlation.Cells[i,j]);

except

a:=0;

end;

write(f,a);

end;

//записываем в файл доли

for i:=1 to SEValue do

begin

a:=0;

write(f,a);

end;

closefile(f);

end;

end;

procedure TForm_Risk_or_Profit.NAboutClick(Sender: TObject);

begin

AboutProgram.ShowModal;

end;

procedure TForm_Risk_or_Profit.ApplicationEvents1Hint(Sender: TObject);

begin

StatusBar1.SimpleText:=Application.Hint;

end;

end.

unit Unit2;

interface

 

uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, ComCtrls, StdCtrls, Menus, ToolWin, Spin, Grids, Math, AppEvnts,

ImgList;

type

TForm_for_ready_portfolio = class(TForm)

ToolBar1: TToolBar;

MainMenu1: TMainMenu;

NFile: TMenuItem;

NOpen: TMenuItem;

NSave: TMenuItem;

N4: TMenuItem;

NExit: TMenuItem;

NOperations: TMenuItem;

NMinRisk: TMenuItem;

NHelp: TMenuItem;

NAbout: TMenuItem;

StatusBar1: TStatusBar;

NMaxProfit: TMenuItem;

LCount: TLabel;

SE_Input_count: TSpinEdit;

BClear: TButton;

LTable: TLabel;

SG_Input_date: TStringGrid;

LCorrelation: TLabel;

SG_Correlation: TStringGrid;

BCalculation: TButton;

Label1: TLabel;

MemoResult: TMemo;

OpenDialog1: TOpenDialog;

SaveDialog1: TSaveDialog;

ToolButtonOpen: TToolButton;

ToolButtonSave: TToolButton;

ToolButton3: TToolButton;

ToolButtonMinRisk: TToolButton;

ToolButtonMaxProfit: TToolButton;

ToolButton6: TToolButton;

ToolButtonAbout: TToolButton;

ToolButton8: TToolButton;

ToolButtonExit: TToolButton;

ImageList1: TImageList;

ApplicationEvents1: TApplicationEvents;

procedure NMinRiskClick(Sender: TObject);

procedure NExitClick(Sender: TObject);

procedure NMaxProfitClick(Sender: TObject);

procedure BCalculationClick(Sender: TObject);

procedure FormCreate(Sender: TObject);

procedure FormClose(Sender: TObject; var Action: TCloseAction);

procedure SG_Input_dateKeyPress(Sender: TObject; var Key: Char);

//procedure FormShow(Sender: TObject);

procedure SG_CorrelationKeyPress(Sender: TObject; var Key: Char);

procedure SE_Input_countChange(Sender: TObject);

procedure BClearClick(Sender: TObject);

procedure SG_CorrelationSelectCell(Sender: TObject; ACol,

ARow: Integer; var CanSelect: Boolean);

procedure SG_CorrelationExit(Sender: TObject);

procedure SG_CorrelationMouseUp(Sender: TObject; Button: TMouseButton;

Shift: TShiftState; X, Y: Integer);

procedure NOpenClick(Sender: TObject);

procedure NSaveClick(Sender: TObject);

procedure NAboutClick(Sender: TObject);

procedure ApplicationEvents1Hint(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

type myarray=array [1..100] of real;

myarr=array [1..100,1..100] of real;

var Form_for_ready_portfolio: TForm_for_ready_portfolio;

SEValue,SelectedRow,SelectedCol:integer;

implementation

uses Unit1, UAboutMe;

{$R *.dfm}

procedure TForm_for_ready_portfolio.NMinRiskClick(Sender: TObject);

begin

Form_for_ready_portfolio.Visible:=False;

Form_Risk_or_Profit.RG_Risk_or_Profit.ItemIndex:=0;

Form_Risk_or_Profit.Show;

end;

procedure TForm_for_ready_portfolio.NExitClick(Sender: TObject);

begin

Close;

end;

procedure TForm_for_ready_portfolio.NMaxProfitClick(Sender: TObject);

begin

Form_for_ready_portfolio.Visible:=False;

Form_Risk_or_Profit.RG_Risk_or_Profit.ItemIndex:=1;

Form_Risk_or_Profit.Show;

end;

procedure TForm_for_ready_portfolio.BCalculationClick(Sender: TObject);

var profitability_of_portfolio,deviation_of_portfolio:real;

number_of_stocks,i,j:integer;

dispersion,sum:real;

profitabilities_of_stocks,deviation_of_stocks,equity_share:myarray;

begin

number_of_stocks:=SE_Input_count.Value;

sum:=0;

for i:=1 to number_of_stocks do

begin

try

equity_share[i]:=strtofloat(SG_Input_date.Cells[i,1]);

except

showmessage('Извините, Вы не ввели долю '+intToStr(i)+'-ой бумаги!');

exit;

end;

sum:=sum+equity_share[i];

try

profitabilities_of_stocks[i]:=strtofloat(SG_Input_date.Cells[i,2]);

except

showmessage('Извините, Вы не ввели доходность '+intToStr(i)+'-ой бумаги!');

exit;

end;

try

deviation_of_stocks[i]:=strtofloat(SG_Input_date.Cells[i,3]);

except

showmessage('Извините, Вы не ввели риск '+intToStr(i)+'-ой бумаги!');

exit;

end;

end;

if sum<>1 then

begin

Application.MessageBox('Извините, сумма долей бумаг должна быть равна 1','Ошибка!');

exit;

end;

profitability_of_portfolio:=0;

dispersion:=0;

for i:=1 to number_of_stocks do

begin profitability_of_portfolio:=profitability_of_portfolio+equity_share[i]*profitabilities_of_stocks[i];

for j:=1 to number_of_stocks do

try dispersion:=dispersion+equity_share[i]*equity_share[j]*strtofloat(SG_Correlation.Cells[i,j])*deviation_of_stocks[i]*deviation_of_stocks[j];

except

showmessage('Извините, Вы не ввели корреляцию '+intToStr(i)+'-ой и '+intToStr(j)+'-ой бумаг!');

exit;

end;

end;

deviation_of_portfolio:=sqrt(dispersion);

MemoResult.Lines.Add('Ожидаемая доходность портфеля: '+floattostr(roundto(profitability_of_portfolio,-4))+'%');

MemoResult.Lines.Add('Стандартное отклонение доходности: '+floattostr(roundto(deviation_of_portfolio,-4))+'%');

end;

procedure TForm_for_ready_portfolio.FormCreate(Sender: TObject);

begin

SG_Input_date.Cells[0,0]:='Показатель | Номер бумаги';

SG_Input_date.Cells[0,1]:='Доля';

SG_Input_date.Cells[0,2]:='Доходность';

SG_Input_date.Cells[0,3]:='Стандартное отклонение';

SelectedRow:=1;

SelectedCol:=1;

end;

procedure TForm_for_ready_portfolio.FormClose(Sender: TObject;

var Action: TCloseAction);

begin

Form_Risk_or_Profit.Close;

end;

procedure TForm_for_ready_portfolio.SG_Input_dateKeyPress(Sender: TObject;

var Key: Char);

begin

case key of

'0'..'9',#8,',':;

else key:=#0;

end;

end;

procedure TForm_for_ready_portfolio.SG_CorrelationKeyPress(Sender: TObject;

var Key: Char);

begin

case key of

'0'..'9',#8,',','-':;

else key:=#0;

end;

end;

procedure TForm_for_ready_portfolio.SE_Input_countChange(Sender: TObject);

var i:integer;

begin

SEValue:=SE_Input_count.Value;

for i:=1 to SEValue do

begin

SG_Input_date.Cells[i,0]:=inttostr(i);

SG_Correlation.Cells[0,i]:=inttostr(i);

SG_Correlation.Cells[i,0]:=inttostr(i);

SG_Correlation.Cells[i,i]:='1';

end;

SG_Input_date.ColCount:=SEValue+1;

SG_Correlation.ColCount:=SEValue+1;

SG_Correlation.RowCount:=SEValue+1;

end;

procedure TForm_for_ready_portfolio.BClearClick(Sender: TObject);

var i,j:integer;

begin

for i:=1 to SEValue do

for j:=1 to SEValue do

begin

SG_Input_date.Cells[i,j]:='';

SG_Correlation.Cells[i,j]:='';

end;

MemoResult.Lines.Clear;

SE_Input_count.Value:=2;

end;

procedure TForm_for_ready_portfolio.SG_CorrelationSelectCell(

Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);

begin

if ACol=ARow

then begin CanSelect:=False; exit; end;

SG_CorrelationExit(Sender);

SelectedRow:=ARow;

SelectedCol:=ACol;

end;

procedure TForm_for_ready_portfolio.SG_CorrelationExit(Sender: TObject);

begin

try

if abs(StrToFloat(SG_Correlation.Cells[SelectedCol,SelectedRow]))<=1 then SG_Correlation.Cells[SelectedRow,SelectedCol]:=SG_Correlation.Cells[SelectedCol,SelectedRow]

else

begin

ShowMessage('Извините, корреляция не может быть больше 1!');

SG_Correlation.Cells[SelectedCol,SelectedRow]:='0';

end;

except

SG_Correlation.Cells[SelectedCol,SelectedRow]:='0';

SG_Correlation.Cells[SelectedRow,SelectedCol]:='0';

end;

end;

procedure TForm_for_ready_portfolio.SG_CorrelationMouseUp(Sender: TObject;

Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

begin

SG_CorrelationExit(Sender);

end;

procedure TForm_for_ready_portfolio.NOpenClick(Sender: TObject);

var f:file of real;

i,j:integer;

a:real;

begin

if OpenDialog1.Execute then

begin

BClearClick(Sender);

AssignFile(f,OpenDialog1.FileName);

try

reset(f);

except

Application.MessageBox('Извините, невозможно открыть файл!','Ошибка!');

end;

read(f,a);

SEValue:=round(a);

SE_Input_count.Value:=SEValue;

//считываем из файла доходности

for i:=1 to SEValue do

begin

read(f,a);

SG_Input_date.Cells[i,2]:=FloatToStr(a);

end;

//считываем из файла риски

for i:=1 to SEValue do

begin

read(f,a);

SG_Input_date.Cells[i,3]:=FloatToStr(a);

end;

//считываем из файла корреляцию

for i:=1 to SEValue do

for j:=1 to SEValue do

begin

read(f,a);

SG_Correlation.Cells[i,j]:=FloatToStr(a);

end;

//считываем из файла доли

for i:=1 to SEValue do

begin

read(f,a);

SG_Input_date.Cells[i,1]:=FloatToStr(a);

end;

closefile(f);

end;

end;

procedure TForm_for_ready_portfolio.NSaveClick(Sender: TObject);

var f:file of real;

i,j:integer;

a:real;

begin

if SaveDialog1.Execute then

begin

if ExtractFileExt(SaveDialog1.FileName)=''

then SaveDialog1.FileName:=SaveDialog1.FileName+'.tpr';

AssignFile(f,SaveDialog1.FileName);

rewrite(f);

a:=SEValue;

write(f,a);

//записываем в файл доходности

for i:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Input_date.Cells[i,2]);

except

a:=0;

end;

write(f,a);

end;

//записываем в файл риски

for i:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Input_date.Cells[i,3]);

except

a:=0;

end;

write(f,a);

end;

//записываем в файл корреляцию

for i:=1 to SEValue do

for j:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Correlation.Cells[i,j]);

except

a:=0;

end;

write(f,a);

end;

//записываем в файл доли

for i:=1 to SEValue do

begin

try

a:=StrToFloat(SG_Input_date.Cells[i,1]);

except

a:=0;

end;

write(f,a);

end;

closefile(f);

end;

end;

procedure TForm_for_ready_portfolio.NAboutClick(Sender: TObject);

begin

AboutProgram.ShowModal

end;

procedure TForm_for_ready_portfolio.ApplicationEvents1Hint(

Sender: TObject);

begin

StatusBar1.SimpleText:=Application.Hint;

end;

end.

 

 


Дата добавления: 2015-08-18; просмотров: 57 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Завершение работы| Подготовка прибора к испытанию

mybiblioteka.su - 2015-2024 год. (0.139 сек.)