⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 agent.java

📁 在这个电脑中的虚拟市场中
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
package asm;import java.util.Vector;/** * Title:        Artificial Stock Market * Description:  人工模拟股市(来源:SFI的Swarm版本)的Java版本 * Copyright:    Copyright (c) 2003 * Company:      http://agents.yeah.net * @author jake * @version 1.0 */public class Agent {  static double minstrength;//最小的规则适应度  public double demand;	/*对股票的需求量" bid or -offer"*/  public double profit;	/*当期赢得的利润" exp-weighted moving average "*/  public double wealth;	/*总财富" total agent wealth "*/  public double position;/*股票的持有量" total shares of stock "*/  public double cash;/*当期的现金量" total agent cash position "*/  public double initialcash;//初始时刻的现金  public double minholding;//最小的持股量  public double mincash;//最小现金量  public double intrate;//利率  public double intratep1;//利率+1  public double price;//当前的股票价格 price is maintained by World  public double dividend;//当前的股息 dividend is maintained by World  public int myID;  int currentTime; /*当前时间"The agent regularly checks with Swarm to see what time it is"*/  int lastgatime;	/*上一次运行遗传算法的时间" last time period when the GeneticAlgorithm was run"*/  double avspecificity; /*平均特异性'average specificity of active forecasts"*/  double forecast;       /*对price+dividend的预测值"prediction of stock price: (trialprice+dividend)*pdcoeff + offset."*/  double lforecast; /*上一次的预测值"lagged forecast: forecast value from previous period"*/  double global_mean; /*"price+dividend"*/  double realDeviation;  /*预测与现实的差" ftarget-lforecast: how far off was the agent's forecast?"*/  double variance;   /*一个加权平均数公式:bv*variance + av*deviation*deviation"an Exp.Weighted MA of the agent's historical variance: Combine the old variance with deviation^squared, as in:  bv*variance + av*deviation*deviation"*/  double pdcoeff;   /*预测系数" coefficient used in predicting stock price, recalculated each period in prepareForTrading"*/  double offset;    /*预测系数" coefficient used in predicting stock price, recalculated each period in prepareForTrading"*/  double divisor;   /*计算股票需求量的一个系数" a coefficient used to calculate demand for stock. It is a proportion (lambda) of forecastvar (basically, accuracy of forecasts)"*/  int gacount;     /*运行过遗传算法的次数" how many times has the Genetic Algorithm been used?"*/  AgentParam privateParams;     /*关于agent参数的一个集合"BFParams object holds parameters of this object"*/  Vector fcastList;        /*预测规则的列表"A Swarm Array, holding the forecasts that the agent might use"*/  Vector activeList;       /*激活的预测规则列表"A Swarm list containing a subset of all forecasts"*/  Vector oldActiveList;    /*激活的预测规则列表的拷贝"A copy of the activeList from the previous time step"*/  Vector History;         //关于agent的历史纪录  World  worldForAgent;   //当前的世界状态和编码  AsmModel local;         //对于AsmModel的一个拷贝/*"This tells BFagents where they should look to get the default  parameters. it should give the agent an object from the BFParams  class."*/void setBFParameterObject(AgentParam x){    privateParams=x;}/*" Sets a world for an agent.  It is a class method as it is used inboth class and instance methods in BFagent."*/void setWorld(World aWorld){  worldForAgent = aWorld;}/*"  Sets the IVAR intrate and uses that to calculate intratep1 (intrate + 1)."*/void setintrate(double rate){  //设定利率  intrate = rate;  intratep1 = intrate + 1.0;}/*" Sets the borrowing and short selling constraints, i.e., the  //      values can be negative. It sets values of the IVARS minholding and mincash"*/void setminHolding(double holding,double minimumcash){  minholding = holding;  mincash = minimumcash;}/*" Sets the initial stock holdings of each agent. It is the * designated initializer.  Most agent classes will have additional * initialization, but should do [super setInitialHoldings] to run * this first. It will initialize instance variables common to all * agents, setting profit,wealth, and position equal to 0, and it sets * the variable cash equal to initialcash "*/void setInitialHoldings(){  //几个参数的初始化  profit = 0.0;  wealth = 0.0;  cash = initialcash;  position = 0.0;}/*" Sets an instance variable of agent, price, to the current price  which is controlled by the object known as "world". Please note this  assumes world is already set. "*/void getPriceFromWorld(){  price = worldForAgent.getPrice();}/*"Sets an instance variable of agent, dividend, to the current dividend. That information is retrieved from the object known as "world"."*/void getDividendFromWorld(){  dividend = worldForAgent.getDividend();}void creditEarningsAndPayTaxes()/*"Sent to each agent after a dividend is declared.  The agents * receive the dividend for each unit of stock they hold.  Their cash" * in the fixed asset account also receives its interest.  Then taxes * are charged on the previous total wealth, at a rate that balances * the interest on cash -- so if the agent had everything in cash it * would end up at the same place. * This is done in each period after the new dividend is declared.  It is * not normally overridden by subclases.  The taxes are assessed on the * previous wealth at a rate so that there's no net effect on an agent * with position = 0. * * In principle we do: *	wealth = cash + price*position;			// previous wealth *	cash += intrate * cash + position*dividend;	// earnings *	cash -= wealth*intrate;				// taxes * but we cut directly to the cash: *	cash -= (price*intrate - dividend)*position" */{//对每个agent进行征税和分红  getPriceFromWorld();  getDividendFromWorld();// Update cash  cash -= (price*intrate - dividend)*position;  if (cash < mincash)cash = mincash;// Update wealth  wealth = cash + price*position;}double constrainDemand(double slope[],double trialprice)/*" Method used by agents to constrain their demand according to the * mincash and minholding constraints. * It checks "demand" against the * mincash and minholding constraints and clips it if necessary, then * also setting *slope.  For use within subclass implementations of * getDemandAndSlope: forPrice:.  Used only by agents that work with * the Slope Specialist."*/{//检查交宜人的需求量是否过量。如果是买入,则察看他的现金是否还够,否则察看他能否卖出那么多股票。// If buying, we check to see if we're within borrowing limits,// remembering to handle the problem of negative dividends  -// cash might already be less than the min.  In that case we// freeze the trader.  if (demand > 0.0) {    if (demand*trialprice > (cash - mincash))      {	if (cash - mincash > 0.0) {	  demand = (cash - mincash)/trialprice;	  slope[0] = -demand/trialprice;	}	else	  {	    demand = 0.0;	    slope[0] = 0.0;	  }      }  }// If selling, we check to make sure we have enough stock to sell  else if (demand < 0.0 && demand + position < minholding)    {      demand = minholding - position;      slope[0] = 0.0;    }  return demand;}/*"initForecasts. Creates BFCast objects (forecasts) and puts them  into an array called fCastList.  These are the "meat" of this  agent's functionality, as they are repeatedly updated, improved, and  tested in the remainder of the class.  Please note each BFagent has  a copy of the default params object called privateParams.  It can be  used to set individualized values of settings in BFParams for each  agent. That would allow true diversity! I don't see how that diversity  would be allowed for in the ASM-2.0."*/void initForecasts(){  //初始化自己所有的预测规则  int  sumspecificity = 0;  int i;  Forecast aForecast=new Forecast(privateParams.condbits);  int numfcasts;// Initialize our instance variables  //all instances of BFagent can use the same BFParams object.  //ASM-2.0 was written that way, something like:  // privateParams= params;  // That seemed fraught with danger, with all instances having  // read/write access to a global parameter object, so now I'm  // creating a copy that each agent can have and individualize.  //privateParams = [params copy: [self getZone]];  //If you want to customize privateParams, this is the spot!  numfcasts = privateParams.numfcasts;  //fcastList=[Array create: [self getZone] setCount: numfcasts];  avspecificity = 0.0;  gacount = 0;  variance = privateParams.initvar;  getPriceFromWorld();  getDividendFromWorld();  global_mean = price + dividend;  forecast = lforecast = global_mean;  // Initialize the forecasts, put them into Swarm Array  //keep the 0'th forecast in a  "know nothing" condition  //[fcastList atOffset: 0 put: [self createNewForecast]];  //fcastList.addElement(new Forecast(worldForAgent.NWORLDBITS));  //create rest of forecasts with random conditions  //初始化每条规则,主要让规则的if部分随机取0,1,2,then部分在允许范围内取值。    for(i = 0; i < numfcasts; i++){      aForecast=createNewForecast();      setConditionsRandomly(aForecast);      fcastList.addElement(aForecast); //put aForecast into Swarm array "fcastlist"     }/* Compute average specificity */  //pj: Here is the proper way to iterate over Swarm collections  //计算平均特异度  int size=fcastList.size();  for(i=0;i<size;i++){    aForecast=(Forecast)(fcastList.elementAt(i));    sumspecificity += aForecast.specificity;  }  avspecificity = (double) sumspecificity/(double)numfcasts;}/*"Creates a new forecast object (instance of BFCast), with all  condition bits set to 00 here, meaning "don't care.  It also sets  values for the other coefficients inside the BFCast.  This method is  accessed at several points throughout the BFagent class when new  forecasts are needed."*/Forecast createNewForecast(){  //新建一条规则  Forecast aForecast=new Forecast(privateParams.condbits);  //needed to set values of a,b,and c  //设置a,b,c系数的取值范围  double abase = privateParams.a_min + 0.5*(1.0-privateParams.subrange)*privateParams.a_range;  double bbase = privateParams.b_min + 0.5*(1.0-privateParams.subrange)*privateParams.b_range;  double cbase = privateParams.c_min + 0.5*(1.0-privateParams.subrange)*privateParams.c_range;  double asubrange = privateParams.subrange*privateParams.a_range;  double bsubrange = privateParams.subrange*privateParams.b_range;  double csubrange = privateParams.subrange*privateParams.c_range;  aForecast.a=abase + Math.random()*asubrange;  aForecast.b=bbase + Math.random()*bsubrange;  aForecast.c=cbase + Math.random()*csubrange;  aForecast.condbits=privateParams.condbits;  aForecast.nnulls=privateParams.nnulls;  aForecast.bitcost=privateParams.bitcost;  aForecast.forecast=0.0;  aForecast.lforecast=global_mean;  aForecast.variance=privateParams.newfcastvar;  //same as bfagent's init  aForecast.strength=0.0;  return aForecast;}/*"Take a forecast object and randomly change the bits that govern  which conditions it monitors.  This appears to be a piece of  functionality that could move to the BFCast class itself. There were  quite a few of these details floating around in BFagent at one time,  many are gone now."*///随机设置预测规则的if部分void setConditionsRandomly(Forecast fcastObject){  int bit;  double problist[];//概率列表,判断每个位是否设置为不在乎2  problist=new double[privateParams.condbits];  String conditions="";  getProbList(problist);// = double[privateParams.getProbListPtr];  for(bit=0; bit< privateParams.condbits; bit++){       if (Math.random() < problist[bit]){	  conditions+=String.valueOf((int)(Math.random()*2));	  fcastObject.incrSpecificity();	  fcastObject.updateSpecfactor();	}      else{          conditions+="2";      }    }    fcastObject.conditions=conditions;}void prepareForTrading()  /*" * Set up a new active list for this agent's forecasts, and compute the * coefficients pdcoeff and offset in the equation *	forecast = pdcoeff*(trialprice+dividend) + offset * * The active list of all the fcasts matching the present conditions is saved * for later updates. "*/{  //准备交易,根据当前的世界的编码信息,激活规则  double weight, countsum, forecastvar=0.0;  int mincount;  int nactive;  String myworld;  Forecast  aForecast=new Forecast(privateParams.condbits);  Forecast  bestForecast;  double maxstrength;  currentTime = getCurrentTime();  //如果满足条件,则激活遗传算法优化每一个规则  if (currentTime >= privateParams.firstgatime && Math.random() < privateParams.gaprob)    {      local.localasm.setStatus("正在执行遗传算法");      performGA();      activeList.removeAllElements();    }  //this saves a copy of the agent's last as lforecast.  lforecast = forecast;  //得到世界当前的编码  myworld = collectWorldData();  //根据编码激活规则  updateActiveList(myworld);  maxstrength = -1e50;  bestForecast = null;  nactive = 0;  mincount = privateParams.mincount;  //在激活的规则列表中找出适应度最高的规则  int size=activeList.size();  for(int i=0;i<size;i++){      aForecast=(Forecast)activeList.elementAt(i);      if(i==0&&bestForecast==null)bestForecast=aForecast;      aForecast.lastactive=currentTime;      if(aForecast.incrCount()>= mincount){	  double strength=aForecast.strength;	  ++nactive;	  if (strength > maxstrength||(strength<-1e50&&maxstrength==-1e50)){	      maxstrength = strength;	      bestForecast= aForecast;          }	}    }  //如果有规则被激活,则选择最好的规则作为参数  if (nactive>=1)  // meaning that at least some forecasts are active    {      pdcoeff = bestForecast.a;      offset = bestForecast.b*dividend + bestForecast.c;      if(privateParams.individual==1){       forecastvar = bestForecast.variance;      }else{        forecastvar = variance;      }    }  else  //如果没有规则被激活 meaning "nactive" zero, no forecasts are active    {      countsum = 0.0;      pdcoeff = 0.0;      double pdcoeff1=0;      double offset1=0;      offset = 0.0;      mincount = privateParams.mincount;      //针对每条规则计算加权平均的预测系数

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -